code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
|---|---|
const std = @import("std");
const zp = @import("zplay");
const dig = zp.deps.dig;
const fontawesome = dig.fontawesome;
var big_font: *dig.Font = undefined;
var small_font: *dig.Font = undefined;
fn init(ctx: *zp.Context) anyerror!void {
std.log.info("game init", .{});
// init imgui
try dig.init(ctx.window);
big_font = try dig.loadTTF(
"assets/msyh.ttf",
25,
dig.c.ImFontAtlas_GetGlyphRangesChineseFull(dig.getIO().*.Fonts),
);
small_font = try dig.loadTTF(
"assets/msyh.ttf",
22,
dig.c.ImFontAtlas_GetGlyphRangesChineseFull(dig.getIO().*.Fonts),
);
}
fn printSection(title: [:0]const u8, text: [:0]const u8) void {
dig.pushFont(big_font);
defer dig.popFont();
if (dig.collapsingHeader_TreeNodeFlags(title, null)) {
dig.pushFont(small_font);
dig.textWrapped(text.ptr);
dig.popFont();
}
}
fn loop(ctx: *zp.Context) void {
while (ctx.pollEvent()) |e| {
_ = dig.processEvent(e);
switch (e) {
.keyboard_event => |key| {
if (key.trigger_type == .up) {
switch (key.scan_code) {
.escape => ctx.kill(),
.f1 => ctx.toggleFullscreeen(null),
else => {},
}
}
},
.quit_event => ctx.kill(),
else => {},
}
}
ctx.graphics.clear(true, false, false, [4]f32{ 0.45, 0.55, 0.6, 1.0 });
dig.beginFrame();
defer dig.endFrame();
if (dig.begin("金刚经(上)", null, null)) {
printSection("第一品 法会因由分",
\\如是我闻,一时,佛在舍卫国祗树给孤独园,与大比丘众千二百五十人俱。尔时,世尊食时,著衣持钵,
\\入舍卫大城乞食。于其城中,次第乞已,还至本处。饭食讫,收衣钵,洗足已,敷座而坐。
);
printSection("第二品 善现启请分",
\\时,长老须菩提在大众中即从座起,偏袒右肩,右膝着地,合掌恭敬而白佛言:“希有!世尊!如来善护念
\\诸菩萨,善付嘱诸菩萨。世尊!善男子、善女人,发阿耨多罗三藐三菩提心,应云何住,云何降伏其心?
\\”佛言:“善哉,善哉。须菩提!如汝所说,如来善护念诸菩萨,善付嘱诸菩萨。汝今谛听!当为汝说:善
\\男子、善女人,发阿耨多罗三藐三菩提心,应如是住,如是降伏其心。”“唯然,世尊!愿乐欲闻。”
);
printSection("第三品 大乘正宗分",
\\佛告须菩提:“诸菩萨摩诃萨应如是降伏其心!所有一切众生之类:若卵生、若胎生、若湿生、若化生;若
\\有色、若无色;若有想、若无想、若非有想非无想,我皆令入无余涅盘而灭度之。如是灭度无量无数无边
\\众生,实无众生得灭度者。何以故?须菩提!若菩萨有我相、人相、众生相、寿者相,即非菩萨。”
);
printSection("第四品 妙行无住分",
\\“复次,须菩提!菩萨于法,应无所住,行于布施,所谓不住色布施,不住声香味触法布施。须菩提!菩萨
\\应如是布施,不住于相。何以故?若菩萨不住相布施,其福德不可思量。须菩提!于意云何?东方虚空可
\\思量不?”“不也,世尊!”“须菩提!南西北方四维上下虚空可思量不?”“不也,世尊!”“须菩提!菩萨无
\\住相布施,福德亦复如是不可思量。须菩提!菩萨但应如所教住。”
);
printSection("第五品 如理实见分",
\\“须菩提!于意云何?可以身相见如来不?”“不也,世尊!不可以身相得见如来。何以故?如来所说身相,
\\即非身相。”佛告须菩提:“凡所有相,皆是虚妄。若见诸相非相,则见如来。”
);
printSection("第六品 正信希有分",
\\须菩提白佛言:“世尊!颇有众生,得闻如是言说章句,生实信不?”佛告须菩提:“莫作是说。如来灭后,
\\后五百岁,有持戒修福者,于此章句能生信心,以此为实,当知是人不于一佛二佛三四五佛而种善根,已
\\于无量千万佛所种诸善根,闻是章句,乃至一念生净信者,须菩提!如来悉知悉见,是诸众生得如是无量
\\福德。何以故?是诸众生无复我相、人相、众生相、寿者相;无法相,亦无非法相。何以故?是诸众生若
\\心取相,则为著我人众生寿者。若取法相,即著我人众生寿者。何以故?若取非法相,即著我人众生寿者
\\,是故不应取法,不应取非法。以是义故,如来常说:‘汝等比丘,知我说法,如筏喻者;法尚应舍,何况
\\非法。’”
);
printSection("第七品 无得无说分",
\\“须菩提!于意云何?如来得阿耨多罗三藐三菩提耶?如来有所说法耶?”须菩提言:“如我解佛所说义,无
\\有定法名阿耨多罗三藐三菩提,亦无有定法,如来可说。何以故?如来所说法,皆不可取、不可说、非法
\\、非非法。所以者何?一切贤圣,皆以无为法而有差别。”
);
printSection("第八品 依法出生分",
\\“须菩提!于意云何?若人满三千大千世界七宝以用布施,是人所得福德,宁为多不?”须菩提言:“甚多,
\\世尊!何以故?是福德即非福德性,是故如来说福德多。”“若复有人,于此经中受持,乃至四句偈等,为
\\他人说,其福胜彼。何以故?须菩提!一切诸佛,及诸佛阿耨多罗三藐三菩提法,皆从此经出。须菩提!
\\所谓佛法者,即非佛法。”
);
printSection("第九品 一相无相分",
\\“须菩提!于意云何?须陀洹能作是念:‘我得须陀洹果’不?”须菩提言:“不也,世尊!何以故?须陀洹名
\\为入流,而无所入,不入色声香味触法,是名须陀洹。”“须菩提!于意云何?斯陀含能作是念:‘我得斯陀
\\含果’不?”须菩提言:不也,世尊!何以故?斯陀含名一往来,而实无往来,是名斯陀含。”“须菩提!于
\\意云何?阿那含能作是念:‘我得阿那含果’不?”须菩提言:“不也,世尊!何以故?阿那含名为不来,而实
\\无不来,是故名阿那含。”“须菩提!于意云何?阿罗汉能作是念,‘我得阿罗汉道’不?”须菩提言:“不也,
\\世尊!何以故?实无有法名阿罗汉。世尊!若阿罗汉作是念:‘我得阿罗汉道’,即为著我人众生寿者。世
\\尊!佛说我得无诤三昧,人中最为第一,是第一离欲阿罗汉。世尊,我不作是念:‘我是离欲阿罗汉’。世
\\尊!我若作是念:‘我得阿罗汉道’,世尊则不说须菩提是乐阿兰那行者!以须菩提实无所行,而名须菩提
\\是乐阿兰那行。
);
printSection("第十品 庄严净土分",
\\佛告须菩提:“于意云何?如来昔在然灯佛所,于法有所得不?”“不也,世尊!如来在然灯佛所,于法实无
\\所得。”“须菩提!于意云何?菩萨庄严佛土不?”“不也,世尊!何以故?庄严佛土者,即非庄严,是名庄
\\严。”“是故须菩提!诸菩萨摩诃萨应如是生清净心,不应住色生心,不应住声香味触法生心,应无所住而
\\生其心。须菩提!譬如有人,身如须弥山王,于意云何?是身为大不?”须菩提言:“甚大,世尊!何以故
\\?佛说非身,是名大身。”
);
printSection("第十一品 无为福胜分",
\\“须菩提!如恒河中所有沙数,如是沙等恒河,于意云何?是诸恒河沙宁为多不?”须菩提言:“甚多,世尊
\\!但诸恒河尚多无数,何况其沙。”“须菩提!我今实言告汝:若有善男子、善女人,以七宝满尔所恒河沙
\\数三千大千世界,以用布施,得福多不?”须菩提言:“甚多,世尊!”佛告须菩提:“若善男子、善女人,
\\于此经中,乃至受持四句偈等,为他人说,而此福德胜前福德。”
);
printSection("第十二品 尊重正教分",
\\“复次,须菩提!随说是经,乃至四句偈等,当知此处,一切世间、天人、阿修罗,皆应供养,如佛塔庙,
\\何况有人尽能受持读诵。须菩提!当知是人成就最上第一希有之法,若是经典所在之处,则为有佛,若尊
\\重弟子。”
);
printSection("第十三品 如法受持分",
\\尔时,须菩提白佛言:“世尊!当何名此经,我等云何奉持?”佛告须菩提:“是经名为《金刚般若波罗蜜》
\\,以是名字,汝当奉持。所以者何?须菩提!佛说般若波罗蜜,即非般若波罗蜜,是名般若波罗蜜。须菩
\\提!于意云何?如来有所说法不?”须菩提白佛言:“世尊!如来无所说。”“须菩提!于意云何?三千大千
\\世界所有微尘是为多不?”须菩提言:“甚多,世尊!”“须菩提!诸微尘,如来说非微尘,是名微尘。如来
\\说:世界,非世界,是名世界。须菩提!于意云何?可以三十二相见如来不?”“不也,世尊!不可以三十
\\二相得见如来。何以故?如来说:三十二相,即是非相,是名三十二相。”“须菩提!若有善男子、善女人
\\,以恒河沙等身命布施;若复有人,于此经中,乃至受持四句偈等,为他人说,其福甚多。”
);
printSection("第十四品 离相寂灭分",
\\尔时,须菩提闻说是经,深解义趣,涕泪悲泣,而白佛言:“希有,世尊!佛说如是甚深经典,我从昔来所
\\得慧眼,未曾得闻如是之经。世尊!若复有人得闻是经,信心清净,则生实相,当知是人,成就第一希有
\\功德。世尊!是实相者,即是非相,是故如来说名实相。世尊!我今得闻如是经典,信解受持不足为难,
\\若当来世,后五百岁,其有众生,得闻是经,信解受持,是人则为第一希有。
\\何以故?此人无我相、无人相、无众生相、无寿者相。所以者何?我相即是非相,人相、众生相、寿者相
\\即是非相。何以故?离一切诸相,则名诸佛。”佛告须菩提:“如是!如是!若复有人得闻是经,不惊、不
\\怖、不畏,当知是人甚为希有。何以故?须菩提!如来说第一波罗蜜,非第一波罗蜜,是名第一波罗蜜。
\\须菩提!忍辱波罗蜜,如来说非忍辱波罗蜜,是名忍辱波罗蜜。何以故?须菩提!如我昔为歌利王割截身
\\体,我于尔时,无我相、无人相、无众生相、无寿者相。何以故?
\\我于往昔节节支解时,若有我相、人相、众生相、寿者相,应生嗔恨。须菩提!又念过去于五百世作忍辱
\\仙人,于尔所世,无我相、无人相、无众生相、无寿者相。是故须菩提!菩萨应离一切相,发阿耨多罗三
\\藐三菩提心,不应住色生心,不应住声香味触法生心,应生无所住心。若心有住,则为非住。是故佛说:
\\‘菩萨心不应住色布施。’须菩提!菩萨为利益一切众生,应如是布施。如来说:一切诸相,即是非相。又说
\\:一切众生,即非众生。须菩提!如来是真语者、实语者、如语者、不诳语者、不异语者。须菩提!如来
\\所得法,此法无实无虚。须菩提!若菩萨心住于法而行布施,如人入暗,则无所见。若菩萨心不住法而行
\\布施,如人有目,日光明照,见种种色。须菩提!当来之世,若有善男子、善女人,能于此经受持读诵,
\\则为如来以佛智慧,悉知是人,悉见是人,皆得成就无量无边功德。”
);
printSection("第十五品 持经功德分",
\\“须菩提!若有善男子、善女人,初日分以恒河沙等身布施,中日分复以恒河沙等身布施,后日分亦以恒河
\\沙等身布施,如是无量百千万亿劫以身布施;若复有人,闻此经典,信心不逆,其福胜彼,何况书写、受
\\持、读诵、为人解说。须菩提!以要言之,是经有不可思议、不可称量、无边功德。如来为发大乘者说,
\\为发最上乘者说。若有人能受持读诵,广为人说,如来悉知是人,悉见是人,皆得成就不可量、不可称、
\\无有边、不可思议功德。如是人等,则为荷担如来阿耨多罗三藐三菩提。
\\何以故?须菩提!若乐小法者,著我见、人见、众生见、寿者见,则于此经,不能听受读诵、为人解说。
\\须菩提!在在处处,若有此经,一切世间、天、人、阿修罗,所应供养;当知此处则为是塔,皆应恭敬,
\\作礼围绕,以诸华香而散其处。”
);
printSection("第十六品 能净业障分",
\\“复次,须菩提!若善男子、善女人,受持读诵此经,若为人轻贱,是人先世罪业,应堕恶道,以今世人轻
\\贱故,先世罪业则为消灭,当得阿耨多罗三藐三菩提。”“须菩提!我念过去无量阿僧祗劫,于然灯佛前,
\\得值八百四千万亿那由他诸佛,悉皆供养承事,无空过者,若复有人, 于后末世,能受持读诵此经,所得
\\功德,于我所供养诸佛功德,百分不及一,千万亿分、乃至算数譬喻所不能及。须菩提!若善男子、善女
\\人,于后末世,有受持读诵此经,所得功德,我若具说者,或有人闻,心则狂乱,狐疑不信。须菩提!当
\\知是经义不可思议,果报亦不可思议。”
);
}
dig.end();
if (dig.begin("金刚经(下)", null, 0)) {
printSection("第十七品 究竟无我分",
\\尔时,须菩提白佛言:“世尊!善男子、善女人,发阿耨多罗三藐三菩提心,云何应住?云何降伏其心?
\\”佛告须菩提:“善男子、善女人,发阿耨多罗三藐三菩提心者,当生如是心,我应灭度一切众生。灭度一
\\切众生已,而无有一众生实灭度者。
\\何以故?须菩提!若菩萨有我相、人相、众生相、寿者相,则非菩萨。
\\所以者何?须菩提!实无有法发阿耨多罗三藐三菩提心者。”“须菩提!于意云何?如来于然灯佛所,有法
\\得阿耨多罗三藐三菩提不?”“不也,世尊!如我解佛所说义,佛于然灯佛所,无有法得阿耨多罗三藐三菩
\\提。”佛言:“如是!如是!须菩提!实无有法如来得阿耨多罗三藐三菩提。须菩提!若有法如来得阿耨多
\\罗三藐三菩提者,然灯佛则不与我授记:汝于来世,当得作佛,号释迦牟尼。以实无有法得阿耨多罗三藐
\\三菩提,是故然灯佛与我授记,作是言:‘汝于来世,当得作佛,号释迦牟尼。’
\\何以故?如来者,即诸法如义。若有人言:‘如来得阿耨多罗三藐三菩提’。须菩提!实无有法,佛得阿耨多
\\罗三藐三菩提。须菩提!如来所得阿耨多罗三藐三菩提,于是中无实无虚。是故如来说:一切法皆是佛法
\\。须菩提!所言一切法者,即非一切法,是故名一切法。须菩提!譬如人身长大。”须菩提言:“世尊!如
\\来说:人身长大,则为非大身,是名大身。”“须菩提!菩萨亦如是。若作是言:‘我当灭度无量众生’,则不
\\名菩萨。
\\何以故?须菩提!实无有法名为菩萨。是故佛说:一切法无我、无人、无众生、无寿者。须菩提!若菩萨
\\作是言,‘我当庄严佛土’,是不名菩萨。
\\何以故?如来说:庄严佛土者,即非庄严,是名庄严。须菩提!若菩萨通达无我法者,如来说名真是菩
\\萨。
);
printSection("第十八品 一体同观分",
\\“须菩提!于意云何?如来有肉眼不?”
\\“如是,世尊!如来有肉眼。”
\\“须菩提!于意云何?如来有天眼不?”
\\“如是,世尊!如来有天眼。”
\\“须菩提!于意云何?如来有慧眼不?”
\\“如是,世尊!如来有慧眼。”
\\“须菩提!于意云何?如来有法眼不?”
\\“如是,世尊!如来有法眼。”
\\“须菩提!于意云何?如来有佛眼不?”
\\“如是,世尊!如来有佛眼。”
\\“须菩提!于意云何?如恒河中所有沙,佛说是沙不?”
\\“如是,世尊!如来说是沙。”
\\“须菩提!于意云何?如一恒河中所有沙,有如是等恒河,是诸恒河所有沙数,佛世界如是,宁为多不?
\\”“甚多,世尊!”佛告须菩提:“尔所国土中,所有众生,若干种心,如来悉知。何以故?如来说:诸心皆
\\为非心,是名为心。所以者何?须菩提!过去心不可得,现在心不可得,未来心不可得。”
);
printSection("第十九品 法界通化分",
\\“须菩提!于意云何?若有人满三千大千世界七宝以用布施,是人以是因缘,得福多不?”“如是,世尊!此
\\人以是因缘,得福甚多。”“须菩提!若福德有实,如来不说得福德多;以福德无故,如来说得福德多。”
);
printSection("第二十品 离色离相分",
\\“须菩提!于意云何?佛可以具足色身见不?”“不也,世尊!如来不应以具足色身见。何以故?如来说:具
\\足色身,即非具足色身,是名具足色身。”“须菩提!于意云何?如来可以具足诸相见不?”“不也,世尊!
\\如来不应以具足诸相见。何以故?如来说:诸相具足,即非具足,是名诸相具足。”
);
printSection("第二十一品 非说所说分",
\\“须菩提!汝勿谓如来作是念:‘我当有所说法。’莫作是念,何以故?若人言:如来有所说法,即为谤佛,
\\不能解我所说故。须菩提!说法者,无法可说,是名说法。”尔时,慧命须菩提白佛言:“世尊!颇有众生
\\,于未来世,闻说是法,生信心不?”佛言:“须菩提!彼非众生,非不众生。何以故?须菩提!众生众生
\\者,如来说非众生,是名众生。”
);
printSection("第二十二品 无法可得分",
\\须菩提白佛言:“世尊!佛得阿耨多罗三藐三菩提,为无所得耶?”佛言:“如是,如是。须菩提!我于阿耨
\\多罗三藐三菩提乃至无有少法可得,是名阿耨多罗三藐三菩提。”
);
printSection("第二十三品 净心行善分",
\\复次,须菩提!是法平等,无有高下,是名阿耨多罗三藐三菩提;以无我、无人、无众生、无寿者,修一
\\切善法,即得阿耨多罗三藐三菩提。须菩提!所言善法者,如来说即非善法,是名善法。
);
printSection("第二十四品 福智无比分",
\\“须菩提!若三千大千世界中所有诸须弥山王,如是等七宝聚,有人持用布施;若人以此《般若波罗蜜经》
\\,乃至四句偈等,受持读诵、为他人说,于前福德百分不及一,百千万亿分,乃至算数譬喻所不能及。”
);
printSection("第二十五品 化无所化分",
\\“须菩提!于意云何?汝等勿谓如来作是念:‘我当度众生。’须菩提!莫作是念。何以故?实无有众生如来
\\度者。若有众生如来度者,如来则有我、人、众生、寿者。须菩提!如来说:‘有我者,则非有我,而凡夫
\\之人以为有我。’须菩提!凡夫者,如来说则非凡夫,是名凡夫。”
);
printSection("第二十六品 法身非相分",
\\“须菩提!于意云何?可以三十二相观如来不?”须菩提言:“如是!如是!以三十二相观如来。”佛言:“须
\\菩提!若以三十二相观如来者,转轮圣王则是如来。”须菩提白佛言:“世尊!如我解佛所说义,不应以三
\\十二相观如来。”尔时,世尊而说偈言:“若以色见我,以音声求我,是人行邪道,不能见如来”
);
printSection("第二十七品 无断无灭分",
\\“须菩提!汝若作是念:‘如来不以具足相故,得阿耨多罗三藐三菩提。’须菩提!莫作是念,‘如来不以具足
\\相故,得阿耨多罗三藐三菩提。’须菩提!汝若作是念,发阿耨多罗三藐三菩提心者,说诸法断灭。莫作是
\\念!何以故?发阿耨多罗三藐三菩提心者,于法不说断灭相。”
);
printSection("第二十八品 不受不贪分",
\\“须菩提!若菩萨以满恒河沙等世界七宝,持用布施;若复有人知一切法无我,得成于忍,此菩萨胜
\\前菩萨所得功德。何以故?须菩提!以诸菩萨不受福德故。”须菩提白佛言:“世尊!云何菩萨不受福德?
\\”“须菩提!菩萨所作福德,不应贪著,是故说不受福德。”
);
printSection("第二十九品 威仪寂净分",
\\“须菩提!若有人言:如来若来若去、若坐若卧,是人不解我所说义。何以故?如来者,无所从来,亦无所
\\去,故名如来。”
);
printSection("第三十品 一合理相分",
\\“须菩提!若善男子、善女人,以三千大千世界碎为微尘,于意云何?是微尘众宁为多不?”“甚多,世尊!
\\何以故?若是微尘众实有者,佛则不说是微尘众,所以者何?佛说:微尘众,即非微尘众,是名微尘众。
\\世尊!如来所说三千大千世界,则非世界,是名世界。何以故?若世界实有者,则是一合相。如来说:‘
\\一合相,则非一合相,是名一合相。’须菩提!一合相者,则是不可说,但凡夫之人贪著其事。”
);
printSection("第三十一品 知见不生分",
\\“须菩提!若人言:佛说我见、人见、众生见、寿者见。须菩提!于意云何?是人解我所说义不?”“不也,世
\\尊!是人不解如来所说义。何以故?世尊说:我见、人见、众生见、寿者见,即非我见、人见、众生见、
\\寿者见,是名我见、人见、众生见、寿者见。”“须菩提!发阿耨多罗三藐三菩提心者,于一切法,应如是
\\知,如是见,如是信解,不生法相。须菩提!所言法相者,如来说即非法相,是名法相。”
);
printSection("第三十二品 应化非真分",
\\“须菩提!若有人以满无量阿僧祗世界七宝持用布施,若有善男子、善女人发菩提心者,持于此经,乃至四
\\句偈等,受持读诵,为人演说,其福胜彼。云何为人演说,不取于相,如如不动。何以故?”“一切有为法
\\,如梦幻泡影,如露亦如电,应作如是观”佛说是经已,长老须菩提及诸比丘、比丘尼、优婆塞、优婆夷,
\\一切世间、天、人、阿修罗,闻佛所说,皆大欢喜,信受奉行。
);
}
dig.end();
}
fn quit(ctx: *zp.Context) void {
_ = ctx;
std.log.info("game quit", .{});
}
pub fn main() anyerror!void {
try zp.run(.{
.initFn = init,
.loopFn = loop,
.quitFn = quit,
.enable_resizable = true,
.enable_maximized = true,
});
}
|
examples/imgui_ttf.zig
|
const c = @import("c");
const intToError = @import("error.zig").intToError;
const errorToInt = @import("error.zig").errorToInt;
const Error = @import("error.zig").Error;
const Matrix = @import("types.zig").Matrix;
const BBox = @import("types.zig").BBox;
const Vector = @import("image.zig").Vector;
const Outline = @This();
handle: *c.FT_Outline,
pub fn numPoints(self: Outline) u15 {
return @intCast(u15, self.handle.*.n_points);
}
pub fn numContours(self: Outline) u15 {
return @intCast(u15, self.handle.*.n_contours);
}
pub fn points(self: Outline) []const Vector {
return self.handle.*.points[0..self.numPoints()];
}
pub fn tags(self: Outline) []const u8 {
return self.handle.tags[0..@intCast(u15, self.handle.n_points)];
}
pub fn contours(self: Outline) []const i16 {
return self.handle.*.contours[0..self.numContours()];
}
pub fn check(self: Outline) Error!void {
try intToError(c.FT_Outline_Check(self.handle));
}
pub fn transform(self: Outline, matrix: ?Matrix) void {
c.FT_Outline_Transform(self.handle, if (matrix) |m| &m else null);
}
pub fn bbox(self: Outline) Error!BBox {
var b: BBox = undefined;
try intToError(c.FT_Outline_Get_BBox(self.handle, &b));
return b;
}
pub fn Funcs(comptime Context: type) type {
return struct {
move_to: fn (ctx: Context, to: Vector) Error!void,
line_to: fn (ctx: Context, to: Vector) Error!void,
conic_to: fn (ctx: Context, control: Vector, to: Vector) Error!void,
cubic_to: fn (ctx: Context, control_0: Vector, control_1: Vector, to: Vector) Error!void,
shift: i32,
delta: i32,
};
}
pub fn FuncsWrapper(comptime Context: type) type {
return struct {
const Self = @This();
ctx: Context,
callbacks: Funcs(Context),
fn getSelf(ptr: ?*anyopaque) *Self {
return @ptrCast(*Self, @alignCast(@alignOf(Self), ptr));
}
pub fn move_to(to: [*c]const c.FT_Vector, ctx: ?*anyopaque) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.move_to(self.ctx, to.*)) |_|
0
else |err|
errorToInt(err);
}
pub fn line_to(to: [*c]const c.FT_Vector, ctx: ?*anyopaque) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.line_to(self.ctx, to.*)) |_|
0
else |err|
errorToInt(err);
}
pub fn conic_to(
control: [*c]const c.FT_Vector,
to: [*c]const c.FT_Vector,
ctx: ?*anyopaque,
) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.conic_to(
self.ctx,
control.*,
to.*,
)) |_|
0
else |err|
errorToInt(err);
}
pub fn cubic_to(
control_0: [*c]const c.FT_Vector,
control_1: [*c]const c.FT_Vector,
to: [*c]const c.FT_Vector,
ctx: ?*anyopaque,
) callconv(.C) c_int {
const self = getSelf(ctx);
return if (self.callbacks.cubic_to(
self.ctx,
control_0.*,
control_1.*,
to.*,
)) |_|
0
else |err|
errorToInt(err);
}
};
}
pub fn decompose(self: Outline, ctx: anytype, callbacks: Funcs(@TypeOf(ctx))) Error!void {
var wrapper = FuncsWrapper(@TypeOf(ctx)){ .ctx = ctx, .callbacks = callbacks };
try intToError(c.FT_Outline_Decompose(
self.handle,
&.{
.move_to = @TypeOf(wrapper).move_to,
.line_to = @TypeOf(wrapper).line_to,
.conic_to = @TypeOf(wrapper).conic_to,
.cubic_to = @TypeOf(wrapper).cubic_to,
.shift = callbacks.shift,
.delta = callbacks.delta,
},
&wrapper,
));
}
|
freetype/src/freetype/Outline.zig
|
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const panic = std.debug.panic;
const yeti = @import("yeti");
const List = yeti.List;
test "list push" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer expect(!gpa.deinit()) catch panic("MEMORY LEAK!!!", .{});
var list = List(i64, .{}).init(gpa.allocator());
defer list.deinit();
try expectEqual(list.len, 0);
try list.append(4);
try expectEqual(list.len, 1);
try expectEqual(list.slice()[0], 4);
try list.append(10);
try expectEqual(list.len, 2);
try expectEqual(list.slice()[0], 4);
try expectEqual(list.slice()[1], 10);
try list.append(7);
try expectEqual(list.len, 3);
try expectEqual(list.slice()[0], 4);
try expectEqual(list.slice()[1], 10);
try expectEqual(list.slice()[2], 7);
const items = list.slice();
try expectEqual(items.len, 3);
}
test "list fill initial_capacity" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer expect(!gpa.deinit()) catch panic("MEMORY LEAK!!!", .{});
var list = List(u64, .{}).init(gpa.allocator());
defer list.deinit();
const fill = 32;
var i: u64 = 0;
while (i < fill) : (i += 1) {
try list.append(i);
}
const items = list.slice();
try expectEqual(items.len, fill);
i = 0;
while (i < fill) : (i += 1) {
try expectEqual(items[i], i);
}
}
test "list fill double initial_capacity" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer expect(!gpa.deinit()) catch panic("MEMORY LEAK!!!", .{});
var list = List(u64, .{}).init(gpa.allocator());
defer list.deinit();
const fill = 64;
var i: u64 = 0;
while (i < fill) : (i += 1) {
try list.append(i);
}
const items = list.slice();
try expectEqual(items.len, fill);
i = 0;
while (i < fill) : (i += 1) {
try expectEqual(items[i], i);
}
}
test "list appendSlice" {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer expect(!gpa.deinit()) catch panic("MEMORY LEAK!!!", .{});
var list = List(u8, .{ .initial_capacity = 2 }).init(gpa.allocator());
defer list.deinit();
try list.appendSlice("hello");
try expectEqual(list.len, 5);
try expectEqual(list.items.len, 8);
try expectEqualStrings(list.slice(), "hello");
try list.appendSlice(" world");
try expectEqual(list.len, 11);
try expectEqual(list.items.len, 20);
try expectEqualStrings(list.slice(), "hello world");
}
|
src/tests/test_list.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const nvg = @import("nanovg");
const gui = @import("../gui.zig");
const Rect = @import("../geometry.zig").Rect;
const Scrollbar = @This();
widget: gui.Widget,
allocator: Allocator,
orientation: gui.Orientation,
mouse_offset: f32 = 0,
value: f32 = 0,
min_value: f32 = 0,
max_value: f32 = 0,
decrement_button: *gui.Button,
increment_button: *gui.Button,
thumb_button: *gui.Button,
onChangedFn: ?fn (*Self) void = null,
pub const button_size = 16;
const scroll_speed = 5;
const Self = @This();
pub fn init(allocator: Allocator, rect: Rect(f32), orientation: gui.Orientation) !*Self {
var self = try allocator.create(Self);
self.* = Self{
.widget = gui.Widget.init(allocator, rect),
.allocator = allocator,
.orientation = orientation,
.increment_button = try gui.Button.init(allocator, Rect(f32).make(0, 0, button_size, button_size), ""),
.decrement_button = try gui.Button.init(allocator, Rect(f32).make(0, 0, button_size, button_size), ""),
.thumb_button = try gui.Button.init(allocator, Rect(f32).make(0, 0, button_size, button_size), ""),
};
self.widget.onResizeFn = onResize;
self.widget.onMouseMoveFn = onMouseMove;
self.widget.onMouseDownFn = onMouseDown;
self.widget.onMouseUpFn = onMouseUp;
self.widget.drawFn = draw;
self.thumb_button.widget.onMouseDownFn = thumbMouseDown;
self.thumb_button.widget.onMouseMoveFn = thumbMouseMove;
self.thumb_button.widget.focus_policy = gui.FocusPolicy.none();
self.decrement_button.onClickFn = decrementClick;
self.decrement_button.widget.focus_policy = gui.FocusPolicy.none();
self.decrement_button.auto_repeat_interval = 10;
self.decrement_button.iconFn = if (self.orientation == .vertical)
gui.drawSmallArrowUp
else
gui.drawSmallArrowLeft;
self.decrement_button.icon_x = 5;
self.decrement_button.icon_y = 5;
self.increment_button.onClickFn = incrementClick;
self.increment_button.widget.focus_policy = gui.FocusPolicy.none();
self.increment_button.auto_repeat_interval = 10;
self.increment_button.iconFn = if (self.orientation == .vertical)
gui.drawSmallArrowDown
else
gui.drawSmallArrowRight;
self.increment_button.icon_x = 5;
self.increment_button.icon_y = 5;
try self.widget.addChild(&self.decrement_button.widget);
try self.widget.addChild(&self.increment_button.widget);
try self.widget.addChild(&self.thumb_button.widget);
self.updateLayout();
return self;
}
pub fn deinit(self: *Self) void {
self.decrement_button.deinit();
self.increment_button.deinit();
self.thumb_button.deinit();
self.widget.deinit();
self.allocator.destroy(self);
}
pub fn setValue(self: *Self, value: f32) void {
const clamped_value = std.math.clamp(value, self.min_value, self.max_value);
if (clamped_value != self.value) {
self.value = clamped_value;
self.updateThumbPosition();
if (self.onChangedFn) |onChanged| onChanged(self);
}
}
pub fn setMaxValue(self: *Self, max_value: f32) void {
self.max_value = std.math.max(0, max_value);
self.setValue(self.value); // clamps
self.updateThumbSize();
self.updateThumbPosition();
}
fn decrementClick(button: *gui.Button) void {
const self = @fieldParentPtr(Self, "widget", button.widget.parent.?);
self.setValue(self.value - scroll_speed);
}
fn incrementClick(button: *gui.Button) void {
const self = @fieldParentPtr(Self, "widget", button.widget.parent.?);
self.setValue(self.value + scroll_speed);
}
fn updateThumbPosition(self: *Self) void {
const rect = self.widget.getRect();
const thumb_rect = self.thumb_button.widget.getRect();
const range = (if (self.orientation == .vertical)
rect.h - thumb_rect.h
else
rect.w - thumb_rect.w) - 2 * button_size + 2;
const pos = button_size - 1 + self.value * range / self.max_value;
if (self.orientation == .vertical) {
self.thumb_button.widget.relative_rect.y = pos;
} else {
self.thumb_button.widget.relative_rect.x = pos;
}
}
fn updateThumbSize(self: *Self) void {
const view = if (self.orientation == .vertical)
self.widget.relative_rect.h
else
self.widget.relative_rect.w;
const content = view + self.max_value;
const track = view - 2 * button_size + 2;
const thumb = track * view / content;
if (self.orientation == .vertical) {
self.thumb_button.widget.setSize(button_size, thumb);
} else {
self.thumb_button.widget.setSize(thumb, button_size);
}
}
fn thumbMouseDown(widget: *gui.Widget, event: *const gui.MouseEvent) void {
gui.Button.onMouseDown(widget, event);
const self = @fieldParentPtr(Self, "widget", widget.parent.?);
self.mouse_offset = if (self.orientation == .vertical) event.y else event.x;
}
fn thumbMouseMove(widget: *gui.Widget, event: *const gui.MouseEvent) void {
if (event.isButtonPressed(.left)) {
const self = @fieldParentPtr(Self, "widget", widget.parent.?);
if (self.orientation == .vertical) {
const y = widget.relative_rect.y + event.y - self.mouse_offset;
const max_y = self.widget.relative_rect.h - (button_size - 1) - widget.relative_rect.h;
widget.relative_rect.y = std.math.clamp(y, button_size - 1, max_y);
const max_widget = max_y - (button_size - 1);
self.setValue(self.max_value * (widget.relative_rect.y - (button_size - 1)) / max_widget);
} else {
const x = widget.relative_rect.x + event.x - self.mouse_offset;
const max_x = self.widget.relative_rect.w - button_size + 1 - widget.relative_rect.w;
widget.relative_rect.x = std.math.clamp(x, button_size - 1, max_x);
const max_widget = max_x - (button_size - 1);
self.setValue(self.max_value * (widget.relative_rect.x - (button_size - 1)) / max_widget);
}
}
}
fn onResize(widget: *gui.Widget, event: *const gui.ResizeEvent) void {
_ = event;
const self = @fieldParentPtr(Self, "widget", widget);
self.updateLayout();
}
fn updateLayout(self: *Self) void {
const rect = self.widget.relative_rect;
if (self.orientation == .vertical) {
self.increment_button.widget.relative_rect.y = rect.h - button_size;
self.thumb_button.widget.relative_rect.y = std.math.max(button_size - 1, self.thumb_button.widget.relative_rect.y);
} else {
self.increment_button.widget.relative_rect.x = rect.w - button_size;
self.thumb_button.widget.relative_rect.x = std.math.max(button_size - 1, self.thumb_button.widget.relative_rect.x);
}
self.updateThumbSize();
self.updateThumbPosition();
}
fn onMouseMove(widget: *gui.Widget, event: *const gui.MouseEvent) void {
const self = @fieldParentPtr(Self, "widget", widget);
_ = self;
_ = event;
}
fn onMouseDown(widget: *gui.Widget, event: *const gui.MouseEvent) void {
const self = @fieldParentPtr(Self, "widget", widget);
const rect = widget.getRect();
_ = self;
_ = rect;
_ = event;
}
fn onMouseUp(widget: *gui.Widget, event: *const gui.MouseEvent) void {
const self = @fieldParentPtr(Self, "widget", widget);
_ = self;
_ = event;
}
fn draw(widget: *gui.Widget, vg: nvg) void {
//const self = @fieldParentPtr(Self, "widget", widget);
const rect = widget.relative_rect;
// background
vg.beginPath();
vg.rect(rect.x + 1, rect.y + 1, rect.w - 2, rect.h - 2);
vg.fillColor(gui.theme_colors.shadow);
vg.fill();
// border
vg.beginPath();
vg.rect(rect.x + 0.5, rect.y + 0.5, rect.w - 1, rect.h - 1);
vg.strokeColor(gui.theme_colors.border);
vg.stroke();
widget.drawChildren(vg);
}
|
src/gui/widgets/Scrollbar.zig
|
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const builtin = @import("builtin");
test "cmpxchg" {
try testCmpxchg();
comptime try testCmpxchg();
}
fn testCmpxchg() !void {
var x: i32 = 1234;
if (@cmpxchgWeak(i32, &x, 99, 5678, .SeqCst, .SeqCst)) |x1| {
try expect(x1 == 1234);
} else {
@panic("cmpxchg should have failed");
}
while (@cmpxchgWeak(i32, &x, 1234, 5678, .SeqCst, .SeqCst)) |x1| {
try expect(x1 == 1234);
}
try expect(x == 5678);
try expect(@cmpxchgStrong(i32, &x, 5678, 42, .SeqCst, .SeqCst) == null);
try expect(x == 42);
}
test "fence" {
var x: i32 = 1234;
@fence(.SeqCst);
x = 5678;
}
test "atomicrmw and atomicload" {
var data: u8 = 200;
try testAtomicRmw(&data);
try expect(data == 42);
try testAtomicLoad(&data);
}
fn testAtomicRmw(ptr: *u8) !void {
const prev_value = @atomicRmw(u8, ptr, .Xchg, 42, .SeqCst);
try expect(prev_value == 200);
comptime {
var x: i32 = 1234;
const y: i32 = 12345;
try expect(@atomicLoad(i32, &x, .SeqCst) == 1234);
try expect(@atomicLoad(i32, &y, .SeqCst) == 12345);
}
}
fn testAtomicLoad(ptr: *u8) !void {
const x = @atomicLoad(u8, ptr, .SeqCst);
try expect(x == 42);
}
test "cmpxchg with ptr" {
var data1: i32 = 1234;
var data2: i32 = 5678;
var data3: i32 = 9101;
var x: *i32 = &data1;
if (@cmpxchgWeak(*i32, &x, &data2, &data3, .SeqCst, .SeqCst)) |x1| {
try expect(x1 == &data1);
} else {
@panic("cmpxchg should have failed");
}
while (@cmpxchgWeak(*i32, &x, &data1, &data3, .SeqCst, .SeqCst)) |x1| {
try expect(x1 == &data1);
}
try expect(x == &data3);
try expect(@cmpxchgStrong(*i32, &x, &data3, &data2, .SeqCst, .SeqCst) == null);
try expect(x == &data2);
}
test "cmpxchg with ignored result" {
var x: i32 = 1234;
_ = @cmpxchgStrong(i32, &x, 1234, 5678, .Monotonic, .Monotonic);
try expect(5678 == x);
}
test "128-bit cmpxchg" {
try test_u128_cmpxchg();
comptime try test_u128_cmpxchg();
}
fn test_u128_cmpxchg() !void {
if (builtin.zig_is_stage2) {
if (builtin.stage2_arch != .x86_64) return error.SkipZigTest;
if (!builtin.stage2_x86_cx16) return error.SkipZigTest;
} else {
if (builtin.cpu.arch != .x86_64) return error.SkipZigTest;
if (comptime !std.Target.x86.featureSetHas(builtin.cpu.features, .cx16)) return error.SkipZigTest;
}
var x: u128 = 1234;
if (@cmpxchgWeak(u128, &x, 99, 5678, .SeqCst, .SeqCst)) |x1| {
try expect(x1 == 1234);
} else {
@panic("cmpxchg should have failed");
}
while (@cmpxchgWeak(u128, &x, 1234, 5678, .SeqCst, .SeqCst)) |x1| {
try expect(x1 == 1234);
}
try expect(x == 5678);
try expect(@cmpxchgStrong(u128, &x, 5678, 42, .SeqCst, .SeqCst) == null);
try expect(x == 42);
}
var a_global_variable = @as(u32, 1234);
test "cmpxchg on a global variable" {
_ = @cmpxchgWeak(u32, &a_global_variable, 1234, 42, .Acquire, .Monotonic);
try expect(a_global_variable == 42);
}
test "atomic load and rmw with enum" {
const Value = enum(u8) { a, b, c };
var x = Value.a;
try expect(@atomicLoad(Value, &x, .SeqCst) != .b);
_ = @atomicRmw(Value, &x, .Xchg, .c, .SeqCst);
try expect(@atomicLoad(Value, &x, .SeqCst) == .c);
try expect(@atomicLoad(Value, &x, .SeqCst) != .a);
try expect(@atomicLoad(Value, &x, .SeqCst) != .b);
}
|
test/behavior/atomics.zig
|
const std = @import("std");
usingnamespace @import("common.zig");
const parser = @import("../main.zig").parser.client;
const hzzp = @import("hzzp");
const base64 = std.base64;
const ascii = std.ascii;
const math = std.math;
const rand = std.rand;
const time = std.time;
const mem = std.mem;
const Sha1 = std.crypto.hash.Sha1;
const assert = std.debug.assert;
pub fn create(buffer: []u8, reader: anytype, writer: anytype) BaseClient(@TypeOf(reader), @TypeOf(writer)) {
assert(buffer.len >= 16);
return BaseClient(@TypeOf(reader), @TypeOf(writer)).init(buffer, reader, writer);
}
pub const websocket_guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
pub const handshake_key_length = 16;
pub const handshake_key_length_b64 = base64.standard.Encoder.calcSize(handshake_key_length);
pub const encoded_key_length_b64 = base64.standard.Encoder.calcSize(Sha1.digest_length);
fn checkHandshakeKey(original: []const u8, received: []const u8) bool {
var hash = Sha1.init(.{});
hash.update(original);
hash.update(websocket_guid);
var hashed_key: [Sha1.digest_length]u8 = undefined;
hash.final(&hashed_key);
var encoded: [encoded_key_length_b64]u8 = undefined;
_ = base64.standard.Encoder.encode(&encoded, &hashed_key);
return mem.eql(u8, &encoded, received);
}
pub fn BaseClient(comptime Reader: type, comptime Writer: type) type {
const ParserType = parser.ClientParser(Reader);
const HttpClient = hzzp.base.client.BaseClient(Reader, Writer);
return struct {
const Self = @This();
prng: rand.DefaultPrng,
handshake_client: HttpClient,
handshake_key: [handshake_key_length_b64]u8 = undefined,
read_buffer: []u8,
parser: ParserType,
writer: Writer,
handshaken: bool = false,
current_mask: ?u32 = null,
mask_index: usize = 0,
payload_size: usize = 0,
payload_index: usize = 0,
// Whether a reader is currently using the read_buffer. if true, parser.next should NOT be called since the
// reader expects all of the data.
self_contained: bool = false,
pub fn init(buffer: []u8, input: Reader, output: Writer) Self {
const rand_seed = @truncate(u64, @bitCast(u128, time.nanoTimestamp()));
return .{
.prng = rand.DefaultPrng.init(rand_seed),
.handshake_client = HttpClient.init(buffer, input, output),
.parser = ParserType.init(buffer, input),
.read_buffer = buffer,
.writer = output,
};
}
pub fn handshakeStart(self: *Self, path: []const u8) Writer.Error!void {
var raw_key: [handshake_key_length]u8 = undefined;
self.prng.random.bytes(&raw_key);
_ = base64.standard_encoder.encode(&self.handshake_key, &raw_key);
try self.handshake_client.writeStatusLine("GET", path);
try self.handshake_client.writeHeaderValue("Connection", "Upgrade");
try self.handshake_client.writeHeaderValue("Upgrade", "websocket");
try self.handshake_client.writeHeaderValue("Sec-WebSocket-Version", "13");
try self.handshake_client.writeHeaderValue("Sec-WebSocket-Key", &self.handshake_key);
}
pub fn handshakeAddHeaderValue(self: *Self, name: []const u8, value: []const u8) Writer.Error!void {
return self.handshake_client.writeHeaderValue(name, value);
}
pub fn handshakeAddHeaderValueFormat(self: *Self, name: []const u8, comptime format: []const u8, args: anytype) Writer.Error!void {
return self.handshake_client.writeHeaderFormat(name, format, args);
}
pub const HandshakeError = error{ WrongResponse, InvalidConnectionHeader, FailedChallenge } || HttpClient.NextError || Writer.Error;
pub fn handshakeFinish(self: *Self) HandshakeError!void {
try self.handshake_client.finishHeaders();
var got_upgrade_header: bool = false;
var got_accept_header: bool = false;
while (try self.handshake_client.next()) |event| {
switch (event) {
.status => |status| {
if (status.code != 101) return error.WrongResponse;
},
.header => |header| {
if (ascii.eqlIgnoreCase(header.name, "connection")) {
got_upgrade_header = true;
if (!ascii.eqlIgnoreCase(header.value, "upgrade")) {
return error.InvalidConnectionHeader;
}
} else if (ascii.eqlIgnoreCase(header.name, "sec-websocket-accept")) {
got_accept_header = true;
if (!checkHandshakeKey(&self.handshake_key, header.value)) {
return error.FailedChallenge;
}
}
},
.head_done => break,
.payload => unreachable,
.skip => {},
.end => break,
}
}
self.handshaken = true;
}
pub fn writeHeader(self: *Self, header: MessageHeader) Writer.Error!void {
assert(self.handshaken);
var bytes: [2]u8 = undefined;
bytes[0] = @enumToInt(header.opcode);
bytes[1] = 0;
if (header.fin) bytes[0] |= 0x80;
if (header.rsv1) bytes[0] |= 0x40;
if (header.rsv2) bytes[0] |= 0x20;
if (header.rsv3) bytes[0] |= 0x10;
const mask = header.mask orelse self.prng.random.int(u32);
bytes[1] |= 0x80;
if (header.length < 126) {
bytes[1] |= @truncate(u8, header.length);
try self.writer.writeAll(&bytes);
} else if (header.length < 0x10000) {
bytes[1] |= 126;
try self.writer.writeAll(&bytes);
var len: [2]u8 = undefined;
mem.writeIntBig(u16, &len, @truncate(u16, header.length));
try self.writer.writeAll(&len);
} else {
bytes[1] |= 127;
try self.writer.writeAll(&bytes);
var len: [8]u8 = undefined;
mem.writeIntBig(u64, &len, header.length);
try self.writer.writeAll(&len);
}
var mask_bytes: [4]u8 = undefined;
mem.writeIntLittle(u32, &mask_bytes, mask);
try self.writer.writeAll(&mask_bytes);
self.current_mask = mask;
self.mask_index = 0;
}
pub fn writeChunkRaw(self: *Self, payload: []const u8) Writer.Error!void {
try self.writer.writeAll(payload);
}
const mask_buffer_size = 1024;
pub fn writeChunk(self: *Self, payload: []const u8) Writer.Error!void {
if (self.current_mask) |mask| {
var buffer: [mask_buffer_size]u8 = undefined;
var index: usize = 0;
for (payload) |c, i| {
buffer[index] = c ^ parser.extractMaskByte(mask, i + self.mask_index);
index += 1;
if (index == mask_buffer_size) {
try self.writer.writeAll(&buffer);
index = 0;
}
}
if (index > 0) {
try self.writer.writeAll(buffer[0..index]);
}
self.mask_index += payload.len;
} else unreachable;
}
pub fn next(self: *Self) ParserType.NextError!?Event {
assert(self.handshaken);
assert(!self.self_contained);
return self.parser.next();
}
pub const ReadNextError = ParserType.NextError;
pub fn readNextChunk(self: *Self, buffer: []u8) ReadNextError!?ChunkEvent {
if (self.parser.state != .chunk) return null;
assert(self.handshaken);
assert(!self.self_contained);
if (try self.parser.next()) |event| {
switch (event) {
.chunk => |chunk| return chunk,
.header => unreachable,
}
}
}
pub fn flushReader(self: *Self) ReadNextError!void {
var buffer: [256]u8 = undefined;
while (self.self_contained) {
_ = try self.readNextChunkBuffer(&buffer);
}
}
pub fn readNextChunkBuffer(self: *Self, buffer: []u8) ReadNextError!usize {
if (self.payload_index >= self.payload_size) {
if (self.parser.state != .chunk) {
self.self_contained = false;
return 0;
}
self.self_contained = true;
if (try self.parser.next()) |event| {
switch (event) {
.chunk => |chunk| {
self.payload_index = 0;
self.payload_size = chunk.data.len;
},
.header => unreachable,
}
} else unreachable;
}
const start = self.payload_index;
const size = std.math.min(buffer.len, self.payload_size - start);
const end = start + size;
mem.copy(u8, buffer[0..size], self.read_buffer[start..end]);
self.payload_index = end;
return size;
}
pub const PayloadReader = std.io.Reader(*Self, ReadNextError, readNextChunkBuffer);
pub fn reader(self: *Self) PayloadReader {
assert(self.parser.state == .chunk);
return .{ .context = self };
}
};
}
const testing = std.testing;
test "attempt echo on echo.websocket.org" {
if (std.builtin.os.tag == .windows) return error.SkipZigTest;
var socket = try std.net.tcpConnectToHost(testing.allocator, "echo.websocket.org", 80);
defer socket.close();
var buffer: [4096]u8 = undefined;
var client = create(&buffer, socket.reader(), socket.writer());
try client.handshakeStart("/");
try client.handshakeAddHeaderValue("Host", "echo.websocket.org");
try client.handshakeFinish();
try client.writeHeader(.{
.opcode = .Binary,
.length = 4,
});
try client.writeChunk("test");
var header = (try client.next()).?;
testing.expect(header == .header);
testing.expect(header.header.fin == true);
testing.expect(header.header.rsv1 == false);
testing.expect(header.header.rsv2 == false);
testing.expect(header.header.rsv3 == false);
testing.expect(header.header.opcode == .Binary);
testing.expect(header.header.length == 4);
testing.expect(header.header.mask == null);
var payload = (try client.next()).?;
testing.expect(payload == .chunk);
testing.expect(payload.chunk.final == true);
testing.expect(mem.eql(u8, payload.chunk.data, "test"));
}
test "reader() and flushReader()" {
if (std.builtin.os.tag == .windows) return error.SkipZigTest;
var socket = try std.net.tcpConnectToHost(testing.allocator, "echo.websocket.org", 80);
defer socket.close();
const payload = "0123456789ABCDEF" ** 32;
// Intentionally smaller buffer to require multiple chunks
var buffer: [payload.len / 2]u8 = undefined;
var client = create(&buffer, socket.reader(), socket.writer());
try client.handshakeStart("/");
try client.handshakeAddHeaderValue("Host", "echo.websocket.org");
try client.handshakeFinish();
try client.writeHeader(.{
.opcode = .Binary,
.length = payload.len,
});
try client.writeChunk(payload);
var header = (try client.next()).?;
testing.expect(header == .header);
testing.expect(header.header.fin == true);
testing.expect(header.header.rsv1 == false);
testing.expect(header.header.rsv2 == false);
testing.expect(header.header.rsv3 == false);
testing.expect(header.header.opcode == .Binary);
testing.expect(header.header.length == payload.len);
testing.expect(header.header.mask == null);
testing.expect(client.parser.state == .chunk);
const reader = client.reader();
testing.expect((try reader.readByte()) == '0');
testing.expect((try reader.readByte()) == '1');
testing.expect((try reader.readByte()) == '2');
try client.flushReader();
testing.expectError(error.EndOfStream, reader.readByte());
testing.expect(client.parser.state != .chunk);
// Allow multiple flushes to make cleanup easier
try client.flushReader();
}
|
src/base/client.zig
|
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const Paper = struct {
const Fold = struct {
axis: u1,
pos: u11,
};
points: std.AutoHashMap([2]u11, bool),
folds: []*Fold,
next: usize,
bb: [2]u11,
alloc: std.mem.Allocator,
pub fn init(alloc: std.mem.Allocator, inp: []const u8) !*Paper {
var paper = try alloc.create(Paper);
paper.alloc = alloc;
paper.next = 0;
var chunks = std.mem.split(u8, inp, "\n\n");
var b = try std.BoundedArray(u11, 2048).init(0);
var ints = try aoc.BoundedInts(u11, &b, chunks.next().?);
var points = std.AutoHashMap([2]u11, bool).init(alloc);
var i: usize = 0;
while (i < ints.len) : (i += 2) {
try points.put([2]u11{ ints[i], ints[i + 1] }, true);
}
var folds = std.ArrayList(*Fold).init(alloc);
var foldsChunk = chunks.next().?;
var n: u11 = 0;
var axis: u1 = 0;
i = 0;
while (i < foldsChunk.len) : (i += 1) {
switch (foldsChunk[i]) {
'x' => {
axis = 0;
},
'y' => {
axis = 1;
},
'0'...'9' => {
n = 10 * n + @as(u11, foldsChunk[i] - '0');
},
'\n' => {
var f = try alloc.create(Fold);
f.axis = axis;
f.pos = n;
try folds.append(f);
n = 0;
},
else => {},
}
}
paper.folds = folds.toOwnedSlice();
//aoc.print("{any}\n", .{paper}) catch unreachable;
paper.points = points;
return paper;
}
pub fn deinit(self: *Paper) void {
for (self.folds) |e| {
self.alloc.destroy(e);
}
self.alloc.free(self.folds);
self.points.deinit();
self.alloc.destroy(self);
}
pub fn nextFold(self: *Paper) !usize {
var fold = self.folds[self.next];
var it = self.points.keyIterator();
while (it.next()) |k| {
var np: [2]u11 = k.*;
if (np[fold.axis] > fold.pos) {
np[fold.axis] = fold.pos - (np[fold.axis] - fold.pos);
_ = self.points.remove(k.*);
if (!self.points.contains(np)) {
try self.points.put(np, true);
}
}
}
self.bb[fold.axis] = fold.pos;
self.next += 1;
return self.points.count();
}
pub fn part1(self: *Paper) !usize {
return self.nextFold();
}
pub fn part2(self: *Paper) ![]const u8 {
while (self.next < self.folds.len) {
_ = try self.nextFold();
}
var s = try self.alloc.alloc(u8, @as(usize, self.bb[0] + 1) * @as(usize, self.bb[1]));
std.mem.set(u8, s, ' ');
var y: u11 = 0;
while (y < self.bb[1]) : (y += 1) {
var x: u11 = 0;
while (x < self.bb[0]) : (x += 1) {
if (self.points.contains([2]u11{ x, y })) {
s[x + y * (self.bb[0] + 1)] = '#';
}
}
s[x + y * (self.bb[0] + 1)] = '\n';
}
return s;
}
};
test "part1" {
var t1 = try Paper.init(aoc.talloc, aoc.test1file);
defer t1.deinit();
try aoc.assertEq(@as(usize, 10), try t1.part1());
var r = try Paper.init(aoc.talloc, aoc.inputfile);
defer r.deinit();
try aoc.assertEq(@as(usize, 4691), try r.part1());
}
test "part2" {
var t1 = try Paper.init(aoc.talloc, aoc.test1file);
defer t1.deinit();
try aoc.assertStrEq("bar", try t1.part2());
var r = try Paper.init(aoc.talloc, aoc.inputfile);
defer r.deinit();
try aoc.assertStrEq("foo", try r.part2());
}
fn day13(inp: []const u8, bench: bool) anyerror!void {
var paper = try Paper.init(aoc.halloc, inp);
var p1 = try paper.part1();
var p2 = try paper.part2();
if (!bench) {
try aoc.print("Part 1: {}\nPart 2:\n{s}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day13);
}
|
2021/13/aoc.zig
|
const std = @import("std");
const palettes = @import("palettes.zig");
const assert = std.debug.assert;
/// Format `fmt` with ANSI color codes.
/// 16-color format:
/// - `<fg.black>`
/// - `<bg.blue>`
/// 256-color format:
/// - `<fg.88>`
/// - `<bg.255>`
/// Modes:
/// - `<b>`: Bold
/// - `<d>`: Dim
/// - `<r>`: Reset
pub fn colorFormat(comptime fmt: []const u8) []const u8 {
comptime var new_fmt: [fmt.len * 4]u8 = undefined;
comptime var new_fmt_i: usize = 0;
// TODO: Stress test to see if the line below is necessary
@setEvalBranchQuota(9999);
comptime var i: usize = 0;
comptime while (i < fmt.len) {
const c = fmt[i];
switch (c) {
'>' => {
i += 1;
},
'<' => {
i += 1;
var start: usize = i;
// Find closing bracket
while (i < fmt.len and fmt[i] != '>') : (i += 1) {}
const color_name = fmt[start..i];
const encoded = parseColorName(color_name);
var orig = new_fmt_i;
new_fmt_i += encoded.len;
std.mem.copy(u8, new_fmt[orig..new_fmt_i], encoded);
},
else => {
new_fmt[new_fmt_i] = fmt[i];
new_fmt_i += 1;
i += 1;
},
}
};
return new_fmt[0..new_fmt_i];
}
fn parseColorName(comptime s: []const u8) []const u8 {
const cmp = std.ascii.startsWithIgnoreCase;
if (cmp(s, "fg.") == true) {
const name = s[3..];
if (std.ascii.isAlpha(name[0])) {
// E.g.: fg.white
return @field(palettes.Palette16.fg, name);
} else if (std.ascii.isDigit(name[0])) {
// E.g.: fg.32
const index = std.fmt.parseInt(u8, name, 10) catch unreachable;
return palettes.Palette256.fg[index][0..11];
} else {
@compileError("Unknown formatting: " ++ s);
}
} else if (cmp(s, "bg.") == true) {
const name = s[3..];
if (std.ascii.isAlpha(name[0])) {
return @field(palettes.Palette16.bg, name);
} else if (std.ascii.isDigit(name[0])) {
const index = std.fmt.parseInt(u8, name, 10) catch unreachable;
return palettes.Palette256.bg[index][0..11];
} else {
@compileError("Unknown formatting: " ++ s);
}
} else {
return @field(palettes.Mode, s);
}
}
|
src/main.zig
|
const std = @import("std");
const x509 = @import("iguanaTLS").x509;
const tls = @import("iguanaTLS");
const TypeOfRequest = enum { GET, POST, PUT, DELETE };
pub fn makeGetRequestAlloc(allocator: std.mem.Allocator, host: []const u8, path: []const u8) ![]const u8 {
return makeRequestAlloc(allocator, host, path, "", "", .GET);
}
pub fn makePostRequestAlloc(allocator: std.mem.Allocator, host: []const u8, path: []const u8, body: []const u8, headers: []const u8) ![]const u8 {
return makeRequestAlloc(allocator, host, path, body, headers, .POST);
}
fn makeRequestAlloc(allocator: std.mem.Allocator,
host: []const u8,
path: []const u8,
body: []const u8,
headers: []const u8,
typeOfRequest: TypeOfRequest) ![]const u8 {
const sock = try std.net.tcpConnectToHost(allocator, host, 443);
defer sock.close();
var client = try tls.client_connect(.{
.reader = sock.reader(),
.writer = sock.writer(),
.cert_verifier = .none,
.temp_allocator = allocator,
.ciphersuites = tls.ciphersuites.all,
.protocols = &[_][]const u8{"http/1.1"},
}, host);
defer client.close_notify() catch {};
try std.testing.expectEqualStrings("http/1.1", client.protocol);
const typeOfRequestStr: []const u8 = switch (typeOfRequest) {
.GET => "GET",
.POST => "POST",
.PUT => "PUT",
.DELETE => "DELETE"
};
var content_length_request: []const u8 = "";
if (body.len > 0) {
content_length_request = try std.fmt.allocPrint(allocator, "Content-Length: {d}\r\n", .{body.len});
}
defer allocator.free(content_length_request);
try client.writer().print("{s} {s} HTTP/1.1\r\nHost: {s}\r\nAccept: */*\r\n{s}\r\n{s}\r\n{s}",
.{typeOfRequestStr, path, host, headers, content_length_request, body});
{
const header = try client.reader().readUntilDelimiterAlloc(allocator, '\n', std.math.maxInt(usize));
try std.testing.expectEqualStrings("HTTP/1.1 200 OK", std.mem.trim(u8, header, &std.ascii.spaces));
allocator.free(header);
}
// Skip the rest of the headers except for Content-Length
var content_length: ?usize = null;
hdr_loop: while (true) {
const header = try client.reader().readUntilDelimiterAlloc(allocator, '\n', std.math.maxInt(usize));
defer allocator.free(header);
const hdr_contents = std.mem.trim(u8, header, &std.ascii.spaces);
if (hdr_contents.len == 0) {
break :hdr_loop;
}
if (std.mem.startsWith(u8, hdr_contents, "Content-Length: ")) {
content_length = try std.fmt.parseUnsigned(usize, hdr_contents[16..], 10);
}
}
try std.testing.expect(content_length != null);
const html_contents = try allocator.alloc(u8, content_length.?);
try client.reader().readNoEof(html_contents);
std.log.info("{s}", .{html_contents});
return html_contents;
}
// test "basic test" {
// try std.testing.expectEqual(10, 3 + 7);
// }
|
src/request.zig
|
const platform = @import("platform");
const proto = @import("proto");
const gdb = @import("gdb");
const std = @import("std");
pub const RW = enum { r, w };
pub var device_reader: std.fs.File.Reader = undefined;
pub var device_writer: std.fs.File.Writer = undefined;
/// When single stepping, you may need to hook some addresses.
/// Call this with every address that could possibly be reached.
pub fn singleStepHook(addr: u64, current_instr: platform.HookedInstr) !void {
std.log.info("Hooking at 0x{X} for single stepping", .{addr});
try singleStepHooks.append(std.heap.page_allocator, .{
.replaced_bytes = current_instr,
.addr = addr,
});
}
/// Call this when you want to overwrite a software breakpoint.
/// They are autmatically managed (removed when gdb asks for it etc)
pub fn swBreakpointHook(addr: u64, current_instr: platform.HookedInstr) !void {
std.log.info("Adding software breakpoint at 0x{X}", .{addr});
try softwareBreakpointHooks.append(std.heap.page_allocator, .{
.replaced_bytes = current_instr,
.addr = addr,
});
}
/// Send a command to the device. You may be expected to recieve
/// or send additional data after this operation.
pub fn sendDeviceCommand(cmd: proto.Command) !void {
try device_writer.writeIntLittle(u32, @intCast(u32, @sizeOf(proto.Command)));
std.log.info("Sent device command: {any}", .{cmd});
try device_writer.writeAll(std.mem.asBytes(&cmd));
}
/// Start a memory write operation.
/// You're expected to write `len` bytes to `device_writer` after this.
pub fn startMemoryWrite(addr: u64, len: u32) !void {
try sendDeviceCommand(.{
.command_type = .write_memory,
.addr = addr,
.size = len,
});
try device_writer.writeIntLittle(u32, len);
}
/// Start a memory read operation.
/// You're expected to read `len` bytes from `device_reader` after this.
pub fn startMemoryRead(addr: u64, len: u32) !void {
try sendDeviceCommand(.{
.command_type = .read_memory,
.addr = addr,
.size = len,
});
}
/// Resume the execution on the remote device. You are expected to send a frame back to the device.
pub fn resumeExecution() !void {
try sendDeviceCommand(.{
.command_type = .resume_execution,
});
}
/// Write the bytes in `data` at address `addr`
pub fn writeMemory(addr: u64, data: []const u8) !void {
try startMemoryWrite(addr, @intCast(u32, data.len));
for (data) |b| {
try device_writer.writeByte(b);
}
}
/// Read `num_bytes` at `addr` and return them by value
pub fn readBytes(addr: u64, comptime num_bytes: usize) ![num_bytes]u8 {
var result: [num_bytes]u8 = undefined;
try readBytesInto(addr, &result);
return result;
}
/// Fill `buf` with bytes from address `addr`
pub fn readBytesInto(addr: u64, buf: []u8) !void {
try startMemoryRead(addr, @intCast(u32, buf.len));
for (buf) |*b| {
b.* = try device_reader.readByte();
}
}
/// Check if a hook is placed at a given address `addr`
pub fn hasStepHookAtAddr(addr: u64) bool {
for (singleStepHooks.items) |hook| {
if (hook.addr == addr)
return true;
}
return false;
}
var frame: ?platform.Frame = undefined;
const Hook = struct {
addr: u64,
replaced_bytes: platform.HookedInstr,
};
var singleStepHooks: std.ArrayListUnmanaged(Hook) = .{};
var softwareBreakpointHooks: std.ArrayListUnmanaged(Hook) = .{};
const minified_target_xml = blk: {
@setEvalBranchQuota(99999999);
comptime var result: [:0]const u8 = "";
comptime var had_newline: bool = false;
inline for (platform.target_xml) |c| {
// Very simple yet effective minification:
// After newlines we remove any spaces and newlines
// until the next non-space or non-newline char
const curr_str = [_]u8{c};
if (had_newline) {
switch (c) {
' ',
'\n',
=> {},
else => {
result = result ++ curr_str;
had_newline = false;
},
}
} else {
if (c == '\n') {
had_newline = true;
} else {
result = result ++ curr_str;
}
}
}
break :blk result;
};
fn newFrame() !platform.Frame {
const next_frame = platform.readFrame();
for (singleStepHooks.items) |hook| {
std.log.info("Clearing hook at 0x{X}", .{hook.addr});
try writeMemory(hook.addr, &hook.replaced_bytes);
}
singleStepHooks.clearRetainingCapacity();
std.log.info("Read frame: {any}", .{next_frame});
return next_frame;
}
fn sendRegisters(gdb_stream: *gdb.Stream, first_register: usize, last_register: usize) !void {
var tries: usize = 0;
while (tries < 10) : (tries += 1) {
var session = try gdb_stream.startSendSession();
var current_register = first_register;
while (true) : (current_register += 1) {
if (frame.?.getGdbReg(current_register)) |regval| {
var reg_buf: [16]u8 = undefined;
_ = try std.fmt.bufPrint(®_buf, "{X:0>16}", .{std.mem.nativeToBig(u64, regval.*)});
try session.send(®_buf);
} else {
try session.send("x" ** 16);
}
if (current_register == last_register)
break;
}
session.finalize() catch |err| {
switch (err) {
// error.GdbDeniedPacket => continue,
else => return err,
}
};
break;
}
}
// fn checkAddrRange(addr: u64, size: u64, access: RW) void {
// // @TODO: All of this
// var mmio_register_mode: usize = 1;
// if(frame.?.pagingEnabled()) {
// const page_size = frame.?.pageSize(addr);
// var curr_addr = @divTrunc(addr, page_size);
// while(curr_addr < addr + size) : (curr_addr += page_size) {
// const perms = frame.?.permissionsAtVaddr(addr);
// switch(access) {
// .read => if(!perms.allowsReading()) return .AccessDenied,
// .write => if(!perms.allowsWriting()) return .AccessDenied,
// }
// mmio_register_mode = std.math.max(mmio_register_mode, perms.register_mode);
// }
// } else {
// if(addr > 0x40000000) { // Probably the highest addr you'll access without paging enabled
// return .AccessDenied;
// }
// }
// return switch(mmio_register_mode) {
// 1 => .AccessNormally,
// 4 => .AccessAsVolatileU32,
// else => {
// std.log.crit("Unimplemented register mode: {d}", .{mmio_register_mode});
// @panic("");
// },
// };
// }
fn handlePacket(pkt: []const u8, gdb_stream: *gdb.Stream) !void {
if (frame == null) {
frame = try newFrame();
std.log.info("Got frame from device: {any}", .{frame});
}
// This becomes unlegible if packed tightly
// zig fmt: off
if (std.mem.eql(u8, pkt, "vMustReplyEmpty")) {
try gdb_stream.send("");
}
// Stop reason packet
else if (std.mem.eql(u8, pkt, "?")) {
try frame.?.informHalt(gdb_stream);
}
// General query packets
else if (std.mem.startsWith(u8, pkt, "qSupported")) {
// 1M max packet size
try gdb_stream.send("PacketSize=1048576;qXfer:features:read+;swbreak+;hwbreak+");
}
else if(std.mem.startsWith(u8, pkt, "qXfer:features:read:target.xml:")) { // Read target xml
const request = pkt[31..]; // We cut off the 31 chars above
const comma_idx = std.mem.indexOfScalar(u8, request, ',').?;
const offset = try std.fmt.parseUnsigned(usize, request[0..comma_idx], 16);
const max_size = try std.fmt.parseUnsigned(usize, request[comma_idx + 1..], 16);
const data_head = minified_target_xml[offset..]; // Send minified XML
//const data_head = platform.target_xml[offset..]; // Send XML source
const read_size = std.math.min(data_head.len, max_size);
var session = try gdb_stream.startSendSession();
// What does "l" and "m" stand for? "l"ast and "m"ore?
try session.send(if(read_size == data_head.len) "l" else "m");
try session.send(data_head[0..read_size]);
try session.finalize();
}
else if (std.mem.startsWith(u8, pkt, "qAttached")) {
// Existing process
try gdb_stream.send("1");
}
else if (std.mem.eql(u8, pkt, "qTStatus")) {
try gdb_stream.send("");
}
else if (std.mem.eql(u8, pkt, "qfThreadInfo")) {
// Get a list of active threads
try gdb_stream.send("");
}
else if (std.mem.startsWith(u8, pkt, "qL")) {
// Thread information, just junk
try gdb_stream.send("");
}
else if (std.mem.startsWith(u8, pkt, "qC")) {
// Get current thread ID
try gdb_stream.send("QC 1");
}
// Set thread for operation
else if (pkt.len == 3 and pkt[0] == 'H' and pkt[2] == '0') { // Hg0 et al
try gdb_stream.send("OK");
}
else if (std.mem.startsWith(u8, pkt, "Hc")) {
try gdb_stream.send("");
}
// Detach
else if (std.mem.startsWith(u8, pkt, "D")) {
try gdb_stream.send("OK");
}
else if(std.mem.startsWith(u8, pkt, "m") or std.mem.startsWith(u8, pkt, "x")) { // Read memory
const reply_in_binary = pkt[0] == 'x';
const comma_idx = std.mem.indexOfScalar(u8, pkt, ',').?;
const addr = try std.fmt.parseUnsigned(usize, pkt[1..comma_idx], 16);
const size = try std.fmt.parseUnsigned(usize, pkt[comma_idx + 1 ..], 16);
// Assume the entire read is within the same page for now
const read_addr = frame.?.operableAddr(addr, .r) catch |err| {
switch(err) {
error.CannotWrite => unreachable,
error.NotMapped => {
std.log.warn("vaddr 0x{X} in debuggee isn't mapped", .{addr});
try gdb_stream.send("E14"); // EFAULT, Bad address
},
error.PaddrNotIdentityMapped => {
std.log.warn("paddr behind vaddr 0x{X} isn't accessible by the debugger", .{addr});
try gdb_stream.send("E14"); // EFAULT, Bad address
},
else => |e| return e,
}
return;
};
var tries: usize = 0;
while(tries < 5) {
if(size > 0)
try startMemoryRead(read_addr, @intCast(u32, size));
var session = try gdb_stream.startSendSession();
var i: usize = 0;
while(i < size) : (i += 1) {
if(reply_in_binary) {
try session.send(&[_]u8{try device_reader.readByte()});
} else {
var buf: [2]u8 = undefined;
_ = std.fmt.bufPrint(&buf, "{X:0>2}", .{try device_reader.readByte()}) catch unreachable;
try session.send(&buf);
}
}
session.finalize() catch |err| {
switch(err) {
// error.GdbDeniedPacket => continue,
else => return err,
}
};
break;
}
}
else if(std.mem.startsWith(u8, pkt, "M") or std.mem.startsWith(u8, pkt, "X")) { // Write memory
// @TODO: Sometimes GDB uses this to write breakpoints
// on aarch64 by writing a BRK #0 instruction. This only works
// if we're debugging the current EL and we should do something
// about it if that is what they're doing.
const read_in_binary = pkt[0] == 'X';
const comma_idx = std.mem.indexOfScalar(u8, pkt, ',').?;
const colon_idx = std.mem.indexOfScalar(u8, pkt, ':').?;
const addr = try std.fmt.parseUnsigned(usize, pkt[1..comma_idx], 16);
const size = try std.fmt.parseUnsigned(usize, pkt[comma_idx + 1 .. colon_idx], 16);
const data = pkt[colon_idx + 1..];
// Assume the entire write is within the same page for now
const write_addr = frame.?.operableAddr(addr, .w) catch |err| {
switch(err) {
error.CannotWrite => {
std.log.warn("paddr behind vaddr 0x{X} isn't writeable by the debugger", .{addr});
try gdb_stream.send("E01"); // EPERM, Operation not permitted
},
error.NotMapped => {
std.log.warn("vaddr 0x{X} in debuggee isn't mapped", .{addr});
try gdb_stream.send("E14"); // EFAULT, Bad address
},
error.PaddrNotIdentityMapped => {
std.log.warn("paddr behind vaddr 0x{X} isn't accessible by the debugger", .{addr});
try gdb_stream.send("E14"); // EFAULT, Bad address
},
else => |e| return e,
}
return;
};
if(size > 0)
try startMemoryWrite(write_addr, @intCast(u32, size));
var i: usize = 0;
if(read_in_binary) {
std.debug.assert(size == data.len);
for(data) |b| {
try device_writer.writeByte(b);
}
} else {
std.debug.assert(size == @divExact(data.len, 2));
while(i < size * 2) : (i += 2) {
const b = std.fmt.parseUnsigned(u8, data[i..][0..2], 16) catch |err| blk: {
std.log.err("Cannot parse hex encoded byte '{s}' in M packet. Error: {}!", .{data[i..][0..2], err});
break :blk 0xAA;
};
try device_writer.writeByte(b);
}
}
try gdb_stream.send("");
}
else if(std.mem.startsWith(u8, pkt, "Z0")) { // Insert software breakpoint
const request = pkt[3..];
const comma_idx = std.mem.indexOfScalar(u8, request, ',').?;
const addr = try std.fmt.parseUnsigned(usize, request[0..comma_idx], 16);
try frame.?.setSwBreak(addr);
try gdb_stream.send("OK");
}
else if(std.mem.startsWith(u8, pkt, "z0")) { // Remove software breakpoint
const request = pkt[3..];
const comma_idx = std.mem.indexOfScalar(u8, request, ',').?;
const addr = try std.fmt.parseUnsigned(usize, request[0..comma_idx], 16);
for(softwareBreakpointHooks.items) |swbp, i| {
if(swbp.addr == addr) {
try writeMemory(swbp.addr, &swbp.replaced_bytes);
_ = softwareBreakpointHooks.swapRemove(i);
try gdb_stream.send("OK");
return;
}
}
try gdb_stream.send("E00");
}
else if(std.mem.eql(u8, pkt, "g")) { // Read registers list
try sendRegisters(gdb_stream, 0, platform.num_default_registers);
}
else if(std.mem.startsWith(u8, pkt, "p")) { // Read single register
const regnum = try std.fmt.parseUnsigned(usize, pkt[1..], 16);
try sendRegisters(gdb_stream, regnum, regnum);
}
else if(std.mem.startsWith(u8, pkt, "P")) { // Write single register
const eql_idx = std.mem.indexOfScalar(u8, pkt, '=').?;
const regnum = try std.fmt.parseUnsigned(usize, pkt[1..eql_idx], 16);
const value = std.mem.bigToNative(u64, try std.fmt.parseUnsigned(u64, pkt[eql_idx + 1..], 16));
if(frame.?.writeGdbReg(regnum, value)) {
try gdb_stream.send("OK");
} else {
try gdb_stream.send("E00");
}
}
else if (std.mem.startsWith(u8, pkt, "c") or std.mem.startsWith(u8, pkt, "s")) { // Continue and step
try frame.?.doStep(std.mem.startsWith(u8, pkt, "s"));
frame = try newFrame();
std.log.info("Got frame from device: {any}", .{frame});
try frame.?.informHalt(gdb_stream);
}
else {
std.log.info("Unknown gdb packet: '{s}', replying empty.", .{pkt});
try gdb_stream.send("");
}
// zig fmt: on
}
/// Reads packets from a gdb instance, processing them one by one
fn processGdbStream(stream: *gdb.Stream) !void {
var packet_buffer: [4096]u8 = undefined;
while (true) {
const pkt = try stream.readInto(&packet_buffer);
try handlePacket(pkt, stream);
}
}
/// Starts a gdb server and starts listening for connections
pub fn run(listen_address: std.net.Address) !void {
device_writer = std.io.getStdOut().writer();
device_reader = std.io.getStdIn().reader();
var server = std.net.StreamServer.init(.{
.kernel_backlog = 0,
.reuse_address = true,
});
try server.listen(listen_address);
defer server.close();
std.log.info("Listening on {}", .{listen_address});
while (true) {
const conn = try server.accept();
defer conn.stream.close();
std.log.info("Accepted connection from {}", .{conn.address});
var gdb_stream = gdb.Stream.init(conn.stream);
processGdbStream(&gdb_stream) catch |err| {
switch (err) {
error.EndOfStream => continue,
else => |e| return e,
}
};
std.log.info("Lost connection from {}", .{conn.address});
}
}
|
src/client/client.zig
|
const std = @import("std");
const awshttp = @import("awshttp.zig");
const json = @import("json.zig");
const url = @import("url.zig");
const case = @import("case.zig");
const servicemodel = @import("servicemodel.zig");
const log = std.log.scoped(.aws);
pub const Options = struct {
region: []const u8 = "aws-global",
dualstack: bool = false,
success_http_code: i64 = 200,
client: Client,
};
/// Using this constant may blow up build times. Recommed using Services()
/// function directly, e.g. const services = Services(.{.sts, .ec2, .s3, .ddb}){};
pub const services = servicemodel.services;
/// Get a service model by importing specific services only. As an example:
/// const services = Services(.{.sts, .ec2, .s3, .ddb}){};
///
/// This will give you a constant with service data for sts, ec2, s3 and ddb only
pub const Services = servicemodel.Services;
pub const Client = struct {
allocator: std.mem.Allocator,
aws_http: awshttp.AwsHttp,
const Self = @This();
pub fn init(allocator: std.mem.Allocator) Self {
return .{
.allocator = allocator,
.aws_http = awshttp.AwsHttp.init(allocator),
};
}
pub fn deinit(self: *Client) void {
self.aws_http.deinit();
}
/// Calls AWS. Use a comptime request and options. For a runtime interface,
/// see Request
pub fn call(_: Self, comptime request: anytype, options: Options) !FullResponse(@TypeOf(request).metaInfo().action) {
const action = @TypeOf(request).metaInfo().action;
return Request(action).call(request, options);
}
};
/// Establish an AWS request that can be later called with runtime-known
/// parameters. If all parameters are known at comptime, the call function
/// may be simpler to use. request parameter here refers to the action
/// constant from the model, e.g. Request(services.lambda.list_functions)
pub fn Request(comptime action: anytype) type {
return struct {
const ActionRequest = action.Request;
const FullResponseType = FullResponse(action);
const Self = @This();
const action = action;
const meta_info = ActionRequest.metaInfo();
const service_meta = meta_info.service_metadata;
pub fn call(request: ActionRequest, options: Options) !FullResponseType {
// every codegenned request object includes a metaInfo function to get
// pointers to service and action
log.debug("call: prefix {s}, sigv4 {s}, version {s}, action {s}", .{
Self.service_meta.endpoint_prefix,
Self.service_meta.sigv4_name,
Self.service_meta.version,
action.action_name,
});
log.debug("proto: {s}", .{Self.service_meta.aws_protocol});
// It seems as though there are 3 major branches of the 6 protocols.
// 1. query/ec2_query, which are identical until you get to complex
// structures. EC2 query does not allow us to request json though,
// so we need to handle xml returns from this.
// 2. *json*: These three appear identical for input (possible difference
// for empty body serialization), but differ in error handling.
// We're not doing a lot of error handling here, though.
// 3. rest_xml: This is a one-off for S3, never used since
switch (Self.service_meta.aws_protocol) {
.query => return Self.callQuery(request, options),
// .query, .ec2_query => return self.callQuery(request, Self.service_meta, action, options),
.json_1_0, .json_1_1 => return Self.callJson(request, options),
.rest_json_1 => return Self.callRestJson(request, options),
.ec2_query, .rest_xml => @compileError("XML responses may be blocked on a zig compiler bug scheduled to be fixed in 0.9.0"),
}
}
/// Rest Json is the most complex and so we handle this seperately
fn callRestJson(request: ActionRequest, options: Options) !FullResponseType {
const Action = @TypeOf(action);
var aws_request: awshttp.HttpRequest = .{
.method = Action.http_config.method,
.content_type = "application/json",
.path = Action.http_config.uri,
};
log.debug("Rest JSON v1 method: '{s}'", .{aws_request.method});
log.debug("Rest JSON v1 success code: '{d}'", .{Action.http_config.success_code});
log.debug("Rest JSON v1 raw uri: '{s}'", .{Action.http_config.uri});
aws_request.path = try buildPath(options.client.allocator, Action.http_config.uri, ActionRequest, request);
defer options.client.allocator.free(aws_request.path);
log.debug("Rest JSON v1 processed uri: '{s}'", .{aws_request.path});
aws_request.query = try buildQuery(options.client.allocator, request);
log.debug("Rest JSON v1 query: '{s}'", .{aws_request.query});
defer options.client.allocator.free(aws_request.query);
// We don't know if we need a body...guessing here, this should cover most
var buffer = std.ArrayList(u8).init(options.client.allocator);
defer buffer.deinit();
var nameAllocator = std.heap.ArenaAllocator.init(options.client.allocator);
defer nameAllocator.deinit();
if (std.mem.eql(u8, "PUT", aws_request.method) or std.mem.eql(u8, "POST", aws_request.method)) {
try json.stringify(request, .{ .whitespace = .{} }, buffer.writer());
}
aws_request.body = buffer.items;
return try Self.callAws(aws_request, .{
.success_http_code = Action.http_config.success_code,
.region = options.region,
.dualstack = options.dualstack,
.client = options.client,
});
}
/// Calls using one of the json protocols (json_1_0, json_1_1)
fn callJson(request: ActionRequest, options: Options) !FullResponseType {
const target =
try std.fmt.allocPrint(options.client.allocator, "{s}.{s}", .{
Self.service_meta.name,
action.action_name,
});
defer options.client.allocator.free(target);
var buffer = std.ArrayList(u8).init(options.client.allocator);
defer buffer.deinit();
// The transformer needs to allocate stuff out of band, but we
// can guarantee we don't need the memory after this call completes,
// so we'll use an arena allocator to whack everything.
// TODO: Determine if sending in null values is ok, or if we need another
// tweak to the stringify function to exclude. According to the
// smithy spec, "A null value MAY be provided or omitted
// for a boxed member with no observable difference." But we're
// seeing a lot of differences here between spec and reality
//
var nameAllocator = std.heap.ArenaAllocator.init(options.client.allocator);
defer nameAllocator.deinit();
try json.stringify(request, .{ .whitespace = .{} }, buffer.writer());
var content_type: []const u8 = undefined;
switch (Self.service_meta.aws_protocol) {
.json_1_0 => content_type = "application/x-amz-json-1.0",
.json_1_1 => content_type = "application/x-amz-json-1.1",
else => unreachable,
}
return try Self.callAws(.{
.query = "",
.body = buffer.items,
.content_type = content_type,
.headers = &[_]awshttp.Header{.{ .name = "X-Amz-Target", .value = target }},
}, options);
}
// Call using query protocol. This is documented as an XML protocol, but
// throwing a JSON accept header seems to work. EC2Query is very simliar to
// Query, so we'll handle both here. Realistically we probably don't effectively
// handle lists and maps properly anyway yet, so we'll go for it and see
// where it breaks. PRs and/or failing test cases appreciated.
fn callQuery(request: ActionRequest, options: Options) !FullResponseType {
var buffer = std.ArrayList(u8).init(options.client.allocator);
defer buffer.deinit();
const writer = buffer.writer();
try url.encode(request, writer, .{
.field_name_transformer = &queryFieldTransformer,
.allocator = options.client.allocator,
});
const continuation = if (buffer.items.len > 0) "&" else "";
const query = if (Self.service_meta.aws_protocol == .query)
try std.fmt.allocPrint(options.client.allocator, "", .{})
else // EC2
try std.fmt.allocPrint(options.client.allocator, "?Action={s}&Version={s}", .{
action.action_name,
Self.service_meta.version,
});
defer options.client.allocator.free(query);
const body = if (Self.service_meta.aws_protocol == .query)
try std.fmt.allocPrint(options.client.allocator, "Action={s}&Version={s}{s}{s}", .{
action.action_name,
Self.service_meta.version,
continuation,
buffer.items,
})
else // EC2
try std.fmt.allocPrint(options.client.allocator, "{s}", .{buffer.items});
defer options.client.allocator.free(body);
return try Self.callAws(.{
.query = query,
.body = body,
.content_type = "application/x-www-form-urlencoded",
}, options);
}
fn callAws(aws_request: awshttp.HttpRequest, options: Options) !FullResponseType {
const response = try options.client.aws_http.callApi(
Self.service_meta.endpoint_prefix,
aws_request,
.{
.region = options.region,
.dualstack = options.dualstack,
.sigv4_service_name = Self.service_meta.sigv4_name,
},
);
defer response.deinit();
if (response.response_code != options.success_http_code) {
try reportTraffic(options.client.allocator, "Call Failed", aws_request, response, log.err);
return error.HttpFailure;
}
// EC2 ignores our accept type, but technically query protocol only
// returns XML as well. So, we'll ignore the protocol here and just
// look at the return type
var isJson: bool = undefined;
for (response.headers) |h| {
if (std.mem.eql(u8, "Content-Type", h.name)) {
if (std.mem.startsWith(u8, h.value, "application/json")) {
isJson = true;
} else if (std.mem.startsWith(u8, h.value, "application/x-amz-json-1.0")) {
isJson = true;
} else if (std.mem.startsWith(u8, h.value, "application/x-amz-json-1.1")) {
isJson = true;
} else if (std.mem.startsWith(u8, h.value, "text/xml")) {
isJson = false;
} else {
log.err("Unexpected content type: {s}", .{h.value});
return error.UnexpectedContentType;
}
break;
}
}
// TODO: Handle XML
if (!isJson) return error.XmlUnimplemented;
const SResponse = if (Self.service_meta.aws_protocol != .query and Self.service_meta.aws_protocol != .ec2_query)
action.Response
else
ServerResponse(action);
const parser_options = json.ParseOptions{
.allocator = options.client.allocator,
.allow_camel_case_conversion = true, // new option
.allow_snake_case_conversion = true, // new option
.allow_unknown_fields = true, // new option. Cannot yet handle non-struct fields though
.allow_missing_fields = false, // new option. Cannot yet handle non-struct fields though
};
if (std.meta.fields(SResponse).len == 0) // We don't care about the body if there are no fields
// Do we care if an unexpected body comes in?
return FullResponseType{
.response = .{},
.response_metadata = .{
.request_id = try requestIdFromHeaders(aws_request, response, options),
},
.parser_options = parser_options,
.raw_parsed = .{ .raw = .{} },
};
var stream = json.TokenStream.init(response.body);
const parsed_response = json.parse(SResponse, &stream, parser_options) catch |e| {
log.err(
\\Call successful, but unexpected response from service.
\\This could be the result of a bug or a stale set of code generated
\\service models.
\\
\\Model Type: {s}
\\
\\Response from server:
\\
\\{s}
\\
, .{ SResponse, response.body });
return e;
};
if (Self.service_meta.aws_protocol != .query and Self.service_meta.aws_protocol != .ec2_query) {
return FullResponseType{
.response = parsed_response,
.response_metadata = .{
.request_id = try requestIdFromHeaders(aws_request, response, options),
},
.parser_options = parser_options,
.raw_parsed = .{ .raw = parsed_response },
};
}
// Grab the first (and only) object from the server. Server shape expected to be:
// { ActionResponse: {ActionResult: {...}, ResponseMetadata: {...} } }
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Next line of code pulls this portion
//
//
// And the response property below will pull whatever is the ActionResult object
// We can grab index [0] as structs are guaranteed by zig to be returned in the order
// declared, and we're declaring in that order in ServerResponse().
const real_response = @field(parsed_response, @typeInfo(SResponse).Struct.fields[0].name);
return FullResponseType{
.response = @field(real_response, @typeInfo(@TypeOf(real_response)).Struct.fields[0].name),
.response_metadata = .{
.request_id = try options.client.allocator.dupe(u8, real_response.ResponseMetadata.RequestId),
},
.parser_options = parser_options,
.raw_parsed = .{ .server = parsed_response },
};
}
};
}
/// Get request ID from headers. Caller responsible for freeing memory
fn requestIdFromHeaders(request: awshttp.HttpRequest, response: awshttp.HttpResult, options: Options) ![]u8 {
var request_id: []u8 = undefined;
var found = false;
for (response.headers) |h| {
if (std.ascii.eqlIgnoreCase(h.name, "X-Amzn-RequestId")) {
found = true;
request_id = try std.fmt.allocPrint(options.client.allocator, "{s}", .{h.value}); // will be freed in FullR.deinit()
}
}
if (!found) {
try reportTraffic(options.client.allocator, "Request ID not found", request, response, log.err);
return error.RequestIdNotFound;
}
return request_id;
}
fn ServerResponse(comptime action: anytype) type {
const T = action.Response;
// NOTE: The non-standard capitalization here is used as a performance
// enhancement and to reduce allocations in json.zig. These fields are
// not (nor are they ever intended to be) exposed outside this codebase
const ResponseMetadata = struct {
RequestId: []u8,
};
const Result = @Type(.{
.Struct = .{
.layout = .Auto,
.fields = &[_]std.builtin.TypeInfo.StructField{
.{
.name = action.action_name ++ "Result",
.field_type = T,
.default_value = null,
.is_comptime = false,
.alignment = 0,
},
.{
.name = "ResponseMetadata",
.field_type = ResponseMetadata,
.default_value = null,
.is_comptime = false,
.alignment = 0,
},
},
.decls = &[_]std.builtin.TypeInfo.Declaration{},
.is_tuple = false,
},
});
return @Type(.{
.Struct = .{
.layout = .Auto,
.fields = &[_]std.builtin.TypeInfo.StructField{
.{
.name = action.action_name ++ "Response",
.field_type = Result,
.default_value = null,
.is_comptime = false,
.alignment = 0,
},
},
.decls = &[_]std.builtin.TypeInfo.Declaration{},
.is_tuple = false,
},
});
}
fn FullResponse(comptime action: anytype) type {
return struct {
response: action.Response,
response_metadata: struct {
request_id: []u8,
},
parser_options: json.ParseOptions,
raw_parsed: union(enum) {
server: ServerResponse(action),
raw: action.Response,
},
// raw_parsed: ServerResponse(request),
const Self = @This();
pub fn deinit(self: Self) void {
switch (self.raw_parsed) {
.server => json.parseFree(ServerResponse(action), self.raw_parsed.server, self.parser_options),
.raw => json.parseFree(action.Response, self.raw_parsed.raw, self.parser_options),
}
self.parser_options.allocator.?.free(self.response_metadata.request_id);
}
};
}
fn queryFieldTransformer(field_name: []const u8, encoding_options: url.EncodingOptions) anyerror![]const u8 {
return try case.snakeToPascal(encoding_options.allocator.?, field_name);
}
fn buildPath(allocator: std.mem.Allocator, raw_uri: []const u8, comptime ActionRequest: type, request: anytype) ![]const u8 {
var buffer = try std.ArrayList(u8).initCapacity(allocator, raw_uri.len);
// const writer = buffer.writer();
defer buffer.deinit();
var in_var = false;
var start: u64 = 0;
for (raw_uri) |c, inx| {
switch (c) {
'{' => {
in_var = true;
start = inx + 1;
},
'}' => {
in_var = false;
const replacement_var = raw_uri[start..inx];
inline for (std.meta.fields(ActionRequest)) |field| {
if (std.mem.eql(u8, request.jsonFieldNameFor(field.name), replacement_var)) {
var replacement_buffer = try std.ArrayList(u8).initCapacity(allocator, raw_uri.len);
defer replacement_buffer.deinit();
var encoded_buffer = try std.ArrayList(u8).initCapacity(allocator, raw_uri.len);
defer encoded_buffer.deinit();
const replacement_writer = replacement_buffer.writer();
// std.mem.replacementSize
try json.stringify(
@field(request, field.name),
.{},
replacement_writer,
);
const trimmed_replacement_val = std.mem.trim(u8, replacement_buffer.items, "\"");
try uriEncode(trimmed_replacement_val, encoded_buffer.writer());
try buffer.appendSlice(encoded_buffer.items);
}
}
},
else => if (!in_var) {
try buffer.append(c);
} else {},
}
}
return buffer.toOwnedSlice();
}
fn uriEncode(input: []const u8, writer: anytype) !void {
for (input) |c|
try uriEncodeByte(c, writer);
}
fn uriEncodeByte(char: u8, writer: anytype) !void {
switch (char) {
'!' => _ = try writer.write("%21"),
'#' => _ = try writer.write("%23"),
'$' => _ = try writer.write("%24"),
'&' => _ = try writer.write("%26"),
'\'' => _ = try writer.write("%27"),
'(' => _ = try writer.write("%28"),
')' => _ = try writer.write("%29"),
'*' => _ = try writer.write("%2A"),
'+' => _ = try writer.write("%2B"),
',' => _ = try writer.write("%2C"),
'/' => _ = try writer.write("%2F"),
':' => _ = try writer.write("%3A"),
';' => _ = try writer.write("%3B"),
'=' => _ = try writer.write("%3D"),
'?' => _ = try writer.write("%3F"),
'@' => _ = try writer.write("%40"),
'[' => _ = try writer.write("%5B"),
']' => _ = try writer.write("%5D"),
'%' => _ = try writer.write("%25"),
else => {
_ = try writer.writeByte(char);
},
}
}
fn buildQuery(allocator: std.mem.Allocator, request: anytype) ![]const u8 {
// query should look something like this:
// pub const http_query = .{
// .master_region = "MasterRegion",
// .function_version = "FunctionVersion",
// .marker = "Marker",
// };
var buffer = std.ArrayList(u8).init(allocator);
const writer = buffer.writer();
defer buffer.deinit();
var prefix = "?";
const Req = @TypeOf(request);
if (declaration(Req, "http_query") == null)
return buffer.toOwnedSlice();
const query_arguments = Req.http_query;
inline for (@typeInfo(@TypeOf(query_arguments)).Struct.fields) |arg| {
const val = @field(request, arg.name);
if (try addQueryArg(arg.field_type, prefix, @field(query_arguments, arg.name), val, writer))
prefix = "&";
}
return buffer.toOwnedSlice();
}
fn declaration(comptime T: type, name: []const u8) ?std.builtin.TypeInfo.Declaration {
for (std.meta.declarations(T)) |decl| {
if (std.mem.eql(u8, name, decl.name))
return decl;
}
return null;
}
fn addQueryArg(comptime ValueType: type, prefix: []const u8, key: []const u8, value: anytype, writer: anytype) !bool {
switch (@typeInfo(@TypeOf(value))) {
.Optional => {
if (value) |v|
return try addQueryArg(ValueType, prefix, key, v, writer);
return false;
},
// if this is a pointer, we want to make sure it is more than just a string
.Pointer => |ptr| {
if (ptr.child == u8 or ptr.size != .Slice) {
// This is just a string
return try addBasicQueryArg(prefix, key, value, writer);
}
var p = prefix;
for (value) |li| {
if (try addQueryArg(ValueType, p, key, li, writer))
p = "&";
}
return std.mem.eql(u8, "&", p);
},
.Array => |arr| {
if (arr.child == u8)
return try addBasicQueryArg(prefix, key, value, writer);
var p = prefix;
for (value) |li| {
if (try addQueryArg(ValueType, p, key, li, writer))
p = "&";
}
return std.mem.eql(u8, "&", p);
},
else => {
return try addBasicQueryArg(prefix, key, value, writer);
},
}
}
fn addBasicQueryArg(prefix: []const u8, key: []const u8, value: anytype, writer: anytype) !bool {
_ = try writer.write(prefix);
// TODO: url escaping
try uriEncode(key, writer);
_ = try writer.write("=");
try json.stringify(value, .{}, ignoringWriter(uriEncodingWriter(writer).writer(), '"').writer());
return true;
}
pub fn uriEncodingWriter(child_stream: anytype) UriEncodingWriter(@TypeOf(child_stream)) {
return .{ .child_stream = child_stream };
}
/// A Writer that ignores a character
pub fn UriEncodingWriter(comptime WriterType: type) type {
return struct {
child_stream: WriterType,
pub const Error = WriterType.Error;
pub const Writer = std.io.Writer(*Self, Error, write);
const Self = @This();
pub fn write(self: *Self, bytes: []const u8) Error!usize {
try uriEncode(bytes, self.child_stream);
return bytes.len; // We say that all bytes are "written", even if they're not, as caller may be retrying
}
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
};
}
pub fn ignoringWriter(child_stream: anytype, ignore: u8) IgnoringWriter(@TypeOf(child_stream)) {
return .{ .child_stream = child_stream, .ignore = ignore };
}
/// A Writer that ignores a character
pub fn IgnoringWriter(comptime WriterType: type) type {
return struct {
child_stream: WriterType,
ignore: u8,
pub const Error = WriterType.Error;
pub const Writer = std.io.Writer(*Self, Error, write);
const Self = @This();
pub fn write(self: *Self, bytes: []const u8) Error!usize {
for (bytes) |b| {
if (b != self.ignore)
try self.child_stream.writeByte(b);
}
return bytes.len; // We say that all bytes are "written", even if they're not, as caller may be retrying
}
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
};
}
fn reportTraffic(allocator: std.mem.Allocator, info: []const u8, request: awshttp.HttpRequest, response: awshttp.HttpResult, comptime reporter: fn (comptime []const u8, anytype) void) !void {
var msg = std.ArrayList(u8).init(allocator);
defer msg.deinit();
const writer = msg.writer();
try writer.print("{s}\n\n", .{info});
try writer.print("Return status: {d}\n\n", .{response.response_code});
if (request.query.len > 0) try writer.print("Request Query:\n \t{s}\n", .{request.query});
_ = try writer.write("Unique Request Headers:\n");
if (request.headers.len > 0) {
for (request.headers) |h|
try writer.print("\t{s}: {s}\n", .{ h.name, h.value });
}
try writer.print("\tContent-Type: {s}\n\n", .{request.content_type});
_ = try writer.write("Request Body:\n");
try writer.print("-------------\n{s}\n", .{request.body});
_ = try writer.write("-------------\n");
_ = try writer.write("Response Headers:\n");
for (response.headers) |h|
try writer.print("\t{s}: {s}\n", .{ h.name, h.value });
_ = try writer.write("Response Body:\n");
try writer.print("--------------\n{s}\n", .{response.body});
_ = try writer.write("--------------\n");
reporter("{s}\n", .{msg.items});
}
// TODO: Where does this belong really?
fn typeForField(comptime T: type, field_name: []const u8) !type {
const ti = @typeInfo(T);
switch (ti) {
.Struct => {
inline for (ti.Struct.fields) |field| {
if (std.mem.eql(u8, field.name, field_name))
return field.field_type;
}
},
else => return error.TypeIsNotAStruct, // should not hit this
}
return error.FieldNotFound;
}
test "custom serialization for map objects" {
const allocator = std.testing.allocator;
var buffer = std.ArrayList(u8).init(allocator);
defer buffer.deinit();
var tags = try std.ArrayList(@typeInfo(try typeForField(services.lambda.tag_resource.Request, "tags")).Pointer.child).initCapacity(allocator, 2);
defer tags.deinit();
tags.appendAssumeCapacity(.{ .key = "Foo", .value = "Bar" });
tags.appendAssumeCapacity(.{ .key = "Baz", .value = "Qux" });
const req = services.lambda.tag_resource.Request{ .resource = "hello", .tags = tags.items };
try json.stringify(req, .{ .whitespace = .{} }, buffer.writer());
try std.testing.expectEqualStrings(
\\{
\\ "Resource": "hello",
\\ "Tags": {
\\ "Foo": "Bar",
\\ "Baz": "Qux"
\\ }
\\}
, buffer.items);
}
test "REST Json v1 builds proper queries" {
const allocator = std.testing.allocator;
const svs = Services(.{.lambda}){};
const request = svs.lambda.list_functions.Request{
.max_items = 1,
};
const query = try buildQuery(allocator, request);
defer allocator.free(query);
try std.testing.expectEqualStrings("?MaxItems=1", query);
}
test "REST Json v1 handles reserved chars in queries" {
const allocator = std.testing.allocator;
const svs = Services(.{.lambda}){};
var keys = [_][]const u8{"Foo?I'm a crazy%dude"}; // Would love to have a way to express this without burning a var here
const request = svs.lambda.untag_resource.Request{
.tag_keys = keys[0..],
.resource = "hello",
};
const query = try buildQuery(allocator, request);
defer allocator.free(query);
try std.testing.expectEqualStrings("?tagKeys=Foo%3FI%27m a crazy%25dude", query);
}
test "REST Json v1 serializes lists in queries" {
const allocator = std.testing.allocator;
const svs = Services(.{.lambda}){};
var keys = [_][]const u8{ "Foo", "Bar" }; // Would love to have a way to express this without burning a var here
const request = svs.lambda.untag_resource.Request{
.tag_keys = keys[0..],
.resource = "hello",
};
const query = try buildQuery(allocator, request);
defer allocator.free(query);
try std.testing.expectEqualStrings("?tagKeys=Foo&tagKeys=Bar", query);
}
test "REST Json v1 buildpath substitutes" {
const allocator = std.testing.allocator;
const svs = Services(.{.lambda}){};
const request = svs.lambda.list_functions.Request{
.max_items = 1,
};
const input_path = "https://myhost/{MaxItems}/";
const output_path = try buildPath(allocator, input_path, @TypeOf(request), request);
defer allocator.free(output_path);
try std.testing.expectEqualStrings("https://myhost/1/", output_path);
}
test "REST Json v1 buildpath handles restricted characters" {
const allocator = std.testing.allocator;
const svs = Services(.{.lambda}){};
const request = svs.lambda.list_functions.Request{
.marker = ":",
};
const input_path = "https://myhost/{Marker}/";
const output_path = try buildPath(allocator, input_path, @TypeOf(request), request);
defer allocator.free(output_path);
try std.testing.expectEqualStrings("https://myhost/%3A/", output_path);
}
test "basic json request serialization" {
const allocator = std.testing.allocator;
const svs = Services(.{.dynamo_db}){};
const request = svs.dynamo_db.list_tables.Request{
.limit = 1,
};
var buffer = std.ArrayList(u8).init(allocator);
defer buffer.deinit();
// The transformer needs to allocate stuff out of band, but we
// can guarantee we don't need the memory after this call completes,
// so we'll use an arena allocator to whack everything.
// TODO: Determine if sending in null values is ok, or if we need another
// tweak to the stringify function to exclude. According to the
// smithy spec, "A null value MAY be provided or omitted
// for a boxed member with no observable difference." But we're
// seeing a lot of differences here between spec and reality
//
var nameAllocator = std.heap.ArenaAllocator.init(allocator);
defer nameAllocator.deinit();
try json.stringify(request, .{ .whitespace = .{} }, buffer.writer());
try std.testing.expectEqualStrings(
\\{
\\ "ExclusiveStartTableName": null,
\\ "Limit": 1
\\}
, buffer.items);
}
test "layer object only" {
const TestResponse = struct {
arn: ?[]const u8 = null,
// uncompressed_code_size: ?i64 = null,
pub fn jsonFieldNameFor(_: @This(), comptime field_name: []const u8) []const u8 {
const mappings = .{
.arn = "Arn",
};
return @field(mappings, field_name);
}
};
const response =
\\ {
\\ "UncompressedCodeSize": 2,
\\ "Arn": "blah"
\\ }
;
// const response =
// \\ {
// \\ "UncompressedCodeSize": 22599541,
// \\ "Arn": "arn:aws:lambda:us-west-2:550620852718:layer:PollyNotes-lib:4"
// \\ }
// ;
const allocator = std.testing.allocator;
var stream = json.TokenStream.init(response);
const parser_options = json.ParseOptions{
.allocator = allocator,
.allow_camel_case_conversion = true, // new option
.allow_snake_case_conversion = true, // new option
.allow_unknown_fields = true, // new option. Cannot yet handle non-struct fields though
.allow_missing_fields = false, // new option. Cannot yet handle non-struct fields though
};
const r = try json.parse(TestResponse, &stream, parser_options);
json.parseFree(TestResponse, r, parser_options);
}
// Use for debugging json responses of specific requests
// test "dummy request" {
// const allocator = std.testing.allocator;
// const svs = Services(.{.sts}){};
// const request = svs.sts.get_session_token.Request{
// .duration_seconds = 900,
// };
// const FullR = FullResponse(request);
// const response =
// var stream = json.TokenStream.init(response);
//
// const parser_options = json.ParseOptions{
// .allocator = allocator,
// .allow_camel_case_conversion = true, // new option
// .allow_snake_case_conversion = true, // new option
// .allow_unknown_fields = true, // new option. Cannot yet handle non-struct fields though
// .allow_missing_fields = false, // new option. Cannot yet handle non-struct fields though
// };
// const SResponse = ServerResponse(request);
// const r = try json.parse(SResponse, &stream, parser_options);
// json.parseFree(SResponse, r, parser_options);
// }
|
src/aws.zig
|
const std = @import("std");
const SDL = @import("sdl2");
const bus = @import("bus.zig");
const cpu = @import("cpu.zig");
const rsp = @import("rsp.zig");
const ai = @import("ai.zig");
const vi = @import("vi.zig");
const Controller = packed struct {
dr : bool = false,
dl : bool = false,
dd : bool = false,
du : bool = false,
start: bool = false,
z : bool = false,
b : bool = false,
a : bool = false,
cr : bool = false,
cl : bool = false,
cd : bool = false,
cu : bool = false,
r : bool = false,
l : bool = false,
_pad0: bool = false,
reset: bool = false,
x : u8 = 0,
y : u8 = 0,
};
const Screen = struct {
width : c_int = undefined,
height: c_int = undefined,
stride: c_int = undefined,
texture : ?*SDL.SDL_Texture = null,
renderer: ?*SDL.SDL_Renderer = null,
};
const isFastBoot = true;
const cpuCyclesFrame : i64 = 93_750_000 / 60;
const cpuCyclesScanline: i64 = cpuCyclesFrame / 512;
pub var controller: Controller = Controller{};
var screen: Screen = Screen{};
/// Initializes all submodules
/// TODO: this is terrible clean this up
pub fn run(romPath: []const u8) anyerror!void {
if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0) {
sdlPanic();
}
defer SDL.SDL_Quit();
var window = SDL.SDL_CreateWindow(
"Vela",
SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED,
960, 720,
SDL.SDL_WINDOW_SHOWN,
) orelse sdlPanic();
defer _ = SDL.SDL_DestroyWindow(window);
screen.renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RENDERER_ACCELERATED) orelse sdlPanic();
defer _ = SDL.SDL_DestroyRenderer(screen.renderer);
if (SDL.SDL_RenderSetLogicalSize(screen.renderer, 960, 720) < 0) {
sdlPanic();
}
if(SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_VSYNC, "1") < 0) {
sdlPanic();
}
// Get allocator
var alloc = std.heap.page_allocator;
var fb = try alloc.alloc(u8, 640 * 480 * 2);
// Initialize submodules
try bus.init(alloc, romPath, isFastBoot);
defer bus.deinit(alloc);
cpu.init(isFastBoot);
SDL.SDL_ShowWindow(window);
changeScreen(320, 3);
var cyclesRem: i64 = cpuCyclesFrame;
var lineRem : i64 = cpuCyclesScanline;
mainLoop: while (true) {
const c = cpu.step();
rsp.step();
ai.step(c);
cyclesRem -= c;
lineRem -= c;
if (cyclesRem <= 0) {
cyclesRem += cpuCyclesFrame;
if (!pollKeys()) {
break :mainLoop;
}
if (screen.stride == 2) {
var i: usize = 0;
while (i < (screen.width * screen.height)) {
fb[i * 2 + 0] = bus.ram[vi.getOrigin() + i * 2 + 1];
fb[i * 2 + 1] = bus.ram[vi.getOrigin() + i * 2 + 0];
i += 1;
}
if (SDL.SDL_UpdateTexture(screen.texture, null, @ptrCast(*u8, fb), screen.width * screen.stride) < 0) {
sdlPanic();
}
} else {
if (SDL.SDL_UpdateTexture(screen.texture, null, @ptrCast(*u8, &bus.ram[vi.getOrigin()]), screen.width * screen.stride) < 0) {
sdlPanic();
}
}
if (SDL.SDL_RenderCopy(screen.renderer, screen.texture, null, null) < 0) {
sdlPanic();
}
SDL.SDL_RenderPresent(screen.renderer);
}
if (lineRem <= 0) {
lineRem += cpuCyclesScanline;
vi.incCurrentV();
}
}
alloc.free(fb);
var x = SDL.SDL_DestroyTexture(screen.texture);
}
fn pollKeys() bool {
const keyState = SDL.SDL_GetKeyboardState(null);
var e: SDL.SDL_Event = undefined;
if (SDL.SDL_PollEvent(&e) != 0) {
switch (e.type) {
SDL.SDL_KEYDOWN, SDL.SDL_KEYUP => {
controller.dr = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_RIGHT)] != 0;
controller.dl = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_LEFT)] != 0;
controller.dd = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_DOWN)] != 0;
controller.du = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_UP)] != 0;
controller.start = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_r)] != 0;
controller.z = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_e)] != 0;
controller.b = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_a)] != 0;
controller.a = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_s)] != 0;
controller.cr = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_g)] != 0;
controller.cl = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_d)] != 0;
controller.cd = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_f)] != 0;
controller.cu = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_r)] != 0;
controller.r = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_w)] != 0;
controller.l = keyState[SDL.SDL_GetScancodeFromKey(SDL.SDLK_q)] != 0;
},
SDL.SDL_QUIT => {
return false;
},
else => {}
}
}
return true;
}
pub fn changeScreen(width: c_int, pFmt: u2) void {
if (width == 320) {
screen.height = 240;
} else if (width == 640) {
screen.height = 480;
} else {
screen.height = 240;
}
screen.width = width;
if (pFmt == 2) {
screen.stride = 2;
screen.texture = SDL.SDL_CreateTexture(
screen.renderer,
SDL.SDL_PIXELFORMAT_RGBA5551, SDL.SDL_TEXTUREACCESS_STREAMING,
screen.width, screen.height
) orelse sdlPanic();
}
else if (pFmt == 0 or pFmt == 3) {
screen.stride = 4;
screen.texture = SDL.SDL_CreateTexture(
screen.renderer,
SDL.SDL_PIXELFORMAT_XBGR8888, SDL.SDL_TEXTUREACCESS_STREAMING,
screen.width, screen.height
) orelse sdlPanic();
} else {
}
}
/// Taken from SDL.zig
fn sdlPanic() noreturn {
const str = @as(?[*:0]const u8, SDL.SDL_GetError()) orelse "unknown error";
@panic(std.mem.sliceTo(str, 0));
}
|
src/core/n64.zig
|
const combn = @import("../combn/combn.zig");
const Result = combn.gllparser.Result;
const Parser = combn.gllparser.Parser;
const Error = combn.gllparser.Error;
const Context = combn.gllparser.Context;
const PosKey = combn.gllparser.PosKey;
const ParserPath = combn.gllparser.ParserPath;
const Sequence = combn.gllparser.Sequence;
const SequenceValue = combn.combinator.sequence.Value;
const Repeated = combn.combinator.Repeated;
const RepeatedValue = combn.combinator.repeated.Value;
const Literal = combn.parser.Literal;
const LiteralValue = combn.parser.literal.Value;
const OneOf = combn.combinator.OneOf;
const MapTo = combn.combinator.MapTo;
const Optional = combn.combinator.Optional;
const String = @import("String.zig");
const Node = @import("Node.zig");
const Compilation = @import("Compilation.zig");
const Identifier = @import("identifier.zig").Identifier;
const CompilerContext = @import("CompilerContext.zig");
const grammar = @import("grammar.zig");
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const assert = std.debug.assert;
pub const CompilerResult = struct {
compilation: Result(Compilation),
ctx: Context(*CompilerContext, Compilation),
compilerContext: *CompilerContext,
pub fn deinit(self: *const @This(), allocator: mem.Allocator) void {
self.ctx.deinit();
self.compilerContext.deinit(allocator);
}
};
pub fn compile(allocator: mem.Allocator, syntax: []const u8) !CompilerResult {
const dsl_parser = try grammar.init(allocator);
defer dsl_parser.deinit(allocator, null);
var compilerContext = try CompilerContext.init(allocator);
var ctx = try Context(*CompilerContext, Compilation).init(allocator, syntax, compilerContext);
try dsl_parser.parse(&ctx);
var sub = ctx.subscribe();
var compilation = sub.next();
assert(sub.next() == null); // our grammar is never ambiguous
if (compilation == null) {
return CompilerResult{
.compilation = Result(Compilation).initError(ctx.offset, "failed to compile"),
.compilerContext = compilerContext,
.ctx = ctx,
};
}
return CompilerResult{
.compilation = compilation.?,
.compilerContext = compilerContext,
.ctx = ctx,
};
}
test "DSL" {
nosuspend {
const allocator = testing.allocator;
// Compile the regexp.
var compilerResult = try compile(allocator, "/a/");
defer compilerResult.deinit(allocator);
switch (compilerResult.compilation.result) {
.err => |e| @panic(e),
.value => {},
}
var program = compilerResult.compilation.result.value;
// Run the regexp.
var input = "//";
var ctx = try Context(void, *Node).init(allocator, input, {});
defer ctx.deinit();
try program.value.parser.ptr.parse(&ctx);
var sub = ctx.subscribe();
var first = sub.next().?;
try testing.expectEqualStrings("TODO(slimsag): value from parsing regexp!", first.result.value.name.value);
try testing.expectEqual(@as(usize, 0), first.offset);
try testing.expect(sub.next() == null);
}
}
|
src/dsl/compiler.zig
|
const std = @import("std");
const xml = @import("lib.zig");
const attributes_field_name = "__attributes__";
const item_field_name = "__item__";
pub fn StructTraverser(comptime Self: type) type {
return struct {
pub fn traverseStruct(self: *Self, input: anytype, parent: xml.Node) !void {
inline for (@typeInfo(@TypeOf(input.*)).Struct.fields) |field| {
try self.traverseField(&@field(input, field.name), field.name, parent);
}
}
pub fn traverseField(self: *Self, input: anytype, comptime name: []const u8, parent: xml.Node) !void {
switch (@typeInfo(@TypeOf(input.*))) {
.Struct =>
if (comptime std.mem.eql(u8, name, attributes_field_name)) {
try self.handleAttributes(input, parent.Element);
}
else {
try self.handleSubStruct(name, input, parent);
}
,
.Pointer => |p| {
if (@typeInfo(p.child) == .Struct) {
return self.handlePointer(name, input, parent.Element);
}
if (p.child == u8) {
return self.handleLeafNode(input, name, parent.Element, Self.handleString);
}
@compileError("Field " ++ name ++ " has unsupported pointer type " ++ @typeName(p.child));
},
.Optional => try self.handleOptional(name, input, parent.Element),
.Int => try self.handleLeafNode(input, name, parent.Element, Self.handleInt),
.Bool => try self.handleLeafNode(input, name, parent.Element, Self.handleBool),
else => @compileError("Unsupported field " ++ name ++ " inside struct")
}
}
pub fn handleLeafNode(self: *Self, input: anytype, comptime name: []const u8, parent: xml.Element, forwardFn: anytype) !void {
if (comptime !std.mem.eql(u8, name, item_field_name)) {
return self.handleSingleItem(name, input, parent);
}
return forwardFn(self, name, input, parent);
}
};
}
|
src/traverser.zig
|
pub const FileType = enum(i32) {
invalid = 0,
gltf = 1,
glb = 2,
_,
};
pub const Result = enum(i32) {
success = 0,
data_too_short = 1,
unknown_format = 2,
invalid_json = 3,
invalid_gltf = 4,
invalid_options = 5,
file_not_found = 6,
io_error = 7,
out_of_memory = 8,
legacy_gltf = 9,
_,
};
pub const MemoryOption = extern struct {
alloc: ?fn (*anyopaque, usize) callconv(.C) ?*anyopaque,
free: ?fn (*anyopaque, *anyopaque) callconv(.C) void,
user_data: ?*anyopaque,
};
pub const FileOption = extern struct {
read: ?fn (*const MemoryOption, *const FileOption, [*:0]const u8, [*c]usize, [*c]?*anyopaque) callconv(.C) Result,
release: ?fn (*const MemoryOption, *const FileOption, ?*anyopaque) callconv(.C) void,
user_data: ?*anyopaque,
};
pub const Option = extern struct {
type: FileType,
json_token_count: usize,
memory: MemoryOption,
file: FileOption,
};
pub const BufferViewType = enum(i32) {
invalid = 0,
indices = 1,
vertices = 2,
_,
};
pub const AttributeType = enum(i32) {
invalid = 0,
position = 1,
normal = 2,
tangent = 3,
texcoord = 4,
color = 5,
joints = 6,
weights = 7,
_,
};
pub const ComponentType = enum(i32) {
invalid = 0,
r_8 = 1,
r_8u = 2,
r_16 = 3,
r_16u = 4,
r_32u = 5,
r_32f = 6,
_,
};
pub const Type = enum(i32) {
invalid = 0,
scalar = 1,
vec2 = 2,
vec3 = 3,
vec4 = 4,
mat2 = 5,
mat3 = 6,
mat4 = 7,
_,
};
pub const PrimitiveType = enum(i32) {
points = 0,
lines = 1,
line_loop = 2,
line_strip = 3,
triangles = 4,
triangle_strip = 5,
triangle_fan = 6,
_,
};
pub const AlphaMode = enum(i32) {
@"opaque" = 0,
mask = 1,
blend = 2,
_,
};
pub const AnimationPathType = enum(i32) {
invalid = 0,
translation = 1,
rotation = 2,
scale = 3,
weights = 4,
_,
};
pub const InterpolationType = enum(i32) {
linear = 0,
step = 1,
cubic_spline = 2,
_,
};
pub const CameraType = enum(i32) {
invalid = 0,
perspective = 1,
orthographic = 2,
_,
};
pub const LightType = enum(i32) {
invalid = 0,
directional = 1,
point = 2,
spot = 3,
_,
};
pub const DataFreeMethod = enum(i32) {
none = 0,
file_release = 1,
memory_free = 2,
_,
};
pub const Extra = extern struct {
start_offset: usize,
end_offset: usize,
};
pub const Extensions = extern struct {
name: [*:0]u8,
data: [*c]u8,
};
pub const Buffer = extern struct {
name: ?[*:0]u8,
size: usize,
uri: ?[*:0]u8,
data: ?*anyopaque,
data_free_method: DataFreeMethod,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const CompressionMode = enum(i32) {
invalid = 0,
attributes = 1,
triangles = 2,
indices = 3,
};
pub const CompressionFilter = enum(i32) {
none = 0,
octahedral = 1,
quaternion = 2,
exponential = 3,
};
pub const MeshoptCompression = extern struct {
buffer: *Buffer,
offset: usize,
size: usize,
stride: usize,
count: usize,
mode: CompressionMode,
filter: CompressionFilter,
};
pub const BufferView = extern struct {
name: ?[*:0]u8,
buffer: *Buffer,
offset: usize,
size: usize,
stride: usize,
type: BufferViewType,
data: ?*anyopaque,
has_meshopt_compression: bool,
meshopt_compression: MeshoptCompression,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const AccessorSparse = extern struct {
count: usize,
indices_buffer_view: *BufferView,
indices_byte_offset: usize,
indices_component_type: ComponentType,
values_buffer_view: *BufferView,
values_byte_offset: usize,
extras: Extra,
indices_extras: Extra,
values_extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
indices_extensions_count: usize,
indices_extensions: ?[*]Extensions,
values_extensions_count: usize,
values_extensions: ?[*]Extensions,
};
pub const Accessor = extern struct {
name: ?[*:0]u8,
component_type: ComponentType,
normalized: bool,
type: Type,
offset: usize,
count: usize,
stride: usize,
buffer_view: ?*BufferView,
has_min: bool,
min: [16]f32,
has_max: bool,
max: [16]f32,
is_sparse: bool,
sparse: AccessorSparse,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Attribute = extern struct {
name: ?[*:0]u8,
type: AttributeType,
index: i32,
data: *Accessor,
};
pub const Image = extern struct {
name: ?[*:0]u8,
uri: ?[*:0]u8,
buffer_view: ?*BufferView,
mime_type: ?[*:0]u8,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Sampler = extern struct {
name: ?[*:0]u8,
mag_filter: i32,
min_filter: i32,
wrap_s: i32,
wrap_t: i32,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Texture = extern struct {
name: ?[*:0]u8,
image: ?*Image,
sampler: ?*Sampler,
has_basisu: bool,
basisu_image: ?*Image,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const TextureTransform = extern struct {
offset: [2]f32,
rotation: f32,
scale: [2]f32,
has_texcoord: bool,
texcoord: i32,
};
pub const TextureView = extern struct {
texture: *Texture,
texcoord: i32,
scale: f32,
has_transform: bool,
transform: TextureTransform,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const PbrMetallicRoughness = extern struct {
base_color_texture: TextureView,
metallic_roughness_texture: TextureView,
base_color_factor: [4]f32,
metallic_factor: f32,
roughness_factor: f32,
extras: Extra,
};
pub const PbrSpecularGlossiness = extern struct {
diffuse_texture: TextureView,
specular_glossiness_texture: TextureView,
diffuse_factor: [4]f32,
specular_factor: [3]f32,
glossiness_factor: f32,
};
pub const ClearCoat = extern struct {
clearcoat_texture: TextureView,
clearcoat_roughness_texture: TextureView,
clearcoat_normal_texture: TextureView,
clearcoat_factor: f32,
clearcoat_roughness_factor: f32,
};
pub const Transmission = extern struct {
transmission_texture: TextureView,
transmission_factor: f32,
};
pub const Ior = extern struct {
ior: f32,
};
pub const Specular = extern struct {
specular_texture: TextureView,
specular_color_texture: TextureView,
specular_color_factor: [3]f32,
specular_factor: f32,
};
pub const Volume = extern struct {
thickness_texture: TextureView,
thickness_factor: f32,
attenuation_color: [3]f32,
attenuation_distance: f32,
};
pub const Sheen = extern struct {
sheen_color_texture: TextureView,
sheen_color_factor: [3]f32,
sheen_roughness_texture: TextureView,
sheen_roughness_factor: f32,
};
pub const EmissiveStrength = extern struct {
emissive_strength: f32,
};
pub const Material = extern struct {
name: ?[*:0]u8,
has_pbr_metallic_roughness: bool,
has_pbr_specular_glossiness: bool,
has_clearcoat: bool,
has_transmission: bool,
has_volume: bool,
has_ior: bool,
has_specular: bool,
has_sheen: bool,
has_emissive_strength: bool,
pbr_metallic_roughness: PbrMetallicRoughness,
pbr_specular_glossiness: PbrSpecularGlossiness,
clearcoat: ClearCoat,
ior: Ior,
specular: Specular,
sheen: Sheen,
transmission: Transmission,
volume: Volume,
emissive_strength: EmissiveStrength,
normal_texture: TextureView,
occlusion_texture: TextureView,
emissive_texture: TextureView,
emissive_factor: [3]f32,
alpha_mode: AlphaMode,
alpha_cutoff: f32,
double_sided: bool,
unlit: bool,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const MaterialMapping = extern struct {
variant: usize,
material: *Material,
extras: Extra,
};
pub const MorphTarget = extern struct {
attributes: [*]Attribute,
attributes_count: usize,
};
pub const DracoMeshCompression = extern struct {
buffer_view: *BufferView,
attributes: [*]Attribute,
attributes_count: usize,
};
pub const Primitive = extern struct {
type: PrimitiveType,
indices: ?*Accessor,
material: ?*Material,
attributes: [*]Attribute,
attributes_count: usize,
targets: ?[*]MorphTarget,
targets_count: usize,
extras: Extra,
has_draco_mesh_compression: bool,
draco_mesh_compression: DracoMeshCompression,
mappings: [*]MaterialMapping,
mappings_count: usize,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Mesh = extern struct {
name: ?[*:0]u8,
primitives: [*]Primitive,
primitives_count: usize,
weights: [*]f32,
weights_count: usize,
target_names: ?[*][*:0]u8,
target_names_count: usize,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Skin = extern struct {
name: ?[*:0]u8,
joints: [*]*Node,
joints_count: usize,
skeleton: ?*Node,
inverse_bind_matrices: ?*Accessor,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const CameraPerspective = extern struct {
has_aspect_ratio: bool,
aspect_ratio: f32,
yfov: f32,
has_zfar: bool,
zfar: f32,
znear: f32,
extras: Extra,
};
pub const CameraOrthographic = extern struct {
xmag: f32,
ymag: f32,
zfar: f32,
znear: f32,
extras: Extra,
};
const CameraMode = extern union {
perspective: CameraPerspective,
orthographic: CameraOrthographic,
};
pub const Camera = extern struct {
name: ?[*:0]u8,
type: CameraType,
data: CameraMode,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Light = extern struct {
name: ?[*:0]u8,
color: [3]f32,
intensity: f32,
type: LightType,
range: f32,
spot_inner_cone_angle: f32,
spot_outer_cone_angle: f32,
extras: Extra,
};
pub const Node = extern struct {
name: ?[*:0]u8,
parent: *Node,
children: ?[*]*Node,
children_count: usize,
skin: ?*Skin,
mesh: ?*Mesh,
camera: ?*Camera,
light: ?*Light,
weights: [*]f32,
weights_count: usize,
has_translation: bool,
has_rotation: bool,
has_scale: bool,
has_matrix: bool,
translation: [3]f32,
rotation: [4]f32,
scale: [3]f32,
matrix: [16]f32,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Scene = extern struct {
name: ?[*:0]u8,
nodes: ?[*]*Node,
nodes_count: usize,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const AnimationSampler = extern struct {
input: *Accessor,
output: *Accessor,
interpolation: InterpolationType,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const AnimationChannel = extern struct {
sampler: *AnimationSampler,
target_node: *Node,
target_path: AnimationPathType,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Animation = extern struct {
name: ?[*:0]u8,
samplers: [*]AnimationSampler,
samplers_count: usize,
channels: [*]AnimationChannel,
channels_count: usize,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const MaterialVariant = extern struct {
name: ?[*:0]u8,
extras: Extra,
};
pub const Asset = extern struct {
copyright: ?[*:0]u8,
generator: ?[*:0]u8,
version: [*:0]u8,
min_version: ?[*:0]u8,
extras: Extra,
extensions_count: usize,
extensions: ?[*]Extensions,
};
pub const Data = extern struct {
file_type: FileType,
file_data: *anyopaque,
asset: Asset,
meshes: [*]Mesh,
meshes_count: usize,
materials: [*]Material,
materials_count: usize,
accessors: [*]Accessor,
accessors_count: usize,
buffer_views: [*]BufferView,
buffer_views_count: usize,
buffers: [*]Buffer,
buffers_count: usize,
images: [*]Image,
images_count: usize,
textures: [*]Texture,
textures_count: usize,
samplers: [*]Sampler,
samplers_count: usize,
skins: [*]Skin,
skins_count: usize,
cameras: [*]Camera,
cameras_count: usize,
lights: [*]Light,
lights_count: usize,
nodes: [*]Node,
nodes_count: usize,
scenes: [*]Scene,
scenes_count: usize,
scene: *Scene,
animations: [*]Animation,
animations_count: usize,
variants: [*]MaterialVariant,
variants_count: usize,
extras: Extra,
data_extensions_count: usize,
data_extensions: ?[*]Extensions,
extensions_used: [*][*:0]u8,
extensions_used_count: usize,
extensions_required: [*][*:0]u8,
extensions_required_count: usize,
json: [*]const u8,
json_size: usize,
bin: ?*const anyopaque,
bin_size: usize,
memory: MemoryOption,
file: FileOption,
};
pub extern fn cgltf_parse(options: *const Option, data: *const anyopaque, size: usize, out_data: **Data) Result;
pub extern fn cgltf_parse_file(options: *const Option, path: [*:0]const u8, out_data: **Data) Result;
pub extern fn cgltf_load_buffers(options: *const Option, data: *Data, gltf_path: [*:0]const u8) Result;
pub extern fn cgltf_load_buffer_base64(options: *const Option, size: usize, base64: [*c]const u8, out_data: [*c]?*anyopaque) Result;
pub extern fn cgltf_decode_string(string: [*:0]u8) usize;
pub extern fn cgltf_decode_uri(uri: [*:0]u8) usize;
pub extern fn cgltf_validate(data: *Data) Result;
pub extern fn cgltf_free(data: *Data) void;
pub extern fn cgltf_node_transform_local(node: *const Node, out_matrix: [*]f32) void;
pub extern fn cgltf_node_transform_world(node: *const Node, out_matrix: [*]f32) void;
pub extern fn cgltf_accessor_read_float(accessor: *const Accessor, index: usize, out: *f32, element_size: usize) bool;
pub extern fn cgltf_accessor_read_uint(accessor: *const Accessor, index: usize, out: *u32, element_size: usize) bool;
pub extern fn cgltf_accessor_read_index(accessor: *const Accessor, index: usize) usize;
pub extern fn cgltf_num_components(@"type": Type) usize;
pub extern fn cgltf_accessor_unpack_floats(accessor: *const Accessor, out: [*]f32, float_count: usize) usize;
pub extern fn cgltf_copy_extras_json(data: [*c]const Data, extras: [*c]const Extra, dest: [*c]u8, dest_size: [*c]usize) Result;
|
cgltf.zig
|
const std = @import("std");
const input = @embedFile("data/input02");
usingnamespace @import("util.zig");
pub fn main() !void {
var valid_count1: usize = 0;
var valid_count2: usize = 0;
var reader = LineIterator.init(input);
while (reader.next()) |line| {
const e = Entry.parse(line) orelse return error.InvalidEntryFormat;
if (e.isValid1()) {
valid_count1 += 1;
}
if (e.isValid2()) {
valid_count2 += 1;
}
}
print("[Part1] Number of valid passwords: {}", .{valid_count1});
print("[Part2] Number of valid passwords: {}", .{valid_count2});
}
const Entry = struct {
const Self = @This();
policy_min: usize,
policy_max: usize,
policy_char: u8,
password: []const u8,
pub fn isValid1(self: Self) bool {
var count: usize = 0;
for (self.password) |c| {
if (c == self.policy_char) {
count += 1;
}
}
return count >= self.policy_min and count <= self.policy_max;
}
pub fn isValid2(self: Self) bool {
const index1 = self.policy_min - 1;
const index2 = self.policy_max - 1;
const match1 = self.password[index1] == self.policy_char;
const match2 = self.password[index2] == self.policy_char;
return match1 != match2;
}
pub fn parse(line: []const u8) ?Entry {
var tokenizer = std.mem.tokenize(line, " ");
const min_max = tokenizer.next() orelse return null;
const min_max_separator = std.mem.indexOf(u8, min_max, "-") orelse return null;
const min = std.fmt.parseUnsigned(usize, min_max[0..min_max_separator], 10) catch return null;
const max = std.fmt.parseUnsigned(usize, min_max[min_max_separator+1..], 10) catch return null;
const char = tokenizer.next() orelse return null;
const password = tokenizer.rest();
return Entry {
.policy_min = min,
.policy_max = max,
.policy_char = char[0],
.password = password,
};
}
};
|
src/day02.zig
|
pub const libpq = @cImport({
@cInclude("libpq-fe.h");
});
pub const Raw = struct {
pub const ConnStatusType = enum(libpq.ConnStatusType) {
CONNECTION_OK = libpq.CONNECTION_OK,
CONNECTION_BAD = libpq.CONNECTION_BAD,
CONNECTION_STARTED = libpq.CONNECTION_STARTED,
CONNECTION_MADE = libpq.CONNECTION_MADE,
CONNECTION_AWAITING_RESPONSE = libpq.CONNECTION_AWAITING_RESPONSE,
CONNECTION_AUTH_OK = libpq.CONNECTION_AUTH_OK,
CONNECTION_SETENV = libpq.CONNECTION_SETENV,
CONNECTION_SSL_STARTUP = libpq.CONNECTION_SSL_STARTUP,
CONNECTION_NEEDED = libpq.CONNECTION_NEEDED,
CONNECTION_CHECK_WRITABLE = libpq.CONNECTION_CHECK_WRITABLE,
CONNECTION_CONSUME = libpq.CONNECTION_CONSUME,
CONNECTION_GSS_STARTUP = libpq.CONNECTION_GSS_STARTUP,
CONNECTION_CHECK_TARGET = libpq.CONNECTION_CHECK_TARGET
};
pub fn PQconnectdb(conninfo: ?[*:0]const u8) error{OutOfMemory}!*libpq.PGconn {
const conn_ptr = libpq.PQconnectdb(conninfo orelse "");
if (conn_ptr) |conn| {
return conn;
} else {
return error.OutOfMemory;
}
}
pub fn PQfinish(conn: *libpq.PGconn) void {
libpq.PQfinish(conn);
}
pub fn PQreset(conn: *libpq.PGconn) void {
libpq.PQreset(conn);
}
pub fn PQstatus(conn: *libpq.PGconn) ConnStatusType {
return switch (libpq.PQstatus(conn)) {
@enumToInt(ConnStatusType.CONNECTION_OK) => ConnStatusType.CONNECTION_OK,
@enumToInt(ConnStatusType.CONNECTION_BAD) => ConnStatusType.CONNECTION_STARTED,
@enumToInt(ConnStatusType.CONNECTION_STARTED) => ConnStatusType.CONNECTION_STARTED,
@enumToInt(ConnStatusType.CONNECTION_MADE) => ConnStatusType.CONNECTION_MADE,
@enumToInt(ConnStatusType.CONNECTION_AWAITING_RESPONSE) => ConnStatusType.CONNECTION_AWAITING_RESPONSE,
@enumToInt(ConnStatusType.CONNECTION_AUTH_OK) => ConnStatusType.CONNECTION_AUTH_OK,
@enumToInt(ConnStatusType.CONNECTION_SETENV) => ConnStatusType.CONNECTION_SETENV,
@enumToInt(ConnStatusType.CONNECTION_SSL_STARTUP) => ConnStatusType.CONNECTION_SSL_STARTUP,
@enumToInt(ConnStatusType.CONNECTION_NEEDED) => ConnStatusType.CONNECTION_NEEDED,
@enumToInt(ConnStatusType.CONNECTION_CHECK_WRITABLE) => ConnStatusType.CONNECTION_CHECK_WRITABLE,
@enumToInt(ConnStatusType.CONNECTION_CONSUME) => ConnStatusType.CONNECTION_CONSUME,
@enumToInt(ConnStatusType.CONNECTION_GSS_STARTUP) => ConnStatusType.CONNECTION_GSS_STARTUP,
@enumToInt(ConnStatusType.CONNECTION_CHECK_TARGET) => ConnStatusType.CONNECTION_CHECK_TARGET,
else => unreachable
};
}
};
|
src/connect.zig
|
const std = @import("std");
const process = std.process;
const os = std.os;
const fs = std.fs;
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const posix = @import("./os/posix.zig");
const windows = @import("./os/windows.zig");
pub const BohioError = error{
CouldNotGetCurrentWorkingDirectory,
HomeNotFound,
ClutchHomeNotFound,
};
/// Get the home directory for the current user in a platform-independent way.
/// Returns the path of the current user's home directory if known.
///
/// # Unix
///
/// Returns the value of the `HOME` environment variable
///
/// # Windows
///
/// Returns the value of the `USERPROFILE` environment variable
///
/// # Errors
///
/// BohioError
///
pub fn homeDir(allocator: *Allocator) ?[]const u8 {
switch (builtin.os.tag) {
.windows => return windows.homeDir(allocator) catch null,
else => return posix.homeDir(allocator) catch null,
}
}
/// Get the clutch directory, using the following heuristics:
///
/// - The value of the `CLUTCH_HOME` environment variable, if it is
/// an absolute path.
/// - The value of the current working directory joined with the value
/// of the `CLUTCH_HOME` environment variable, if `CLUTCH_HOME` is a
/// relative directory.
/// - The `.clutch` directory in the user's home directory, as reported
/// by the `homeDir` function.
///
/// # Errors
///
/// BohioError
///
pub fn clutchHome(allocator: *Allocator) ?[]const u8 {
switch (builtin.os.tag) {
.windows => return windows.clutchHome(allocator) catch null,
else => return posix.clutchHome(allocator) catch null,
}
}
test "homeDir()" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var allocator = &arena.allocator;
const home = homeDir(allocator) orelse "N/A";
defer allocator.free(home);
std.debug.print("Home directory = {}\n", .{home});
}
test "clutchHome()" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var allocator = &arena.allocator;
const clutch_home = clutchHome(allocator) orelse "N/A";
defer allocator.free(clutch_home);
std.debug.print("Clutch Home directory = {}\n", .{clutch_home});
}
|
src/lib.zig
|
const inputFile = @embedFile("./input/day11.txt");
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Str = []const u8;
const BitSet = std.DynamicBitSet;
const assert = std.debug.assert;
const tokenize = std.mem.tokenize;
const print = std.debug.print;
fn sort(comptime T: type, items: []T) void {
std.sort.sort(T, items, {}, comptime std.sort.asc(T));
}
// Mutates input, returning the number of flashes
fn runRound(input: Input) usize {
// We just do the simple thing
// inc each octopus
var nFlashes: usize = 0;
for (input.items) |*octopus| {
octopus.* += 1;
}
// check for octopi above 9
for (input.items) |octopus, i| {
if (octopus > 9) {
nFlashes += propagateFlash(input, i);
}
}
print("{any}\n", .{input});
// Reset flashed octopi
for (input.items) |*octopus| {
if (octopus.* < 0) octopus.* = 0;
}
return nFlashes;
}
/// An octopus has at most 8 neighbors, so its score can increase by max 8 only.
/// This way, flashed octopi will always be negative (and will show up when printed!)
const flashedOctopus: i8 = -9;
/// At position pos, a flash occurs
/// increment the
fn propagateFlash(input: Input, pos: usize) usize {
if (input.items[pos] < 9) {
input.items[pos] += 1;
return 0;
}
var res: usize = 1;
input.items[pos] = flashedOctopus;
const row = pos / input.nCols;
const col = pos % input.nCols;
// zig fmt: off
// left, right
if (col > 0) res += propagateFlash(input, pos - 1);
if (col < input.nCols - 1) res += propagateFlash(input, pos + 1);
// up, up L, up R
if (row > 0) res += propagateFlash(input, pos - input.nCols);
if (row > 0
and col > 0) res += propagateFlash(input, pos - input.nCols - 1);
if (row > 0
and col < input.nCols - 1) res += propagateFlash(input, pos - input.nCols + 1);
// down, down L, down R
if (row < input.nRows - 1) res += propagateFlash(input, pos + input.nCols);
if (row < input.nRows - 1
and col > 0) res += propagateFlash(input, pos + input.nCols - 1);
if (row < input.nRows - 1
and col < input.nCols - 1) res += propagateFlash(input, pos + input.nCols + 1);
// zig fmt: on
return res;
}
fn partOne(input: Input, nRounds: usize) usize {
var res: usize = 0;
var round: usize = 1;
while (round <= nRounds) : (round += 1) {
res += runRound(input);
}
return res;
}
fn partTwo(input: Input) usize {
var round: usize = 1;
print("{any}\n", .{input});
while (true) : (round += 1) {
print("Round {d}\n", .{round});
if (runRound(input) == input.items.len) {
// All flashed!
return round;
}
}
}
pub fn main() !void {
// Standard boilerplate for Aoc problems
const stdout = std.io.getStdOut().writer();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var gpaAllocator = gpa.allocator();
defer assert(!gpa.deinit()); // Check for memory leaks
var arena = std.heap.ArenaAllocator.init(gpaAllocator);
defer arena.deinit();
var allocator = arena.allocator(); // use an arena
var input = try parseInput(inputFile, allocator);
var input2 = try input.clone(allocator);
const p1 = partOne(input, 100);
const p2 = partTwo(input2);
try stdout.print("Part1: {d}\nPart2: {d}", .{ p1, p2 });
}
const Input = struct {
items: []i8,
nRows: usize,
nCols: usize,
pub fn clone(self: @This(), allocator: Allocator) !@This() {
const items = try allocator.dupe(i8, self.items);
return @This(){ .items = items, .nRows = self.nRows, .nCols = self.nCols };
}
pub fn deinit(self: @This(), allocator: Allocator) void {
allocator.free(self.items);
}
// printf implementation
pub fn format(self: @This(), comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
assert(self.items.len == (self.nRows * self.nCols));
var row: usize = 0;
while (row < self.nRows) : (row += 1) {
var col: u32 = 0;
while (col < self.nCols) : (col += 1) {
const x = self.items[row * self.nCols + col];
if (x < 0) {
try writer.print("*", .{});
} else {
try writer.print("{d}", .{x});
}
}
try writer.print("\n", .{});
}
try writer.print("\n", .{});
}
};
fn parseInput(input: Str, allocator: Allocator) !Input {
var lines = ArrayList(i8).init(allocator);
errdefer lines.deinit();
const nCols = std.mem.indexOfScalar(u8, input, '\n').?;
var nRows: usize = 0;
var it = tokenize(u8, input, "\n");
while (it.next()) |line| : (nRows += 1) {
for (line) |c| {
try lines.append(@intCast(i8, c - '0'));
}
}
return Input{ .items = lines.toOwnedSlice(), .nRows = nRows, .nCols = nCols };
}
test "Part 1 simple" {
const testInput =
\\11111
\\19991
\\19191
\\19991
\\11111
\\
;
var allocator = std.testing.allocator;
const input = try parseInput(testInput, allocator);
defer input.deinit(allocator);
try std.testing.expectEqual(@as(usize, 9), partOne(input, 3));
}
test "Part 1" {
const testInput =
\\5483143223
\\2745854711
\\5264556173
\\6141336146
\\6357385478
\\4167524645
\\2176841721
\\6882881134
\\4846848554
\\5283751526
\\
;
var allocator = std.testing.allocator;
const input = try parseInput(testInput, allocator);
defer input.deinit(allocator);
try std.testing.expectEqual(@as(usize, 204), partOne(input, 10));
try std.testing.expectEqual(@as(usize, 1656 - 204), partOne(input, 90));
}
test "Part 2" {
const testInput =
\\5483143223
\\2745854711
\\5264556173
\\6141336146
\\6357385478
\\4167524645
\\2176841721
\\6882881134
\\4846848554
\\5283751526
\\
;
var allocator = std.testing.allocator;
const input = try parseInput(testInput, allocator);
defer input.deinit(allocator);
try std.testing.expectEqual(@as(usize, 195), partTwo(input));
}
|
src/day11.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const int = i64;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day11.txt");
const Rec = struct {
val: int,
};
pub fn main() !void {
var width: usize = 0;
var height: usize = 0;
// Load the map with a border of 9 values
const map = blk: {
var map = List(u8).init(gpa);
errdefer map.deinit();
var lines = tokenize(u8, data, "\r\n");
while (lines.next()) |line| {
if (line.len == 0) { continue; }
if (width == 0) {
width = line.len;
try map.appendNTimes(9, width + 2);
} else {
assert(width == line.len);
}
try map.append(9);
for (line) |c| {
try map.append(c - '0');
}
height += 1;
try map.append(9);
}
try map.appendNTimes(9, width + 2);
break :blk map.toOwnedSlice();
};
defer gpa.free(map);
const pitch = width + 2;
const start = pitch + 1;
var flashes = std.ArrayList(usize).init(gpa);
defer flashes.deinit();
var part1: usize = 0;
var day: usize = 0;
var all_flash_day: ?usize = null;
while (day < 100 or all_flash_day == null) : (day += 1) {
// Clear the border
{
std.mem.set(u8, map[0..pitch], 0);
std.mem.set(u8, map[pitch + pitch*height..], 0);
var y: usize = 0;
while (y < height) : (y += 1) {
const offset = pitch + pitch * y;
map[offset] = 0;
map[offset + pitch - 1] = 0;
}
}
var flashes_this_day: usize = 0;
// All octopuses gain 1 charge
{
var y: usize = 0;
while (y < height) : (y += 1) {
var x: usize = 0;
while (x < width) : (x += 1) {
const idx = y * pitch + x + start;
map[idx] += 1;
if (map[idx] == 10) {
flashes_this_day += 1;
try flashes.append(idx);
}
}
}
}
// Flashing octopuses increase charge of neighbors
while (flashes.popOrNull()) |flash| {
const neighbors = [_]usize {
flash - pitch - 1,
flash - pitch,
flash - pitch + 1,
flash - 1,
flash + 1,
flash + pitch - 1,
flash + pitch,
flash + pitch + 1,
};
for (neighbors) |neigh| {
map[neigh] += 1;
if (map[neigh] == 10) {
flashes_this_day += 1;
try flashes.append(neigh);
}
}
}
// Update condition counters
if (day < 100) {
part1 += flashes_this_day;
}
if (all_flash_day == null and flashes_this_day == width * height) {
all_flash_day = day;
}
// Reset the border to avoid fake flashes from it
{
var y: usize = 0;
while (y < height) : (y += 1) {
var x: usize = 0;
while (x < width) : (x += 1) {
const idx = y * pitch + x + start;
if (map[idx] > 9) map[idx] = 0;
}
}
}
}
const part2 = all_flash_day.? + 1;
print("part1={}, part2={}\n", .{part1, part2});
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const eql = std.mem.eql;
const parseEnum = std.meta.stringToEnum;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
|
src/day11.zig
|
const std = @import("std");
const fs = std.fs;
const Allocator = std.mem.Allocator;
const PATH = "src";
const LINE_LENGTH = 100;
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const format = try checkFormat(PATH, allocator);
const lint = try lintDir(PATH, fs.cwd(), PATH, allocator);
std.process.exit(@boolToInt(format or lint));
}
fn checkFormat(file_path: []const u8, allocator: Allocator) !bool {
const argv = &.{ "zig", "fmt", "--check", file_path };
// TODO: ziglang/zig@a0a2ce92 changed ChildProcess initialization
const allocates = @hasDecl(std.ChildProcess, "deinit");
var child: *std.ChildProcess = undefined;
if (allocates) {
child = try std.ChildProcess.init(argv, allocator);
} else {
child = &std.ChildProcess.init(argv, allocator);
}
defer if (allocates) child.deinit();
const term = child.spawnAndWait() catch |err| {
const stderr = std.io.getStdErr().writer();
try stderr.print("Unable to spawn 'zig fmt': {s}\n", .{@errorName(err)});
return true;
};
switch (term) {
.Exited => |code| {
if (code != 0) {
const stderr = std.io.getStdErr().writer();
try stderr.print("'zig fmt' exited with error code {}:\n", .{code});
return true;
}
},
else => {
const stderr = std.io.getStdErr().writer();
try stderr.print("'zig fmt' exited unexpectedly\n", .{});
return true;
},
}
return false;
}
// Line length linting logic forked from coilhq/tigerbeetle's Apache-2 licensed scripts/lint.zig.
// The code has been modified specifically for the structure of this pkmn engine project with a
// hardcoded symlink skip, though also includes support for Windows paths and skipping entire files.
// The full license can be found at https://github.com/coilhq/tigerbeetle/blob/main/LICENSE
const Ignored = union(enum) { lines: []const u32, all };
const ignore = std.ComptimeStringMap(Ignored, .{
.{ "src/examples/zig/example.zig", .all },
.{ "src/lib/gen2/test.zig", .all },
});
// Windows has trouble with the symlink so we need to hardcode the logic to skip it
const LIBS = "src\\examples\\zig\\libs";
fn ignored(raw_path: []const u8, line: u32, allocator: Allocator) !bool {
var path = try allocator.dupe(u8, raw_path);
std.mem.replaceScalar(u8, path, fs.path.sep_windows, fs.path.sep_posix);
defer allocator.free(path);
const value = ignore.get(path) orelse return false;
switch (value) {
.lines => |lines| return std.mem.indexOfScalar(u32, lines, line) != null,
.all => return true,
}
}
var seen = std.AutoArrayHashMapUnmanaged(fs.File.INode, void){};
const LintError =
error{ OutOfMemory, NotUtf8 } || fs.File.OpenError || fs.File.ReadError || fs.File.WriteError;
fn lintDir(
file_path: []const u8,
parent_dir: fs.Dir,
parent_sub_path: []const u8,
allocator: Allocator,
) LintError!bool {
var err = false;
var dir = try parent_dir.openDir(parent_sub_path, .{ .iterate = true });
defer dir.close();
const stat = try dir.stat();
if (try seen.fetchPut(allocator, stat.inode, {})) |_| return err;
var dir_it = dir.iterate();
while (try dir_it.next()) |entry| {
if (entry.kind == .SymLink) continue;
const is_dir = entry.kind == .Directory;
if (is_dir and std.mem.eql(u8, entry.name, "zig-cache")) continue;
if (is_dir or std.mem.endsWith(u8, entry.name, ".zig")) {
const full_path = try fs.path.join(allocator, &[_][]const u8{ file_path, entry.name });
defer allocator.free(full_path);
if (std.mem.eql(u8, full_path, LIBS)) continue;
var e = false;
if (is_dir) {
e = try lintDir(full_path, dir, entry.name, allocator);
} else {
e = try lintFile(full_path, dir, entry.name, allocator);
}
err = err or e;
}
}
return err;
}
fn lintFile(file_path: []const u8, dir: fs.Dir, sub_path: []const u8, allocator: Allocator) !bool {
const source_file = try dir.openFile(sub_path, .{});
defer source_file.close();
const source = try source_file.readToEndAllocOptions(
allocator,
std.math.maxInt(usize),
null,
@alignOf(u8),
0,
);
return lintLineLength(source, file_path, allocator);
}
fn lintLineLength(source: []const u8, path: []const u8, allocator: Allocator) !bool {
var err = false;
var i: usize = 0;
var line: u32 = 1;
while (std.mem.indexOfScalar(u8, source[i..], '\n')) |newline| : (line += 1) {
const line_length =
std.unicode.utf8CountCodepoints(source[i..][0..newline]) catch return error.NotUtf8;
if (line_length > LINE_LENGTH and !try ignored(path, line, allocator)) {
const stderr = std.io.getStdErr().writer();
try stderr.print(
"{s}:{d} has a length of {d}. Maximum allowed is 100\n",
.{ path, line, line_length },
);
err = true;
}
i += newline + 1;
}
return err;
}
|
src/tools/lint.zig
|
const std = @import("std");
const print = std.debug.print;
const data = @embedFile("../data/day03.txt");
fn day01() !usize {
var iterator = std.mem.tokenize(data, "\r\n");
var accumulation = [12]i16{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
var token_size : ?usize = null;
while (iterator.next()) |token| {
if (token_size == null) {
token_size = token.len;
} else {
std.debug.assert(token_size.? == token.len);
}
for (token) |t, i| {
if (t == '1')
{
accumulation[i] += 1;
}
else
{
accumulation[i] -= 1;
}
}
}
var gamma_rate : u32 = 0;
var epsilon_rate : u32 = 0;
for (accumulation) |a, i| {
if (a > 0) {
gamma_rate |= 1;
} else {
epsilon_rate |= 1;
}
if ((i + 1) >= token_size.?) {
break;
}
gamma_rate <<= 1;
epsilon_rate <<= 1;
}
print("🎁 Power Consumption: {}\n", .{gamma_rate * epsilon_rate});
return token_size.?;
}
fn day02(token_size : usize) !void {
var oxygen_generator_rating = [12]u8{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
var co2_generator_rating = [12]u8{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
var bit : usize = 0;
while (bit < token_size) : (bit += 1) {
var iterator = std.mem.tokenize(data, "\r\n");
var num_oxygens_alive : u32 = 0;
var oxygen_accumulation : i16 = 0;
var num_co2s_alive : u32 = 0;
var co2_accumulation : i16 = 0;
while (iterator.next()) |token| {
if (std.mem.startsWith(u8, token, oxygen_generator_rating[0..bit])) {
num_oxygens_alive += 1;
if (token[bit] == '1') {
oxygen_accumulation += 1;
} else {
oxygen_accumulation -= 1;
}
}
if (std.mem.startsWith(u8, token, co2_generator_rating[0..bit])) {
num_co2s_alive += 1;
if (token[bit] == '1') {
co2_accumulation += 1;
} else {
co2_accumulation -= 1;
}
}
}
if (num_oxygens_alive == 1) {
std.debug.assert(oxygen_accumulation != 0);
if (oxygen_accumulation == 1) {
oxygen_generator_rating[bit] = '1';
} else {
oxygen_generator_rating[bit] = '0';
}
} else if (oxygen_accumulation >= 0) {
oxygen_generator_rating[bit] = '1';
} else {
oxygen_generator_rating[bit] = '0';
}
if (num_co2s_alive == 1) {
std.debug.assert(co2_accumulation != 0);
if (co2_accumulation == 1) {
co2_generator_rating[bit] = '1';
} else {
co2_generator_rating[bit] = '0';
}
} else {
if (co2_accumulation >= 0) {
co2_generator_rating[bit] = '0';
} else {
co2_generator_rating[bit] = '1';
}
}
}
// Note: This really confused me! The `parseInt` function won't stop at a null
// terminating byte, so you need to manually slice it down to only the valid
// characters!
var oxygen_generator_rating_result = try std.fmt.parseInt(
u32, oxygen_generator_rating[0..token_size], 2);
var co2_generator_rating_result = try std.fmt.parseInt(
u32, co2_generator_rating[0..token_size], 2);
print("🎁 Life support rating: {}\n",
.{oxygen_generator_rating_result * co2_generator_rating_result});
}
pub fn main() !void {
var timer = try std.time.Timer.start();
var token_size = try day01();
var part01 = timer.lap();
print("Day 03 - part 01 took {:15}ns\n", .{part01});
timer.reset();
try day02(token_size);
var part02 = timer.lap();
print("Day 03 - part 02 took {:15}ns\n", .{part02});
print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{});
}
|
src/day03.zig
|
const std = @import("std");
const print = std.debug.print;
const data = @embedFile("../data/day11.txt");
fn dump(grid : [100]u8) void {
for (grid) |g, i| {
if (g > 9) {
print(" ", .{});
} else {
print("{}", .{g});
}
if ((i % 10) == 9) {
print("\n", .{});
}
}
print("\n", .{});
}
pub fn main() !void {
var timer = try std.time.Timer.start();
var lines = std.mem.tokenize(data, "\r\n");
const width : u32 = 10;
var grid = [_]u8{0} ** 100;
{
var index : u32 = 0;
while (lines.next()) |line| {
for (line) |c| {
grid[index] = c - '0';
index += 1;
}
}
}
var total_flashes : u32 = 0;
{
const steps : u32 = 1000;
var step : u32 = 0;
while (step < steps) : (step += 1) {
// First, the energy level of each octopus increases by 1.
for (grid) |*g| {
g.* += 1;
}
var flashed = std.StaticBitSet(100).initEmpty();
// Now we flash our octopuses until there are no more to flash.
while (true) {
const lastFlashedCount = flashed.count();
for (grid) |g, i| {
// Skip any octopus that isn't flashing.
if (g <= 9) {
continue;
}
// Skip any octopus we've already flashed.
if (flashed.isSet(i)) {
continue;
}
// Remember that we've already flashed this octopus.
flashed.set(i);
// Increase the energy level of all adjacent octopuses by 1.
const x = i % width;
const y = i / width;
// (x - 1, y - 1)
if ((x > 0) and (y > 0)) {
grid[(y - 1) * width + (x - 1)] += 1;
}
// (x, y - 1)
if (y > 0) {
grid[(y - 1) * width + x] += 1;
}
// (x + 1, y - 1)
if (((x + 1) < width) and (y > 0)) {
grid[(y - 1) * width + (x + 1)] += 1;
}
// (x - 1, y)
if (x > 0) {
grid[y * width + (x - 1)] += 1;
}
// (x + 1, y)
if ((x + 1) < width) {
grid[y * width + (x + 1)] += 1;
}
// (x - 1, y + 1)
if ((x > 0) and ((y + 1) < width)) {
grid[(y + 1) * width + (x - 1)] += 1;
}
// (x, y + 1)
if ((y + 1) < width) {
grid[(y + 1) * width + x] += 1;
}
// (x + 1, y + 1)
if (((x + 1) < width) and ((y + 1) < width)) {
grid[(y + 1) * width + (x + 1)] += 1;
}
}
if (lastFlashedCount == flashed.count()) {
break;
}
}
if (flashed.count() == 100) {
print("🎁 First synchronized flash: {}\n", .{step + 1});
print("Day 11 - part 02 took {:15}ns\n", .{timer.lap()});
print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{});
break;
}
// Lastly do the actual flashes.
for (grid) |*g| {
// Skip any octopus that doesn't flash.
if (g.* <= 9) {
continue;
}
g.* = 0;
total_flashes += 1;
}
if (step == 100) {
print("🎁 Total flashes: {}\n", .{total_flashes});
print("Day 11 - part 01 took {:15}ns\n", .{timer.lap()});
timer.reset();
}
}
}
}
|
src/day11.zig
|
usingnamespace @import("root").preamble;
/// Represents the physical location of a key on the keyboard, not affected by keyboard layouts
pub const Location = enum {
escape,
f1,
f2,
f3,
f4,
f5,
f6,
f7,
f8,
f9,
f10,
f11,
f12,
f13,
f14,
f15,
f16,
f17,
f18,
f19,
f20,
f21,
f22,
f23,
f24,
left_of1,
// Number key row, 123...0
number_key1,
number_key2,
number_key3,
number_key4,
number_key5,
number_key6,
number_key7,
number_key8,
number_key9,
number_key0,
right_of0,
left_of_backspace,
backspace,
// Top line, QWERTY: QWERTY...
tab,
line1_1,
line1_2,
line1_3,
line1_4,
line1_5,
line1_6,
line1_7,
line1_8,
line1_9,
line1_10,
line1_11,
line1_12,
line1_13,
// Middle line, QWERTY: ASDFGH...
capslock,
line2_1,
line2_2,
line2_3,
line2_4,
line2_5,
line2_6,
line2_7,
line2_8,
line2_9,
line2_10,
line2_11,
line2_12,
enter,
// Bottom line, QWERTY: ZXCVBN...
left_shift,
right_of_left_shift,
line3_1,
line3_2,
line3_3,
line3_4,
line3_5,
line3_6,
line3_7,
line3_8,
line3_9,
line3_10,
right_shift,
// Control keys along the bottom
left_ctrl,
right_ctrl,
left_super,
right_super,
left_alt,
right_alt,
spacebar,
option_key, // Between right super and right control
// Directional keys
arrow_up,
arrow_left,
arrow_down,
arrow_right,
// Group above directional keys
print_screen,
pause_break,
scroll_lock,
insert,
home,
page_up,
delete,
end,
page_down,
// numpad
numlock,
numpad_div,
numpad_mul,
numpad7,
numpad8,
numpad9,
numpad_sub,
numpad4,
numpad5,
numpad6,
numpad_add,
numpad1,
numpad2,
numpad3,
numpad0,
numpad_point,
numpad_enter,
// Multimedia keys
media_stop,
media_rewind,
media_pause_play,
media_forward,
media_mute,
media_volume_up,
media_volume_down,
};
/// Represent the intent of pressing the key, affected by keyboard layout
pub const Input = enum {
// Traditional numbers
@"1",
@"2",
@"3",
@"4",
@"5",
@"6",
@"7",
@"8",
@"9",
@"0",
// Traditional letters
q,
w,
e,
r,
t,
y,
u,
i,
o,
p,
a,
s,
d,
f,
g,
h,
j,
k,
l,
z,
x,
c,
v,
b,
n,
m,
// Control keys
spacebar,
option_key,
backspace,
tab,
escape,
capslock,
enter,
f1,
f2,
f3,
f4,
f5,
f6,
f7,
f8,
f9,
f10,
f11,
f12,
f13,
f14,
f15,
f16,
f17,
f18,
f19,
f20,
f21,
f22,
f23,
f24,
// Modifier keys
left_shift,
right_shift,
left_ctrl,
right_ctrl,
left_super,
right_super,
left_alt,
right_alt,
// The buttons traditionally above the arrow keys
print_screen,
pause_break,
scroll_lock,
insert,
home,
page_up,
delete,
end,
page_down,
// arrow keys
arrow_up,
arrow_left,
arrow_down,
arrow_right,
// Punctuation
exclamation_mark,
quotation_mark,
hash,
currency_sign,
percent,
ampersand,
forward_slash,
back_slash,
question_mark,
at,
dollar_sign,
caret,
asterisk,
period,
comma,
colon,
semicolon,
plus,
minus,
underscore,
equals,
vertical_bar,
tilde,
back_tick,
apostrophe,
pound_sign,
plusminus,
acute,
umlaut,
euro_sign,
yen_sign,
paragraph_sign,
section_sign,
open_sq_bracket,
close_sq_bracket,
open_curly_brace,
close_curly_brace,
open_paren,
close_paren,
less_than,
greater_than,
// numpad
numlock,
numpad_div,
numpad_mul,
numpad7,
numpad8,
numpad9,
numpad_sub,
numpad4,
numpad5,
numpad6,
numpad_add,
numpad1,
numpad2,
numpad3,
numpad0,
numpad_point,
numpad_enter,
// Multimedia keys
media_stop,
media_rewind,
media_pause_play,
media_forward,
media_mute,
media_volume_up,
media_volume_down,
// International letters
a_with_umlaut,
o_with_umlaut,
a_with_ring,
slashedO,
ash,
};
pub const wasd_directional = .{
.up = KeyLocation.line1_2,
.left = KeyLocation.line2_1,
.down = KeyLocation.line2_2,
.right = KeyLocation.line2_3,
};
pub const arrow_directional = .{
.up = KeyLocation.arrow_up,
.left = KeyLocation.arrow_left,
.down = KeyLocation.arrow_down,
.right = KeyLocation.arrow_right,
};
pub const numpad_directional = .{
.up = KeyLocation.numpad8,
.left = KeyLocation.numpad4,
.down = KeyLocation.numpad2,
.right = KeyLocation.numpad6,
};
|
lib/input/keyboard/keys.zig
|
const cfg = @import("cfg.zig");
const std = @import("std");
/// minifier that removes whitespace and replaces any words starting with _
/// with smaller allocated identifiers
const Minify = struct {
const Language = enum {
js,
wgsl,
};
const CharType = enum {
whitespace, // any whitespace character
symbol, // any character in the symbols string, see below
ident, // any non-whitespace, non-symbol character
};
const symbols = "{}()[]=<>;:.,|/-+*!&?";
const str_symbols = "\"'`";
const max_ident_size = 2;
const next_ident_symbols = "abcdfghjklmnpqrstvwxzABCDEFGHIJKLMNOPQRSTUVWXYZ";
allocator: std.mem.Allocator,
src: []const u8,
out: std.ArrayList(u8),
start_index: usize,
end_index: usize,
prev_char_type: CharType,
prev_char_type_write: CharType,
ident_map: std.StringHashMap([]const u8),
next_ident: [max_ident_size]u8,
next_ident_index: [max_ident_size]usize,
next_ident_size: usize,
language: Language,
opt_level: cfg.OptLevel,
fn init(
src: []const u8,
allocator: std.mem.Allocator,
language: Language,
opt_level: cfg.OptLevel,
) Minify {
var ctx = Minify{
.allocator = allocator,
.src = src,
.out = std.ArrayList(u8).init(allocator),
.start_index = 0,
.end_index = 0,
.prev_char_type = .whitespace,
.prev_char_type_write = .whitespace,
.ident_map = std.StringHashMap([]const u8).init(allocator),
.next_ident = [_]u8{next_ident_symbols[0]} ** max_ident_size,
.next_ident_index = [_]usize{0} ** max_ident_size,
.next_ident_size = 1,
.language = language,
.opt_level = opt_level,
};
return ctx;
}
fn deinit(ctx: *Minify) void {
var it = ctx.ident_map.iterator();
while (it.next()) |kv| {
ctx.allocator.free(kv.value_ptr.*);
}
ctx.ident_map.deinit();
}
fn minify(ctx: *Minify) ![]const u8 {
while (ctx.end_index < ctx.src.len) {
const char = ctx.src[ctx.end_index];
if (ctx.end_index < ctx.src.len - 1 and
char == '/' and
(ctx.src[ctx.end_index + 1] == '/' or ctx.src[ctx.end_index + 1] == '*'))
{
try ctx.handleComment();
} else if (std.mem.indexOfScalar(u8, symbols, char) != null) {
try ctx.handleCharType(.symbol);
} else if (std.mem.indexOfScalar(u8, str_symbols, char) != null) {
try ctx.handleString();
} else if (std.mem.indexOfScalar(u8, &std.ascii.spaces, char) != null) {
try ctx.handleCharType(.whitespace);
} else {
try ctx.handleCharType(.ident);
}
}
try ctx.flush();
return ctx.out.toOwnedSlice();
}
fn flush(ctx: *Minify) !void {
try ctx.handleCharType(.whitespace);
}
fn handleCharType(ctx: *Minify, char_type: CharType) !void {
// check for the end of a char type run
if (char_type != ctx.prev_char_type) {
if (ctx.prev_char_type == .symbol) {
try ctx.appendSymbol();
} else if (ctx.prev_char_type == .ident) {
try ctx.appendIdent();
}
if (char_type != .whitespace) {
// append a space between two different identifiers
if (ctx.prev_char_type_write == .ident and char_type == .ident) {
try ctx.out.append(' ');
}
// chrome wgsl parser is broken, this works around the issue...
if (ctx.language == .wgsl and
ctx.prev_char_type_write == .symbol and
char_type == .ident)
{
const wgsl_skip = "{([]<>=:;,.";
const last_write_char = ctx.out.items[ctx.out.items.len - 1];
if (std.mem.indexOfScalar(u8, wgsl_skip, last_write_char) == null) {
try ctx.out.append(' ');
}
}
// keep track of the last char type written
ctx.prev_char_type_write = char_type;
}
ctx.prev_char_type = char_type;
ctx.start_index = ctx.end_index;
}
ctx.end_index += 1;
}
fn handleString(ctx: *Minify) !void {
try ctx.flush();
const str_marker = ctx.src[ctx.end_index - 1];
ctx.start_index = ctx.end_index - 1;
while (ctx.end_index < ctx.src.len and
(ctx.src[ctx.end_index] != str_marker or ctx.src[ctx.end_index - 1] == '\\'))
{
ctx.end_index += 1;
}
ctx.end_index += 1;
try ctx.out.appendSlice(ctx.src[ctx.start_index..ctx.end_index]);
}
fn handleComment(ctx: *Minify) !void {
try ctx.flush();
const char = ctx.src[ctx.end_index];
if (char == '/') {
// line comment
while (ctx.src[ctx.end_index] != '\n') {
ctx.end_index += 1;
}
} else {
// block comment
while (ctx.end_index < ctx.src.len - 1 and
ctx.src[ctx.end_index] != '*' and
ctx.src[ctx.end_index + 1] != '/')
{
ctx.end_index += 1;
}
}
}
fn appendSymbol(ctx: *Minify) !void {
try ctx.out.appendSlice(ctx.src[ctx.start_index..ctx.end_index]);
}
fn appendIdent(ctx: *Minify) !void {
const ident = ctx.src[ctx.start_index..ctx.end_index];
// append the identifier as-is if in debug mode or if the identifier starts with _
// digits also cannot be converted into a different identifier
if (ctx.opt_level == .dbg or
ctx.src[ctx.start_index] != '_' or
std.ascii.isDigit(ident[0]))
{
try ctx.out.appendSlice(ident);
} else if (ctx.ident_map.getEntry(ident)) |entry| {
// check if the identifier has already been parsed.
// reuse the replacement identifier in that case
try ctx.out.appendSlice(entry.value_ptr.*);
} else {
// otherwise, get a new replacement identifier
const next_ident = try ctx.nextIdent();
try ctx.ident_map.put(ident, next_ident);
try ctx.out.appendSlice(next_ident);
}
}
fn nextIdent(ctx: *Minify) ![]const u8 {
// identifiers are allocated from a string of characters.
// they start off as single character identifiers
const next = ctx.allocator.dupe(u8, ctx.next_ident[0..ctx.next_ident_size]);
var cur_index = ctx.next_ident_size - 1;
if (ctx.next_ident_index[cur_index] != next_ident_symbols.len - 1) {
// each time an identifier is allocated, the character in the string is set to
// the next one in next_ident_symbols...
ctx.setNextIdent(cur_index, ctx.next_ident_index[cur_index] + 1);
} else {
// if the size is greater than 1, try to increment
// the identifier in a previous string index
ctx.setNextIdent(cur_index, 0);
var out_of_idents = true;
while (cur_index != 0) {
cur_index -= 1;
if (ctx.next_ident_index[cur_index] == next_ident_symbols.len - 1) {
ctx.setNextIdent(cur_index, 0);
} else {
ctx.setNextIdent(cur_index, ctx.next_ident_index[cur_index] + 1);
out_of_idents = false;
break;
}
}
// if that didn't work, we need to increase the size of the string
if (out_of_idents) {
ctx.next_ident_size += 1;
if (ctx.next_ident_size > max_ident_size) {
return error.MaxIdentsExceeded;
}
}
}
return next;
}
fn setNextIdent(ctx: *Minify, ident_index: usize, symbol_index: usize) void {
ctx.next_ident_index[ident_index] = symbol_index;
ctx.next_ident[ident_index] = next_ident_symbols[symbol_index];
}
};
pub fn js(
src: []const u8,
allocator: std.mem.Allocator,
opt_level: cfg.OptLevel,
) ![]const u8 {
var ctx = Minify.init(src, allocator, .js, opt_level);
defer ctx.deinit();
return try ctx.minify();
}
pub fn shader(
src: []const u8,
allocator: std.mem.Allocator,
platform: cfg.Platform,
opt_level: cfg.OptLevel,
) ![]const u8 {
const lang: Minify.Language = switch (platform) {
.web => .wgsl,
else => return error.InvalidPlatform,
};
var ctx = Minify.init(src, allocator, lang, opt_level);
defer ctx.deinit();
return try ctx.minify();
}
|
src/minify.zig
|
const assert = @import("../debug.zig").assert;
const builtin = @import("builtin");
const arch = switch (builtin.arch) {
builtin.Arch.x86_64 => @import("x86_64.zig"),
else => @compileError("unsupported arch"),
};
pub use @import("syscall.zig");
pub use @import("errno.zig");
const std = @import("../../index.zig");
const c = std.c;
const maxInt = std.math.maxInt;
pub const Kevent = c.Kevent;
pub const PATH_MAX = 1024;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT_NONE = 0;
pub const PROT_READ = 1;
pub const PROT_WRITE = 2;
pub const PROT_EXEC = 4;
pub const MAP_FAILED = maxInt(usize);
pub const MAP_SHARED = 0x0001;
pub const MAP_PRIVATE = 0x0002;
pub const MAP_FIXED = 0x0010;
pub const MAP_STACK = 0x0400;
pub const MAP_NOSYNC = 0x0800;
pub const MAP_ANON = 0x1000;
pub const MAP_ANONYMOUS = MAP_ANON;
pub const MAP_FILE = 0;
pub const MAP_NORESERVE = 0;
pub const MAP_GUARD = 0x00002000;
pub const MAP_EXCL = 0x00004000;
pub const MAP_NOCORE = 0x00020000;
pub const MAP_PREFAULT_READ = 0x00040000;
pub const MAP_32BIT = 0x00080000;
pub const WNOHANG = 1;
pub const WUNTRACED = 2;
pub const WSTOPPED = WUNTRACED;
pub const WCONTINUED = 4;
pub const WNOWAIT = 8;
pub const WEXITED = 16;
pub const WTRAPPED = 32;
pub const SA_ONSTACK = 0x0001;
pub const SA_RESTART = 0x0002;
pub const SA_RESETHAND = 0x0004;
pub const SA_NOCLDSTOP = 0x0008;
pub const SA_NODEFER = 0x0010;
pub const SA_NOCLDWAIT = 0x0020;
pub const SA_SIGINFO = 0x0040;
pub const SIGHUP = 1;
pub const SIGINT = 2;
pub const SIGQUIT = 3;
pub const SIGILL = 4;
pub const SIGTRAP = 5;
pub const SIGABRT = 6;
pub const SIGIOT = SIGABRT;
pub const SIGEMT = 7;
pub const SIGFPE = 8;
pub const SIGKILL = 9;
pub const SIGBUS = 10;
pub const SIGSEGV = 11;
pub const SIGSYS = 12;
pub const SIGPIPE = 13;
pub const SIGALRM = 14;
pub const SIGTERM = 15;
pub const SIGURG = 16;
pub const SIGSTOP = 17;
pub const SIGTSTP = 18;
pub const SIGCONT = 19;
pub const SIGCHLD = 20;
pub const SIGTTIN = 21;
pub const SIGTTOU = 22;
pub const SIGIO = 23;
pub const SIGXCPU = 24;
pub const SIGXFSZ = 25;
pub const SIGVTALRM = 26;
pub const SIGPROF = 27;
pub const SIGWINCH = 28;
pub const SIGINFO = 29;
pub const SIGUSR1 = 30;
pub const SIGUSR2 = 31;
pub const SIGTHR = 32;
pub const SIGLWP = SIGTHR;
pub const SIGLIBRT = 33;
pub const SIGRTMIN = 65;
pub const SIGRTMAX = 126;
pub const O_RDONLY = 0o0;
pub const O_WRONLY = 0o1;
pub const O_RDWR = 0o2;
pub const O_ACCMODE = 0o3;
pub const O_CREAT = 0o100;
pub const O_EXCL = 0o200;
pub const O_NOCTTY = 0o400;
pub const O_TRUNC = 0o1000;
pub const O_APPEND = 0o2000;
pub const O_NONBLOCK = 0o4000;
pub const O_DSYNC = 0o10000;
pub const O_SYNC = 0o4010000;
pub const O_RSYNC = 0o4010000;
pub const O_DIRECTORY = 0o200000;
pub const O_NOFOLLOW = 0o400000;
pub const O_CLOEXEC = 0o2000000;
pub const O_ASYNC = 0o20000;
pub const O_DIRECT = 0o40000;
pub const O_LARGEFILE = 0;
pub const O_NOATIME = 0o1000000;
pub const O_PATH = 0o10000000;
pub const O_TMPFILE = 0o20200000;
pub const O_NDELAY = O_NONBLOCK;
pub const F_DUPFD = 0;
pub const F_GETFD = 1;
pub const F_SETFD = 2;
pub const F_GETFL = 3;
pub const F_SETFL = 4;
pub const F_SETOWN = 8;
pub const F_GETOWN = 9;
pub const F_SETSIG = 10;
pub const F_GETSIG = 11;
pub const F_GETLK = 5;
pub const F_SETLK = 6;
pub const F_SETLKW = 7;
pub const F_SETOWN_EX = 15;
pub const F_GETOWN_EX = 16;
pub const F_GETOWNER_UIDS = 17;
pub const SEEK_SET = 0;
pub const SEEK_CUR = 1;
pub const SEEK_END = 2;
pub const SIG_BLOCK = 1;
pub const SIG_UNBLOCK = 2;
pub const SIG_SETMASK = 3;
pub const SOCK_STREAM = 1;
pub const SOCK_DGRAM = 2;
pub const SOCK_RAW = 3;
pub const SOCK_RDM = 4;
pub const SOCK_SEQPACKET = 5;
pub const SOCK_CLOEXEC = 0x10000000;
pub const SOCK_NONBLOCK = 0x20000000;
pub const PROTO_ip = 0o000;
pub const PROTO_icmp = 0o001;
pub const PROTO_igmp = 0o002;
pub const PROTO_ggp = 0o003;
pub const PROTO_ipencap = 0o004;
pub const PROTO_st = 0o005;
pub const PROTO_tcp = 0o006;
pub const PROTO_egp = 0o010;
pub const PROTO_pup = 0o014;
pub const PROTO_udp = 0o021;
pub const PROTO_hmp = 0o024;
pub const PROTO_xns_idp = 0o026;
pub const PROTO_rdp = 0o033;
pub const PROTO_iso_tp4 = 0o035;
pub const PROTO_xtp = 0o044;
pub const PROTO_ddp = 0o045;
pub const PROTO_idpr_cmtp = 0o046;
pub const PROTO_ipv6 = 0o051;
pub const PROTO_ipv6_route = 0o053;
pub const PROTO_ipv6_frag = 0o054;
pub const PROTO_idrp = 0o055;
pub const PROTO_rsvp = 0o056;
pub const PROTO_gre = 0o057;
pub const PROTO_esp = 0o062;
pub const PROTO_ah = 0o063;
pub const PROTO_skip = 0o071;
pub const PROTO_ipv6_icmp = 0o072;
pub const PROTO_ipv6_nonxt = 0o073;
pub const PROTO_ipv6_opts = 0o074;
pub const PROTO_rspf = 0o111;
pub const PROTO_vmtp = 0o121;
pub const PROTO_ospf = 0o131;
pub const PROTO_ipip = 0o136;
pub const PROTO_encap = 0o142;
pub const PROTO_pim = 0o147;
pub const PROTO_raw = 0o377;
pub const PF_UNSPEC = 0;
pub const PF_LOCAL = 1;
pub const PF_UNIX = PF_LOCAL;
pub const PF_FILE = PF_LOCAL;
pub const PF_INET = 2;
pub const PF_AX25 = 3;
pub const PF_IPX = 4;
pub const PF_APPLETALK = 5;
pub const PF_NETROM = 6;
pub const PF_BRIDGE = 7;
pub const PF_ATMPVC = 8;
pub const PF_X25 = 9;
pub const PF_INET6 = 10;
pub const PF_ROSE = 11;
pub const PF_DECnet = 12;
pub const PF_NETBEUI = 13;
pub const PF_SECURITY = 14;
pub const PF_KEY = 15;
pub const PF_NETLINK = 16;
pub const PF_ROUTE = PF_NETLINK;
pub const PF_PACKET = 17;
pub const PF_ASH = 18;
pub const PF_ECONET = 19;
pub const PF_ATMSVC = 20;
pub const PF_RDS = 21;
pub const PF_SNA = 22;
pub const PF_IRDA = 23;
pub const PF_PPPOX = 24;
pub const PF_WANPIPE = 25;
pub const PF_LLC = 26;
pub const PF_IB = 27;
pub const PF_MPLS = 28;
pub const PF_CAN = 29;
pub const PF_TIPC = 30;
pub const PF_BLUETOOTH = 31;
pub const PF_IUCV = 32;
pub const PF_RXRPC = 33;
pub const PF_ISDN = 34;
pub const PF_PHONET = 35;
pub const PF_IEEE802154 = 36;
pub const PF_CAIF = 37;
pub const PF_ALG = 38;
pub const PF_NFC = 39;
pub const PF_VSOCK = 40;
pub const PF_MAX = 41;
pub const AF_UNSPEC = PF_UNSPEC;
pub const AF_LOCAL = PF_LOCAL;
pub const AF_UNIX = AF_LOCAL;
pub const AF_FILE = AF_LOCAL;
pub const AF_INET = PF_INET;
pub const AF_AX25 = PF_AX25;
pub const AF_IPX = PF_IPX;
pub const AF_APPLETALK = PF_APPLETALK;
pub const AF_NETROM = PF_NETROM;
pub const AF_BRIDGE = PF_BRIDGE;
pub const AF_ATMPVC = PF_ATMPVC;
pub const AF_X25 = PF_X25;
pub const AF_INET6 = PF_INET6;
pub const AF_ROSE = PF_ROSE;
pub const AF_DECnet = PF_DECnet;
pub const AF_NETBEUI = PF_NETBEUI;
pub const AF_SECURITY = PF_SECURITY;
pub const AF_KEY = PF_KEY;
pub const AF_NETLINK = PF_NETLINK;
pub const AF_ROUTE = PF_ROUTE;
pub const AF_PACKET = PF_PACKET;
pub const AF_ASH = PF_ASH;
pub const AF_ECONET = PF_ECONET;
pub const AF_ATMSVC = PF_ATMSVC;
pub const AF_RDS = PF_RDS;
pub const AF_SNA = PF_SNA;
pub const AF_IRDA = PF_IRDA;
pub const AF_PPPOX = PF_PPPOX;
pub const AF_WANPIPE = PF_WANPIPE;
pub const AF_LLC = PF_LLC;
pub const AF_IB = PF_IB;
pub const AF_MPLS = PF_MPLS;
pub const AF_CAN = PF_CAN;
pub const AF_TIPC = PF_TIPC;
pub const AF_BLUETOOTH = PF_BLUETOOTH;
pub const AF_IUCV = PF_IUCV;
pub const AF_RXRPC = PF_RXRPC;
pub const AF_ISDN = PF_ISDN;
pub const AF_PHONET = PF_PHONET;
pub const AF_IEEE802154 = PF_IEEE802154;
pub const AF_CAIF = PF_CAIF;
pub const AF_ALG = PF_ALG;
pub const AF_NFC = PF_NFC;
pub const AF_VSOCK = PF_VSOCK;
pub const AF_MAX = PF_MAX;
pub const DT_UNKNOWN = 0;
pub const DT_FIFO = 1;
pub const DT_CHR = 2;
pub const DT_DIR = 4;
pub const DT_BLK = 6;
pub const DT_REG = 8;
pub const DT_LNK = 10;
pub const DT_SOCK = 12;
pub const DT_WHT = 14;
/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;
/// delete event from kq
pub const EV_DELETE = 0x0002;
/// enable event
pub const EV_ENABLE = 0x0004;
/// disable event (not reported)
pub const EV_DISABLE = 0x0008;
/// only report one occurrence
pub const EV_ONESHOT = 0x0010;
/// clear event state after reporting
pub const EV_CLEAR = 0x0020;
/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
/// on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;
/// disable event after reporting
pub const EV_DISPATCH = 0x0080;
pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;
/// attached to aio requests
pub const EVFILT_AIO = -3;
/// attached to vnodes
pub const EVFILT_VNODE = -4;
/// attached to struct proc
pub const EVFILT_PROC = -5;
/// attached to struct proc
pub const EVFILT_SIGNAL = -6;
/// timers
pub const EVFILT_TIMER = -7;
/// Process descriptors
pub const EVFILT_PROCDESC = -8;
/// Filesystem events
pub const EVFILT_FS = -9;
pub const EVFILT_LIO = -10;
/// User events
pub const EVFILT_USER = -11;
/// Sendfile events
pub const EVFILT_SENDFILE = -12;
pub const EVFILT_EMPTY = -13;
/// On input, NOTE_TRIGGER causes the event to be triggered for output.
pub const NOTE_TRIGGER = 0x01000000;
/// ignore input fflags
pub const NOTE_FFNOP = 0x00000000;
/// and fflags
pub const NOTE_FFAND = 0x40000000;
/// or fflags
pub const NOTE_FFOR = 0x80000000;
/// copy fflags
pub const NOTE_FFCOPY = 0xc0000000;
/// mask for operations
pub const NOTE_FFCTRLMASK = 0xc0000000;
pub const NOTE_FFLAGSMASK = 0x00ffffff;
/// low water mark
pub const NOTE_LOWAT = 0x00000001;
/// behave like poll()
pub const NOTE_FILE_POLL = 0x00000002;
/// vnode was removed
pub const NOTE_DELETE = 0x00000001;
/// data contents changed
pub const NOTE_WRITE = 0x00000002;
/// size increased
pub const NOTE_EXTEND = 0x00000004;
/// attributes changed
pub const NOTE_ATTRIB = 0x00000008;
/// link count changed
pub const NOTE_LINK = 0x00000010;
/// vnode was renamed
pub const NOTE_RENAME = 0x00000020;
/// vnode access was revoked
pub const NOTE_REVOKE = 0x00000040;
/// vnode was opened
pub const NOTE_OPEN = 0x00000080;
/// file closed, fd did not allow write
pub const NOTE_CLOSE = 0x00000100;
/// file closed, fd did allow write
pub const NOTE_CLOSE_WRITE = 0x00000200;
/// file was read
pub const NOTE_READ = 0x00000400;
/// process exited
pub const NOTE_EXIT = 0x80000000;
/// process forked
pub const NOTE_FORK = 0x40000000;
/// process exec'd
pub const NOTE_EXEC = 0x20000000;
/// mask for signal & exit status
pub const NOTE_PDATAMASK = 0x000fffff;
pub const NOTE_PCTRLMASK = (~NOTE_PDATAMASK);
/// data is seconds
pub const NOTE_SECONDS = 0x00000001;
/// data is milliseconds
pub const NOTE_MSECONDS = 0x00000002;
/// data is microseconds
pub const NOTE_USECONDS = 0x00000004;
/// data is nanoseconds
pub const NOTE_NSECONDS = 0x00000008;
/// timeout is absolute
pub const NOTE_ABSTIME = 0x00000010;
pub const TCGETS = 0x5401;
pub const TCSETS = 0x5402;
pub const TCSETSW = 0x5403;
pub const TCSETSF = 0x5404;
pub const TCGETA = 0x5405;
pub const TCSETA = 0x5406;
pub const TCSETAW = 0x5407;
pub const TCSETAF = 0x5408;
pub const TCSBRK = 0x5409;
pub const TCXONC = 0x540A;
pub const TCFLSH = 0x540B;
pub const TIOCEXCL = 0x540C;
pub const TIOCNXCL = 0x540D;
pub const TIOCSCTTY = 0x540E;
pub const TIOCGPGRP = 0x540F;
pub const TIOCSPGRP = 0x5410;
pub const TIOCOUTQ = 0x5411;
pub const TIOCSTI = 0x5412;
pub const TIOCGWINSZ = 0x5413;
pub const TIOCSWINSZ = 0x5414;
pub const TIOCMGET = 0x5415;
pub const TIOCMBIS = 0x5416;
pub const TIOCMBIC = 0x5417;
pub const TIOCMSET = 0x5418;
pub const TIOCGSOFTCAR = 0x5419;
pub const TIOCSSOFTCAR = 0x541A;
pub const FIONREAD = 0x541B;
pub const TIOCINQ = FIONREAD;
pub const TIOCLINUX = 0x541C;
pub const TIOCCONS = 0x541D;
pub const TIOCGSERIAL = 0x541E;
pub const TIOCSSERIAL = 0x541F;
pub const TIOCPKT = 0x5420;
pub const FIONBIO = 0x5421;
pub const TIOCNOTTY = 0x5422;
pub const TIOCSETD = 0x5423;
pub const TIOCGETD = 0x5424;
pub const TCSBRKP = 0x5425;
pub const TIOCSBRK = 0x5427;
pub const TIOCCBRK = 0x5428;
pub const TIOCGSID = 0x5429;
pub const TIOCGRS485 = 0x542E;
pub const TIOCSRS485 = 0x542F;
pub const TIOCGPTN = 0x80045430;
pub const TIOCSPTLCK = 0x40045431;
pub const TIOCGDEV = 0x80045432;
pub const TCGETX = 0x5432;
pub const TCSETX = 0x5433;
pub const TCSETXF = 0x5434;
pub const TCSETXW = 0x5435;
pub const TIOCSIG = 0x40045436;
pub const TIOCVHANGUP = 0x5437;
pub const TIOCGPKT = 0x80045438;
pub const TIOCGPTLCK = 0x80045439;
pub const TIOCGEXCL = 0x80045440;
fn unsigned(s: i32) u32 {
return @bitCast(u32, s);
}
fn signed(s: u32) i32 {
return @bitCast(i32, s);
}
pub fn WEXITSTATUS(s: i32) i32 {
return signed((unsigned(s) & 0xff00) >> 8);
}
pub fn WTERMSIG(s: i32) i32 {
return signed(unsigned(s) & 0x7f);
}
pub fn WSTOPSIG(s: i32) i32 {
return WEXITSTATUS(s);
}
pub fn WIFEXITED(s: i32) bool {
return WTERMSIG(s) == 0;
}
pub fn WIFSTOPPED(s: i32) bool {
return @intCast(u16, (((unsigned(s) & 0xffff) *% 0x10001) >> 8)) > 0x7f00;
}
pub fn WIFSIGNALED(s: i32) bool {
return (unsigned(s) & 0xffff) -% 1 < 0xff;
}
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
/// Get the errno from a syscall return value, or 0 for no error.
pub fn getErrno(r: usize) usize {
const signed_r = @bitCast(isize, r);
return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0;
}
pub fn dup2(old: i32, new: i32) usize {
return arch.syscall2(SYS_dup2, @bitCast(usize, isize(old)), @bitCast(usize, isize(new)));
}
pub fn chdir(path: [*]const u8) usize {
return arch.syscall1(SYS_chdir, @ptrToInt(path));
}
pub fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) usize {
return arch.syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp));
}
pub fn fork() usize {
return arch.syscall0(SYS_fork);
}
pub fn getcwd(buf: [*]u8, size: usize) usize {
return arch.syscall2(SYS___getcwd, @ptrToInt(buf), size);
}
pub fn getdents(fd: i32, dirp: [*]u8, count: usize) usize {
return arch.syscall3(SYS_getdents, @bitCast(usize, isize(fd)), @ptrToInt(dirp), count);
}
pub fn isatty(fd: i32) bool {
var wsz: winsize = undefined;
return arch.syscall3(SYS_ioctl, @bitCast(usize, isize(fd)), TIOCGWINSZ, @ptrToInt(&wsz)) == 0;
}
pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
return arch.syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
}
pub fn mkdir(path: [*]const u8, mode: u32) usize {
return arch.syscall2(SYS_mkdir, @ptrToInt(path), mode);
}
pub fn mmap(address: ?*u8, length: usize, prot: usize, flags: usize, fd: i32, offset: isize) usize {
return arch.syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, @bitCast(usize, isize(fd)), @bitCast(usize, offset));
}
pub fn munmap(address: usize, length: usize) usize {
return arch.syscall2(SYS_munmap, address, length);
}
pub fn read(fd: i32, buf: [*]u8, count: usize) usize {
return arch.syscall3(SYS_read, @bitCast(usize, isize(fd)), @ptrToInt(buf), count);
}
pub fn rmdir(path: [*]const u8) usize {
return arch.syscall1(SYS_rmdir, @ptrToInt(path));
}
pub fn symlink(existing: [*]const u8, new: [*]const u8) usize {
return arch.syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new));
}
pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: usize) usize {
return arch.syscall4(SYS_pread, @bitCast(usize, isize(fd)), @ptrToInt(buf), count, offset);
}
pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: usize) usize {
return arch.syscall4(SYS_preadv, @bitCast(usize, isize(fd)), @ptrToInt(iov), count, offset);
}
pub fn pipe(fd: *[2]i32) usize {
return pipe2(fd, 0);
}
pub fn pipe2(fd: *[2]i32, flags: usize) usize {
return arch.syscall2(SYS_pipe2, @ptrToInt(fd), flags);
}
pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {
return arch.syscall3(SYS_write, @bitCast(usize, isize(fd)), @ptrToInt(buf), count);
}
pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {
return arch.syscall4(SYS_pwrite, @bitCast(usize, isize(fd)), @ptrToInt(buf), count, offset);
}
pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: usize) usize {
return arch.syscall4(SYS_pwritev, @bitCast(usize, isize(fd)), @ptrToInt(iov), count, offset);
}
pub fn rename(old: [*]const u8, new: [*]const u8) usize {
return arch.syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new));
}
pub fn open(path: [*]const u8, flags: u32, perm: usize) usize {
return arch.syscall3(SYS_open, @ptrToInt(path), flags, perm);
}
pub fn create(path: [*]const u8, perm: usize) usize {
return arch.syscall2(SYS_creat, @ptrToInt(path), perm);
}
pub fn openat(dirfd: i32, path: [*]const u8, flags: usize, mode: usize) usize {
return arch.syscall4(SYS_openat, @bitCast(usize, isize(dirfd)), @ptrToInt(path), flags, mode);
}
pub fn close(fd: i32) usize {
return arch.syscall1(SYS_close, @bitCast(usize, isize(fd)));
}
pub fn lseek(fd: i32, offset: isize, ref_pos: usize) usize {
return arch.syscall3(SYS_lseek, @bitCast(usize, isize(fd)), @bitCast(usize, offset), ref_pos);
}
pub fn exit(status: i32) noreturn {
_ = arch.syscall1(SYS_exit, @bitCast(usize, isize(status)));
unreachable;
}
pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize {
return arch.syscall3(SYS_getrandom, @ptrToInt(buf), count, usize(flags));
}
pub fn kill(pid: i32, sig: i32) usize {
return arch.syscall2(SYS_kill, @bitCast(usize, isize(pid)), @bitCast(usize, isize(sig)));
}
pub fn unlink(path: [*]const u8) usize {
return arch.syscall1(SYS_unlink, @ptrToInt(path));
}
pub fn waitpid(pid: i32, status: *i32, options: i32) usize {
return arch.syscall4(SYS_wait4, @bitCast(usize, isize(pid)), @ptrToInt(status), @bitCast(usize, isize(options)), 0);
}
pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize {
return arch.syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem));
}
pub fn setuid(uid: u32) usize {
return arch.syscall1(SYS_setuid, uid);
}
pub fn setgid(gid: u32) usize {
return arch.syscall1(SYS_setgid, gid);
}
pub fn setreuid(ruid: u32, euid: u32) usize {
return arch.syscall2(SYS_setreuid, ruid, euid);
}
pub fn setregid(rgid: u32, egid: u32) usize {
return arch.syscall2(SYS_setregid, rgid, egid);
}
const NSIG = 32;
pub const SIG_ERR = @intToPtr(extern fn (i32) void, maxInt(usize));
pub const SIG_DFL = @intToPtr(extern fn (i32) void, 0);
pub const SIG_IGN = @intToPtr(extern fn (i32) void, 1);
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
pub const Sigaction = extern struct {
/// signal handler
__sigaction_u: extern union {
__sa_handler: extern fn (i32) void,
__sa_sigaction: extern fn (i32, *__siginfo, usize) void,
},
/// see signal options
sa_flags: u32,
/// signal mask to apply
sa_mask: sigset_t,
};
pub const _SIG_WORDS = 4;
pub const _SIG_MAXSIG = 128;
pub inline fn _SIG_IDX(sig: usize) usize {
return sig - 1;
}
pub inline fn _SIG_WORD(sig: usize) usize {
return_SIG_IDX(sig) >> 5;
}
pub inline fn _SIG_BIT(sig: usize) usize {
return 1 << (_SIG_IDX(sig) & 31);
}
pub inline fn _SIG_VALID(sig: usize) usize {
return sig <= _SIG_MAXSIG and sig > 0;
}
pub const sigset_t = extern struct {
__bits: [_SIG_WORDS]u32,
};
pub fn raise(sig: i32) usize {
// TODO have a chat with the freebsd folks and make sure there's no bug in
// their libc. musl-libc blocks signals in between these calls because
// if a signal handler runs and forks between the gettid and sending the
// signal, the parent will get 2 signals, one from itself and one from the child
// if the protection does not belong here, then it belongs in abort(),
// like it does in freebsd's libc.
var id: usize = undefined;
const rc = arch.syscall1(SYS_thr_self, @ptrToInt(&id));
if (getErrno(rc) != 0) return rc;
return arch.syscall2(SYS_thr_kill, id, @bitCast(usize, isize(sig)));
}
pub const Stat = arch.Stat;
pub const timespec = arch.timespec;
pub fn fstat(fd: i32, stat_buf: *Stat) usize {
return arch.syscall2(SYS_fstat, @bitCast(usize, isize(fd)), @ptrToInt(stat_buf));
}
pub const iovec = extern struct {
iov_base: [*]u8,
iov_len: usize,
};
pub const iovec_const = extern struct {
iov_base: [*]const u8,
iov_len: usize,
};
// TODO avoid libc dependency
pub fn kqueue() usize {
return errnoWrap(c.kqueue());
}
// TODO avoid libc dependency
pub fn kevent(kq: i32, changelist: []const Kevent, eventlist: []Kevent, timeout: ?*const timespec) usize {
return errnoWrap(c.kevent(
kq,
changelist.ptr,
@intCast(c_int, changelist.len),
eventlist.ptr,
@intCast(c_int, eventlist.len),
timeout,
));
}
// TODO avoid libc dependency
pub fn sysctl(name: [*]c_int, namelen: c_uint, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) usize {
return errnoWrap(c.sysctl(name, namelen, oldp, oldlenp, newp, newlen));
}
// TODO avoid libc dependency
pub fn sysctlbyname(name: [*]const u8, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) usize {
return errnoWrap(c.sysctlbyname(name, oldp, oldlenp, newp, newlen));
}
// TODO avoid libc dependency
pub fn sysctlnametomib(name: [*]const u8, mibp: ?*c_int, sizep: ?*usize) usize {
return errnoWrap(c.sysctlnametomib(name, wibp, sizep));
}
// TODO avoid libc dependency
/// Takes the return value from a syscall and formats it back in the way
/// that the kernel represents it to libc. Errno was a mistake, let's make
/// it go away forever.
fn errnoWrap(value: isize) usize {
return @bitCast(usize, if (value == -1) -isize(c._errno().*) else value);
}
|
std/os/freebsd/index.zig
|
const MachO = @This();
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const fs = std.fs;
const log = std.log.scoped(.link);
const macho = std.macho;
const codegen = @import("../codegen.zig");
const math = std.math;
const mem = std.mem;
const trace = @import("../tracy.zig").trace;
const Type = @import("../type.zig").Type;
const Module = @import("../Module.zig");
const link = @import("../link.zig");
const File = link.File;
pub const base_tag: File.Tag = File.Tag.macho;
const LoadCommand = union(enum) {
Segment: macho.segment_command_64,
LinkeditData: macho.linkedit_data_command,
Symtab: macho.symtab_command,
Dysymtab: macho.dysymtab_command,
pub fn cmdsize(self: LoadCommand) u32 {
return switch (self) {
.Segment => |x| x.cmdsize,
.LinkeditData => |x| x.cmdsize,
.Symtab => |x| x.cmdsize,
.Dysymtab => |x| x.cmdsize,
};
}
pub fn write(self: LoadCommand, file: *fs.File, offset: u64) !void {
return switch (self) {
.Segment => |cmd| writeGeneric(cmd, file, offset),
.LinkeditData => |cmd| writeGeneric(cmd, file, offset),
.Symtab => |cmd| writeGeneric(cmd, file, offset),
.Dysymtab => |cmd| writeGeneric(cmd, file, offset),
};
}
fn writeGeneric(cmd: anytype, file: *fs.File, offset: u64) !void {
const slice = [1]@TypeOf(cmd){cmd};
return file.pwriteAll(mem.sliceAsBytes(slice[0..1]), offset);
}
};
base: File,
/// Table of all load commands
load_commands: std.ArrayListUnmanaged(LoadCommand) = .{},
segment_cmd_index: ?u16 = null,
symtab_cmd_index: ?u16 = null,
dysymtab_cmd_index: ?u16 = null,
data_in_code_cmd_index: ?u16 = null,
/// Table of all sections
sections: std.ArrayListUnmanaged(macho.section_64) = .{},
/// __TEXT segment sections
text_section_index: ?u16 = null,
cstring_section_index: ?u16 = null,
const_text_section_index: ?u16 = null,
stubs_section_index: ?u16 = null,
stub_helper_section_index: ?u16 = null,
/// __DATA segment sections
got_section_index: ?u16 = null,
const_data_section_index: ?u16 = null,
entry_addr: ?u64 = null,
/// Table of all symbols used.
/// Internally references string table for names (which are optional).
symbol_table: std.ArrayListUnmanaged(macho.nlist_64) = .{},
/// Table of symbol names aka the string table.
string_table: std.ArrayListUnmanaged(u8) = .{},
/// Table of symbol vaddr values. The values is the absolute vaddr value.
/// If the vaddr of the executable __TEXT segment vaddr changes, the entire offset
/// table needs to be rewritten.
offset_table: std.ArrayListUnmanaged(u64) = .{},
error_flags: File.ErrorFlags = File.ErrorFlags{},
cmd_table_dirty: bool = false,
/// Pointer to the last allocated text block
last_text_block: ?*TextBlock = null,
/// `alloc_num / alloc_den` is the factor of padding when allocating.
const alloc_num = 4;
const alloc_den = 3;
/// Default path to dyld
/// TODO instead of hardcoding it, we should probably look through some env vars and search paths
/// instead but this will do for now.
const DEFAULT_DYLD_PATH: [*:0]const u8 = "/usr/lib/dyld";
/// Default lib search path
/// TODO instead of hardcoding it, we should probably look through some env vars and search paths
/// instead but this will do for now.
const DEFAULT_LIB_SEARCH_PATH: []const u8 = "/usr/lib";
const LIB_SYSTEM_NAME: [*:0]const u8 = "System";
/// TODO we should search for libSystem and fail if it doesn't exist, instead of hardcoding it
const LIB_SYSTEM_PATH: [*:0]const u8 = DEFAULT_LIB_SEARCH_PATH ++ "/libSystem.B.dylib";
pub const TextBlock = struct {
/// Index into the symbol table
symbol_table_index: ?u32,
/// Index into offset table
offset_table_index: ?u32,
/// Size of this text block
size: u64,
/// Points to the previous and next neighbours
prev: ?*TextBlock,
next: ?*TextBlock,
pub const empty = TextBlock{
.symbol_table_index = null,
.offset_table_index = null,
.size = 0,
.prev = null,
.next = null,
};
};
pub const SrcFn = struct {
pub const empty = SrcFn{};
};
pub fn openPath(allocator: *Allocator, dir: fs.Dir, sub_path: []const u8, options: link.Options) !*File {
assert(options.object_format == .macho);
const file = try dir.createFile(sub_path, .{ .truncate = false, .read = true, .mode = link.determineMode(options) });
errdefer file.close();
var macho_file = try allocator.create(MachO);
errdefer allocator.destroy(macho_file);
macho_file.* = openFile(allocator, file, options) catch |err| switch (err) {
error.IncrFailed => try createFile(allocator, file, options),
else => |e| return e,
};
return &macho_file.base;
}
/// Returns error.IncrFailed if incremental update could not be performed.
fn openFile(allocator: *Allocator, file: fs.File, options: link.Options) !MachO {
switch (options.output_mode) {
.Exe => {},
.Obj => {},
.Lib => return error.IncrFailed,
}
var self: MachO = .{
.base = .{
.file = file,
.tag = .macho,
.options = options,
.allocator = allocator,
},
};
errdefer self.deinit();
// TODO implement reading the macho file
return error.IncrFailed;
//try self.populateMissingMetadata();
//return self;
}
/// Truncates the existing file contents and overwrites the contents.
/// Returns an error if `file` is not already open with +read +write +seek abilities.
fn createFile(allocator: *Allocator, file: fs.File, options: link.Options) !MachO {
switch (options.output_mode) {
.Exe => {},
.Obj => {},
.Lib => return error.TODOImplementWritingLibFiles,
}
var self: MachO = .{
.base = .{
.file = file,
.tag = .macho,
.options = options,
.allocator = allocator,
},
};
errdefer self.deinit();
try self.populateMissingMetadata();
return self;
}
pub fn flush(self: *MachO, module: *Module) !void {
switch (self.base.options.output_mode) {
.Exe => {
var last_cmd_offset: usize = @sizeOf(macho.mach_header_64);
{
// Specify path to dynamic linker dyld
const cmdsize = commandSize(@sizeOf(macho.dylinker_command) + mem.lenZ(DEFAULT_DYLD_PATH));
const load_dylinker = [1]macho.dylinker_command{
.{
.cmd = macho.LC_LOAD_DYLINKER,
.cmdsize = cmdsize,
.name = @sizeOf(macho.dylinker_command),
},
};
try self.base.file.?.pwriteAll(mem.sliceAsBytes(load_dylinker[0..1]), last_cmd_offset);
const file_offset = last_cmd_offset + @sizeOf(macho.dylinker_command);
try self.addPadding(cmdsize - @sizeOf(macho.dylinker_command), file_offset);
try self.base.file.?.pwriteAll(mem.spanZ(DEFAULT_DYLD_PATH), file_offset);
last_cmd_offset += cmdsize;
}
{
// Link against libSystem
const cmdsize = commandSize(@sizeOf(macho.dylib_command) + mem.lenZ(LIB_SYSTEM_PATH));
// TODO Find a way to work out runtime version from the OS version triple stored in std.Target.
// In the meantime, we're gonna hardcode to the minimum compatibility version of 1.0.0.
const min_version = 0x10000;
const dylib = .{
.name = @sizeOf(macho.dylib_command),
.timestamp = 2, // not sure why not simply 0; this is reverse engineered from Mach-O files
.current_version = min_version,
.compatibility_version = min_version,
};
const load_dylib = [1]macho.dylib_command{
.{
.cmd = macho.LC_LOAD_DYLIB,
.cmdsize = cmdsize,
.dylib = dylib,
},
};
try self.base.file.?.pwriteAll(mem.sliceAsBytes(load_dylib[0..1]), last_cmd_offset);
const file_offset = last_cmd_offset + @sizeOf(macho.dylib_command);
try self.addPadding(cmdsize - @sizeOf(macho.dylib_command), file_offset);
try self.base.file.?.pwriteAll(mem.spanZ(LIB_SYSTEM_PATH), file_offset);
last_cmd_offset += cmdsize;
}
},
.Obj => {
{
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
symtab.nsyms = @intCast(u32, self.symbol_table.items.len);
const allocated_size = self.allocatedSize(symtab.stroff);
const needed_size = self.string_table.items.len;
log.debug("allocated_size = 0x{x}, needed_size = 0x{x}\n", .{ allocated_size, needed_size });
if (needed_size > allocated_size) {
symtab.strsize = 0;
symtab.stroff = @intCast(u32, self.findFreeSpace(needed_size, 1));
}
symtab.strsize = @intCast(u32, needed_size);
log.debug("writing string table from 0x{x} to 0x{x}\n", .{ symtab.stroff, symtab.stroff + symtab.strsize });
try self.base.file.?.pwriteAll(self.string_table.items, symtab.stroff);
}
var last_cmd_offset: usize = @sizeOf(macho.mach_header_64);
for (self.load_commands.items) |cmd| {
try cmd.write(&self.base.file.?, last_cmd_offset);
last_cmd_offset += cmd.cmdsize();
}
const off = @sizeOf(macho.mach_header_64) + @sizeOf(macho.segment_command_64);
try self.base.file.?.pwriteAll(mem.sliceAsBytes(self.sections.items), off);
},
.Lib => return error.TODOImplementWritingLibFiles,
}
if (self.entry_addr == null and self.base.options.output_mode == .Exe) {
log.debug("flushing. no_entry_point_found = true\n", .{});
self.error_flags.no_entry_point_found = true;
} else {
log.debug("flushing. no_entry_point_found = false\n", .{});
self.error_flags.no_entry_point_found = false;
try self.writeMachOHeader();
}
}
pub fn deinit(self: *MachO) void {
self.offset_table.deinit(self.base.allocator);
self.string_table.deinit(self.base.allocator);
self.symbol_table.deinit(self.base.allocator);
self.sections.deinit(self.base.allocator);
self.load_commands.deinit(self.base.allocator);
}
pub fn allocateDeclIndexes(self: *MachO, decl: *Module.Decl) !void {
if (decl.link.macho.symbol_table_index) |_| return;
try self.symbol_table.ensureCapacity(self.base.allocator, self.symbol_table.items.len + 1);
try self.offset_table.ensureCapacity(self.base.allocator, self.offset_table.items.len + 1);
log.debug("allocating symbol index {} for {}\n", .{ self.symbol_table.items.len, decl.name });
decl.link.macho.symbol_table_index = @intCast(u32, self.symbol_table.items.len);
_ = self.symbol_table.addOneAssumeCapacity();
decl.link.macho.offset_table_index = @intCast(u32, self.offset_table.items.len);
_ = self.offset_table.addOneAssumeCapacity();
self.symbol_table.items[decl.link.macho.symbol_table_index.?] = .{
.n_strx = 0,
.n_type = 0,
.n_sect = 0,
.n_desc = 0,
.n_value = 0,
};
self.offset_table.items[decl.link.macho.offset_table_index.?] = 0;
}
pub fn updateDecl(self: *MachO, module: *Module, decl: *Module.Decl) !void {
const tracy = trace(@src());
defer tracy.end();
var code_buffer = std.ArrayList(u8).init(self.base.allocator);
defer code_buffer.deinit();
const typed_value = decl.typed_value.most_recent.typed_value;
const res = try codegen.generateSymbol(&self.base, decl.src(), typed_value, &code_buffer, .none);
const code = switch (res) {
.externally_managed => |x| x,
.appended => code_buffer.items,
.fail => |em| {
decl.analysis = .codegen_failure;
try module.failed_decls.put(module.gpa, decl, em);
return;
},
};
log.debug("generated code {}\n", .{code});
const required_alignment = typed_value.ty.abiAlignment(self.base.options.target);
const symbol = &self.symbol_table.items[decl.link.macho.symbol_table_index.?];
const decl_name = mem.spanZ(decl.name);
const name_str_index = try self.makeString(decl_name);
const addr = try self.allocateTextBlock(&decl.link.macho, code.len, required_alignment);
log.debug("allocated text block for {} at 0x{x}\n", .{ decl_name, addr });
log.debug("updated text section {}\n", .{self.sections.items[self.text_section_index.?]});
symbol.* = .{
.n_strx = name_str_index,
.n_type = macho.N_SECT,
.n_sect = @intCast(u8, self.text_section_index.?) + 1,
.n_desc = 0,
.n_value = addr,
};
// Since we updated the vaddr and the size, each corresponding export symbol also needs to be updated.
const decl_exports = module.decl_exports.get(decl) orelse &[0]*Module.Export{};
try self.updateDeclExports(module, decl, decl_exports);
try self.writeSymbol(decl.link.macho.symbol_table_index.?);
const text_section = self.sections.items[self.text_section_index.?];
const section_offset = symbol.n_value - text_section.addr;
const file_offset = text_section.offset + section_offset;
log.debug("file_offset 0x{x}\n", .{file_offset});
try self.base.file.?.pwriteAll(code, file_offset);
}
pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl: *const Module.Decl) !void {}
pub fn updateDeclExports(
self: *MachO,
module: *Module,
decl: *const Module.Decl,
exports: []const *Module.Export,
) !void {
const tracy = trace(@src());
defer tracy.end();
if (decl.link.macho.symbol_table_index == null) return;
const decl_sym = &self.symbol_table.items[decl.link.macho.symbol_table_index.?];
// TODO implement
if (exports.len == 0) return;
const exp = exports[0];
self.entry_addr = decl_sym.n_value;
decl_sym.n_type |= macho.N_EXT;
exp.link.sym_index = 0;
}
pub fn freeDecl(self: *MachO, decl: *Module.Decl) void {}
pub fn getDeclVAddr(self: *MachO, decl: *const Module.Decl) u64 {
return self.symbol_table.items[decl.link.macho.symbol_table_index.?].n_value;
}
pub fn populateMissingMetadata(self: *MachO) !void {
if (self.segment_cmd_index == null) {
self.segment_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.Segment = .{
.cmd = macho.LC_SEGMENT_64,
.cmdsize = @sizeOf(macho.segment_command_64),
.segname = makeStaticString(""),
.vmaddr = 0,
.vmsize = 0,
.fileoff = 0,
.filesize = 0,
.maxprot = 0,
.initprot = 0,
.nsects = 0,
.flags = 0,
},
});
self.cmd_table_dirty = true;
}
if (self.symtab_cmd_index == null) {
self.symtab_cmd_index = @intCast(u16, self.load_commands.items.len);
try self.load_commands.append(self.base.allocator, .{
.Symtab = .{
.cmd = macho.LC_SYMTAB,
.cmdsize = @sizeOf(macho.symtab_command),
.symoff = 0,
.nsyms = 0,
.stroff = 0,
.strsize = 0,
},
});
self.cmd_table_dirty = true;
}
if (self.text_section_index == null) {
self.text_section_index = @intCast(u16, self.sections.items.len);
const segment = &self.load_commands.items[self.segment_cmd_index.?].Segment;
segment.cmdsize += @sizeOf(macho.section_64);
segment.nsects += 1;
const file_size = self.base.options.program_code_size_hint;
const off = @intCast(u32, self.findFreeSpace(file_size, 1));
const flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS;
log.debug("found __text section free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
try self.sections.append(self.base.allocator, .{
.sectname = makeStaticString("__text"),
.segname = makeStaticString("__TEXT"),
.addr = 0,
.size = file_size,
.offset = off,
.@"align" = 0x1000,
.reloff = 0,
.nreloc = 0,
.flags = flags,
.reserved1 = 0,
.reserved2 = 0,
.reserved3 = 0,
});
segment.vmsize += file_size;
segment.filesize += file_size;
segment.fileoff = off;
log.debug("initial text section {}\n", .{self.sections.items[self.text_section_index.?]});
}
{
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
if (symtab.symoff == 0) {
const p_align = @sizeOf(macho.nlist_64);
const nsyms = self.base.options.symbol_count_hint;
const file_size = p_align * nsyms;
const off = @intCast(u32, self.findFreeSpace(file_size, p_align));
log.debug("found symbol table free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
symtab.symoff = off;
symtab.nsyms = @intCast(u32, nsyms);
}
if (symtab.stroff == 0) {
try self.string_table.append(self.base.allocator, 0);
const file_size = @intCast(u32, self.string_table.items.len);
const off = @intCast(u32, self.findFreeSpace(file_size, 1));
log.debug("found string table free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
symtab.stroff = off;
symtab.strsize = file_size;
}
}
}
fn allocateTextBlock(self: *MachO, text_block: *TextBlock, new_block_size: u64, alignment: u64) !u64 {
const segment = &self.load_commands.items[self.segment_cmd_index.?].Segment;
const text_section = &self.sections.items[self.text_section_index.?];
const new_block_ideal_capacity = new_block_size * alloc_num / alloc_den;
var block_placement: ?*TextBlock = null;
const addr = blk: {
if (self.last_text_block) |last| {
const last_symbol = self.symbol_table.items[last.symbol_table_index.?];
const end_addr = last_symbol.n_value + last.size;
const new_start_addr = mem.alignForwardGeneric(u64, end_addr, alignment);
block_placement = last;
break :blk new_start_addr;
} else {
break :blk text_section.addr;
}
};
log.debug("computed symbol address 0x{x}\n", .{addr});
const expand_text_section = block_placement == null or block_placement.?.next == null;
if (expand_text_section) {
const text_capacity = self.allocatedSize(text_section.offset);
const needed_size = (addr + new_block_size) - text_section.addr;
log.debug("text capacity 0x{x}, needed size 0x{x}\n", .{ text_capacity, needed_size });
assert(needed_size <= text_capacity); // TODO handle growth
self.last_text_block = text_block;
text_section.size = needed_size;
segment.vmsize = needed_size;
segment.filesize = needed_size;
if (alignment < text_section.@"align") {
text_section.@"align" = @intCast(u32, alignment);
}
}
text_block.size = new_block_size;
if (text_block.prev) |prev| {
prev.next = text_block.next;
}
if (text_block.next) |next| {
next.prev = text_block.prev;
}
if (block_placement) |big_block| {
text_block.prev = big_block;
text_block.next = big_block.next;
big_block.next = text_block;
} else {
text_block.prev = null;
text_block.next = null;
}
return addr;
}
fn makeStaticString(comptime bytes: []const u8) [16]u8 {
var buf = [_]u8{0} ** 16;
if (bytes.len > buf.len) @compileError("string too long; max 16 bytes");
mem.copy(u8, buf[0..], bytes);
return buf;
}
fn makeString(self: *MachO, bytes: []const u8) !u32 {
try self.string_table.ensureCapacity(self.base.allocator, self.string_table.items.len + bytes.len + 1);
const result = self.string_table.items.len;
self.string_table.appendSliceAssumeCapacity(bytes);
self.string_table.appendAssumeCapacity(0);
return @intCast(u32, result);
}
fn alignSize(comptime Int: type, min_size: anytype, alignment: Int) Int {
const size = @intCast(Int, min_size);
if (size % alignment == 0) return size;
const div = size / alignment;
return (div + 1) * alignment;
}
fn commandSize(min_size: anytype) u32 {
return alignSize(u32, min_size, @sizeOf(u64));
}
fn addPadding(self: *MachO, size: u64, file_offset: u64) !void {
if (size == 0) return;
const buf = try self.base.allocator.alloc(u8, size);
defer self.base.allocator.free(buf);
mem.set(u8, buf[0..], 0);
try self.base.file.?.pwriteAll(buf, file_offset);
}
fn detectAllocCollision(self: *MachO, start: u64, size: u64) ?u64 {
const hdr_size: u64 = @sizeOf(macho.mach_header_64);
if (start < hdr_size)
return hdr_size;
const end = start + satMul(size, alloc_num) / alloc_den;
{
const off = @sizeOf(macho.mach_header_64);
var tight_size: u64 = 0;
for (self.load_commands.items) |cmd| {
tight_size += cmd.cmdsize();
}
const increased_size = satMul(tight_size, alloc_num) / alloc_den;
const test_end = off + increased_size;
if (end > off and start < test_end) {
return test_end;
}
}
for (self.sections.items) |section| {
const increased_size = satMul(section.size, alloc_num) / alloc_den;
const test_end = section.offset + increased_size;
if (end > section.offset and start < test_end) {
return test_end;
}
}
if (self.symtab_cmd_index) |symtab_index| {
const symtab = self.load_commands.items[symtab_index].Symtab;
{
const tight_size = @sizeOf(macho.nlist_64) * symtab.nsyms;
const increased_size = satMul(tight_size, alloc_num) / alloc_den;
const test_end = symtab.symoff + increased_size;
if (end > symtab.symoff and start < test_end) {
return test_end;
}
}
{
const increased_size = satMul(symtab.strsize, alloc_num) / alloc_den;
const test_end = symtab.stroff + increased_size;
if (end > symtab.stroff and start < test_end) {
return test_end;
}
}
}
return null;
}
fn allocatedSize(self: *MachO, start: u64) u64 {
if (start == 0)
return 0;
var min_pos: u64 = std.math.maxInt(u64);
{
const off = @sizeOf(macho.mach_header_64);
if (off > start and off < min_pos) min_pos = off;
}
for (self.sections.items) |section| {
if (section.offset <= start) continue;
if (section.offset < min_pos) min_pos = section.offset;
}
if (self.symtab_cmd_index) |symtab_index| {
const symtab = self.load_commands.items[symtab_index].Symtab;
if (symtab.symoff > start and symtab.symoff < min_pos) min_pos = symtab.symoff;
if (symtab.stroff > start and symtab.stroff < min_pos) min_pos = symtab.stroff;
}
return min_pos - start;
}
fn findFreeSpace(self: *MachO, object_size: u64, min_alignment: u16) u64 {
var start: u64 = 0;
while (self.detectAllocCollision(start, object_size)) |item_end| {
start = mem.alignForwardGeneric(u64, item_end, min_alignment);
}
return start;
}
fn writeSymbol(self: *MachO, index: usize) !void {
const tracy = trace(@src());
defer tracy.end();
const symtab = &self.load_commands.items[self.symtab_cmd_index.?].Symtab;
const sym = [1]macho.nlist_64{self.symbol_table.items[index]};
const off = symtab.symoff + @sizeOf(macho.nlist_64) * index;
log.debug("writing symbol {} at 0x{x}\n", .{ sym[0], off });
try self.base.file.?.pwriteAll(mem.sliceAsBytes(sym[0..1]), off);
}
/// Writes Mach-O file header.
/// Should be invoked last as it needs up-to-date values of ncmds and sizeof_cmds bookkeeping
/// variables.
fn writeMachOHeader(self: *MachO) !void {
var hdr: macho.mach_header_64 = undefined;
hdr.magic = macho.MH_MAGIC_64;
const CpuInfo = struct {
cpu_type: macho.cpu_type_t,
cpu_subtype: macho.cpu_subtype_t,
};
const cpu_info: CpuInfo = switch (self.base.options.target.cpu.arch) {
.aarch64 => .{
.cpu_type = macho.CPU_TYPE_ARM64,
.cpu_subtype = macho.CPU_SUBTYPE_ARM_ALL,
},
.x86_64 => .{
.cpu_type = macho.CPU_TYPE_X86_64,
.cpu_subtype = macho.CPU_SUBTYPE_X86_64_ALL,
},
else => return error.UnsupportedMachOArchitecture,
};
hdr.cputype = cpu_info.cpu_type;
hdr.cpusubtype = cpu_info.cpu_subtype;
const filetype: u32 = switch (self.base.options.output_mode) {
.Exe => macho.MH_EXECUTE,
.Obj => macho.MH_OBJECT,
.Lib => switch (self.base.options.link_mode) {
.Static => return error.TODOStaticLibMachOType,
.Dynamic => macho.MH_DYLIB,
},
};
hdr.filetype = filetype;
hdr.ncmds = @intCast(u32, self.load_commands.items.len);
var sizeofcmds: u32 = 0;
for (self.load_commands.items) |cmd| {
sizeofcmds += cmd.cmdsize();
}
hdr.sizeofcmds = sizeofcmds;
// TODO should these be set to something else?
hdr.flags = 0;
hdr.reserved = 0;
log.debug("writing Mach-O header {}\n", .{hdr});
try self.base.file.?.pwriteAll(@ptrCast([*]const u8, &hdr)[0..@sizeOf(macho.mach_header_64)], 0);
}
/// Saturating multiplication
fn satMul(a: anytype, b: anytype) @TypeOf(a, b) {
const T = @TypeOf(a, b);
return std.math.mul(T, a, b) catch std.math.maxInt(T);
}
|
src-self-hosted/link/MachO.zig
|
const std = @import("std");
const c = @cImport({
@cInclude("epoxy/gl.h");
});
comptime {
std.testing.refAllDecls(@This());
}
pub const VertexArray = enum(c.GLuint) {
invalid = 0,
_,
pub const create = createVertexArray;
pub const delete = deleteVertexArray;
pub const gen = genVertexArray;
pub const bind = bindVertexArray;
pub const enableVertexAttribute = enableVertexArrayAttrib;
pub const disableVertexAttribute = disableVertexArrayAttrib;
pub const attribFormat = vertexArrayAttribFormat;
pub const attribIFormat = vertexArrayAttribIFormat;
pub const attribLFormat = vertexArrayAttribLFormat;
pub const attribBinding = vertexArrayAttribBinding;
pub const vertexBuffer = vertexArrayVertexBuffer;
pub const elementBuffer = vertexArrayElementBuffer;
};
pub const Buffer = enum(c.GLuint) {
invalid = 0,
_,
pub const create = createBuffer;
pub const gen = genBuffer;
pub const bind = bindBuffer;
pub const delete = deleteBuffer;
pub const data = namedBufferData;
};
pub const Shader = enum(c.GLuint) {
invalid = 0,
_,
pub const create = createShader;
pub const delete = deleteShader;
pub const compile = compileShader;
pub const source = shaderSource;
pub const get = getShader;
pub const getCompileLog = getShaderInfoLog;
};
pub const Program = enum(c.GLuint) {
invalid = 0,
_,
pub const create = createProgram;
pub const delete = deleteProgram;
pub const attach = attachShader;
pub const detach = detachShader;
pub const link = linkProgram;
pub const use = useProgram;
pub const get = getProgram;
pub const getCompileLog = getProgramInfoLog;
pub const uniformLocation = getUniformLocation;
};
pub const Texture = enum(c.GLuint) {
invalid = 0,
_,
pub const create = createTexture;
pub const delete = deleteTexture;
pub const bindTo = bindTextureUnit;
pub const parameter = textureParameter;
pub const storage2D = textureStorage2D;
pub const storage3D = textureStorage3D;
pub const subImage2D = textureSubImage2D;
pub const subImage3D = textureSubImage3D;
};
pub const ErrorHandling = enum {
/// OpenGL functions will log the error, but will not assert that no error happened
log,
/// Asserts that no errors will happen.
assert,
/// No error checking will be executed. Gotta go fast!
none,
};
const error_handling: ErrorHandling = if (@hasDecl(@import("root"), ""))
@import("root").opengl_error_handling
else if (std.builtin.mode == .ReleaseFast)
.none
else
.assert;
/// Checks if a OpenGL error happend and may yield it.
/// This function is configurable via `opengl_error_handling` in the root file.
/// In Debug mode, unexpected error codes will be unreachable, in all release modes
/// they will be safely wrapped to `error.UnexpectedError`.
fn checkError() void {
if (error_handling == .none)
return;
var error_code = c.glGetError();
if (error_code == c.GL_NO_ERROR)
return;
while (error_code != c.GL_NO_ERROR) : (error_code = c.glGetError()) {
const name = switch (error_code) {
c.GL_INVALID_ENUM => "invalid enum",
c.GL_INVALID_VALUE => "invalid value",
c.GL_INVALID_OPERATION => "invalid operation",
c.GL_STACK_OVERFLOW => "stack overflow",
c.GL_STACK_UNDERFLOW => "stack underflow",
c.GL_OUT_OF_MEMORY => "out of memory",
c.GL_INVALID_FRAMEBUFFER_OPERATION => "invalid framebuffer operation",
// c.GL_INVALID_FRAMEBUFFER_OPERATION_EXT => Error.InvalidFramebufferOperation,
// c.GL_INVALID_FRAMEBUFFER_OPERATION_OES => Error.InvalidFramebufferOperation,
c.GL_TABLE_TOO_LARGE => "Table too large",
// c.GL_TABLE_TOO_LARGE_EXT => Error.TableTooLarge,
c.GL_TEXTURE_TOO_LARGE_EXT => "Texture too large",
else => "unknown error",
};
std.log.scoped(.OpenGL).err("OpenGL failure: {}\n", .{name});
switch (error_handling) {
.log => {},
.assert => @panic("OpenGL error"),
.none => unreachable,
}
}
}
/// Integer conversion helper.
fn cs2gl(size: usize) c.GLsizei {
return @intCast(c.GLsizei, size);
}
fn ui2gl(val: usize) c.GLuint {
return @intCast(c.GLuint, val);
}
fn b2gl(b: bool) c.GLboolean {
return if (b)
c.GL_TRUE
else
c.GL_FALSE;
}
pub const DebugSource = enum {
api,
window_system,
shader_compiler,
third_party,
application,
other,
};
pub const DebugMessageType = enum {
@"error",
deprecated_behavior,
undefined_behavior,
portability,
performance,
other,
};
pub const DebugSeverity = enum {
high,
medium,
low,
notification,
};
fn DebugMessageCallbackHandler(comptime Context: type) type {
return if (Context == void)
fn (source: DebugSource, msg_type: DebugMessageType, id: usize, severity: DebugSeverity, message: []const u8) void
else
fn (context: Context, source: DebugSource, msg_type: DebugMessageType, id: usize, severity: DebugSeverity, message: []const u8) void;
}
/// Sets the OpenGL debug callback handler in zig style.
/// `context` may be a pointer or `{}`.
pub fn debugMessageCallback(context: anytype, comptime handler: DebugMessageCallbackHandler(@TypeOf(context))) void {
const is_void = (@TypeOf(context) == void);
const H = struct {
fn translateSource(source: c.GLuint) DebugSource {
return switch (source) {
c.GL_DEBUG_SOURCE_API => DebugSource.api,
// c.GL_DEBUG_SOURCE_API_ARB => DebugSource.api,
// c.GL_DEBUG_SOURCE_API_KHR => DebugSource.api,
c.GL_DEBUG_SOURCE_WINDOW_SYSTEM => DebugSource.window_system,
// c.GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB => DebugSource.window_system,
// c.GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR => DebugSource.window_system,
c.GL_DEBUG_SOURCE_SHADER_COMPILER => DebugSource.shader_compiler,
// c.GL_DEBUG_SOURCE_SHADER_COMPILER_ARB => DebugSource.shader_compiler,
// c.GL_DEBUG_SOURCE_SHADER_COMPILER_KHR => DebugSource.shader_compiler,
c.GL_DEBUG_SOURCE_THIRD_PARTY => DebugSource.third_party,
// c.GL_DEBUG_SOURCE_THIRD_PARTY_ARB => DebugSource.third_party,
// c.GL_DEBUG_SOURCE_THIRD_PARTY_KHR => DebugSource.third_party,
c.GL_DEBUG_SOURCE_APPLICATION => DebugSource.application,
// c.GL_DEBUG_SOURCE_APPLICATION_ARB => DebugSource.application,
// c.GL_DEBUG_SOURCE_APPLICATION_KHR => DebugSource.application,
c.GL_DEBUG_SOURCE_OTHER => DebugSource.other,
// c.GL_DEBUG_SOURCE_OTHER_ARB => DebugSource.other,
// c.GL_DEBUG_SOURCE_OTHER_KHR => DebugSource.other,
else => DebugSource.other,
};
}
fn translateMessageType(msg_type: c.GLuint) DebugMessageType {
return switch (msg_type) {
c.GL_DEBUG_TYPE_ERROR => DebugMessageType.@"error",
// c.GL_DEBUG_TYPE_ERROR_ARB => DebugMessageType.@"error",
// c.GL_DEBUG_TYPE_ERROR_KHR => DebugMessageType.@"error",
c.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR => DebugMessageType.deprecated_behavior,
// c.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB => DebugMessageType.deprecated_behavior,
// c.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR => DebugMessageType.deprecated_behavior,
c.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR => DebugMessageType.undefined_behavior,
// c.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB => DebugMessageType.undefined_behavior,
// c.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR => DebugMessageType.undefined_behavior,
c.GL_DEBUG_TYPE_PORTABILITY => DebugMessageType.portability,
// c.GL_DEBUG_TYPE_PORTABILITY_ARB => DebugMessageType.portability,
// c.GL_DEBUG_TYPE_PORTABILITY_KHR => DebugMessageType.portability,
c.GL_DEBUG_TYPE_PERFORMANCE => DebugMessageType.performance,
// c.GL_DEBUG_TYPE_PERFORMANCE_ARB => DebugMessageType.performance,
// c.GL_DEBUG_TYPE_PERFORMANCE_KHR => DebugMessageType.performance,
c.GL_DEBUG_TYPE_OTHER => DebugMessageType.other,
// c.GL_DEBUG_TYPE_OTHER_ARB => DebugMessageType.other,
// c.GL_DEBUG_TYPE_OTHER_KHR => DebugMessageType.other,
else => DebugMessageType.other,
};
}
fn translateSeverity(sev: c.GLuint) DebugSeverity {
return switch (sev) {
c.GL_DEBUG_SEVERITY_HIGH => DebugSeverity.high,
// c.GL_DEBUG_SEVERITY_HIGH_AMD => DebugSeverity.high,
// c.GL_DEBUG_SEVERITY_HIGH_ARB => DebugSeverity.high,
// c.GL_DEBUG_SEVERITY_HIGH_KHR => DebugSeverity.high,
c.GL_DEBUG_SEVERITY_MEDIUM => DebugSeverity.medium,
// c.GL_DEBUG_SEVERITY_MEDIUM_AMD => DebugSeverity.medium,
// c.GL_DEBUG_SEVERITY_MEDIUM_ARB => DebugSeverity.medium,
// c.GL_DEBUG_SEVERITY_MEDIUM_KHR => DebugSeverity.medium,
c.GL_DEBUG_SEVERITY_LOW => DebugSeverity.low,
// c.GL_DEBUG_SEVERITY_LOW_AMD => DebugSeverity.low,
// c.GL_DEBUG_SEVERITY_LOW_ARB => DebugSeverity.low,
// c.GL_DEBUG_SEVERITY_LOW_KHR => DebugSeverity.low,
c.GL_DEBUG_SEVERITY_NOTIFICATION => DebugSeverity.notification,
// c.GL_DEBUG_SEVERITY_NOTIFICATION_KHR => DebugSeverity.notification,
else => DebugSeverity.high,
};
}
fn callback(
c_source: c.GLenum,
c_msg_type: c.GLenum,
id: c.GLuint,
c_severity: c.GLenum,
length: c.GLsizei,
c_message: [*c]const c.GLchar,
userParam: ?*const c_void,
) callconv(.C) void {
const debug_source = translateSource(c_source);
const msg_type = translateMessageType(c_msg_type);
const severity = translateSeverity(c_severity);
const message = c_message[0..@intCast(usize, length)];
if (is_void) {
handler(debug_source, msg_type, id, severity, message);
} else {
handler(@ptrCast(@TypeOf(context), userParam), debug_source, msg_type, id, severity, message);
}
}
};
if (is_void)
c.glDebugMessageCallback(H.callback, null)
else
c.glDebugMessageCallback(H.callback, @ptrCast(?*const c_void, context));
checkError();
}
pub fn clearColor(r: f32, g: f32, b: f32, a: f32) void {
c.glClearColor(r, g, b, a);
checkError();
}
pub fn clearDepth(depth: f32) void {
c.glClearDepth(depth);
checkError();
}
pub fn clear(mask: struct { color: bool = false, depth: bool = false, stencil: bool = false }) void {
c.glClear(
(if (mask.color) c.GL_COLOR_BUFFER_BIT else @as(c.GLenum, 0)) |
(if (mask.depth) c.GL_DEPTH_BUFFER_BIT else @as(c.GLenum, 0)) |
(if (mask.stencil) c.GL_STENCIL_BUFFER_BIT else @as(c.GLenum, 0)),
);
checkError();
}
///////////////////////////////////////////////////////////////////////////////
// Vertex Arrays
pub fn createVertexArrays(items: []VertexArray) void {
c.glCreateVertexArrays(cs2gl(items.len), @ptrCast([*]c.GLuint, items.ptr));
checkError();
}
pub fn createVertexArray() VertexArray {
var vao: VertexArray = undefined;
createVertexArrays(@ptrCast([*]VertexArray, &vao)[0..1]);
return vao;
}
pub fn genVertexArrays(items: []VertexArray) void {
c.glGenVertexArrays(cs2gl(items.len), @ptrCast([*]c.GLuint, items.ptr));
checkError();
}
pub fn genVertexArray() VertexArray {
var vao: VertexArray = undefined;
genVertexArrays(@ptrCast([*]VertexArray, &vao)[0..1]);
return vao;
}
pub fn bindVertexArray(vao: VertexArray) void {
c.glBindVertexArray(@enumToInt(vao));
checkError();
}
pub fn deleteVertexArrays(items: []const VertexArray) void {
c.glDeleteVertexArrays(cs2gl(items.len), @ptrCast([*]const c.GLuint, items.ptr));
}
pub fn deleteVertexArray(vao: VertexArray) void {
deleteVertexArrays(@ptrCast([*]const VertexArray, &vao)[0..1]);
}
pub fn enableVertexAttribArray(index: u32) void {
c.glEnableVertexAttribArray(index);
checkError();
}
pub fn disableVertexAttribArray(index: u32) void {
c.glDisableVertexAttribArray(index);
checkError();
}
pub fn enableVertexArrayAttrib(vertexArray: VertexArray, index: u32) void {
c.glEnableVertexArrayAttrib(@enumToInt(vertexArray), index);
checkError();
}
pub fn disableVertexArrayAttrib(vertexArray: VertexArray, index: u32) void {
c.glDisableVertexArrayAttrib(@enumToInt(vertexArray), index);
checkError();
}
pub const Type = enum(c.GLenum) {
byte = c.GL_BYTE,
short = c.GL_SHORT,
int = c.GL_INT,
fixed = c.GL_FIXED,
float = c.GL_FLOAT,
half_float = c.GL_HALF_FLOAT,
double = c.GL_DOUBLE,
unsigned_byte = c.GL_UNSIGNED_BYTE,
unsigned_short = c.GL_UNSIGNED_SHORT,
unsigned_int = c.GL_UNSIGNED_INT,
int_2_10_10_10_rev = c.GL_INT_2_10_10_10_REV,
unsigned_int_2_10_10_10_rev = c.GL_UNSIGNED_INT_2_10_10_10_REV,
unsigned_int_10_f_11_f_11_f_rev = c.GL_UNSIGNED_INT_10F_11F_11F_REV,
};
pub fn vertexAttribFormat(attribindex: u32, size: u32, attribute_type: Type, normalized: bool, relativeoffset: usize) void {
c.glVertexAttribFormat(
attribindex,
@intCast(c.GLint, size),
@enumToInt(attribute_type),
b2gl(normalized),
ui2gl(relativeoffset),
);
checkError();
}
pub fn vertexAttribIFormat(attribindex: u32, size: u32, attribute_type: Type, relativeoffset: usize) void {
c.glVertexAttribIFormat(
attribindex,
@intCast(c.GLint, size),
@enumToInt(attribute_type),
ui2gl(relativeoffset),
);
checkError();
}
pub fn vertexAttribLFormat(attribindex: u32, size: u32, attribute_type: Type, relativeoffset: usize) void {
c.glVertexAttribLFormat(
attribindex,
@intCast(c.GLint, size),
@enumToInt(attribute_type),
ui2gl(relativeoffset),
);
checkError();
}
pub fn vertexAttribPointer(attribindex: u32, size: u32, attribute_type: Type, normalized: bool, stride: usize, relativeoffset: ?usize) void {
c.glVertexAttribPointer(
attribindex,
@intCast(c.GLint, size),
@enumToInt(attribute_type),
b2gl(normalized),
@intCast(c.GLint, stride),
if (relativeoffset != null) @intToPtr(*c_void, relativeoffset.?) else null,
);
checkError();
}
pub fn vertexArrayAttribFormat(
vertexArray: VertexArray,
attribindex: u32,
size: u32,
attribute_type: Type,
normalized: bool,
relativeoffset: usize,
) void {
c.glVertexArrayAttribFormat(
@enumToInt(vertexArray),
attribindex,
@intCast(c.GLint, size),
@enumToInt(attribute_type),
b2gl(normalized),
ui2gl(relativeoffset),
);
checkError();
}
pub fn vertexArrayAttribIFormat(vertexArray: VertexArray, attribindex: u32, size: u32, attribute_type: Type, relativeoffset: usize) void {
c.glVertexArrayAttribIFormat(
@enumToInt(vertexArray),
attribindex,
@intCast(
c.GLint,
size,
),
@enumToInt(attribute_type),
ui2gl(relativeoffset),
);
checkError();
}
pub fn vertexArrayAttribLFormat(vertexArray: VertexArray, attribindex: u32, size: u32, attribute_type: Type, relativeoffset: usize) void {
c.glVertexArrayAttribLFormat(
@enumToInt(vertexArray),
attribindex,
@intCast(
c.GLint,
size,
),
@enumToInt(attribute_type),
relativeoffset,
);
checkError();
}
pub fn vertexAttribBinding(attribindex: u32, bindingindex: u32) void {
c.glVertexAttribBinding(
attribindex,
bindingindex,
);
checkError();
}
pub fn vertexArrayAttribBinding(vertexArray: VertexArray, attribindex: u32, bindingindex: u32) void {
c.glVertexArrayAttribBinding(
@enumToInt(vertexArray),
attribindex,
bindingindex,
);
checkError();
}
pub fn bindVertexBuffer(bindingindex: u32, buffer: Buffer, offset: usize, stride: usize) void {
c.glBindVertexBuffer(bindingindex, @enumToInt(buffer), cs2gl(offset), cs2gl(stride));
checkError();
}
pub fn vertexArrayVertexBuffer(vertexArray: VertexArray, bindingindex: u32, buffer: Buffer, offset: usize, stride: usize) void {
c.glVertexArrayVertexBuffer(@enumToInt(vertexArray), bindingindex, @enumToInt(buffer), cs2gl(offset), cs2gl(stride));
checkError();
}
pub fn vertexArrayElementBuffer(vertexArray: VertexArray, buffer: Buffer) void {
c.glVertexArrayElementBuffer(@enumToInt(vertexArray), @enumToInt(buffer));
checkError();
}
///////////////////////////////////////////////////////////////////////////////
// Buffer
pub const BufferTarget = enum(c.GLenum) {
/// Vertex attributes
array_buffer = c.GL_ARRAY_BUFFER,
/// Atomic counter storage
atomic_counter_buffer = c.GL_ATOMIC_COUNTER_BUFFER,
/// Buffer copy source
copy_read_buffer = c.GL_COPY_READ_BUFFER,
/// Buffer copy destination
copy_write_buffer = c.GL_COPY_WRITE_BUFFER,
/// Indirect compute dispatch commands
dispatch_indirect_buffer = c.GL_DISPATCH_INDIRECT_BUFFER,
/// Indirect command arguments
draw_indirect_buffer = c.GL_DRAW_INDIRECT_BUFFER,
/// Vertex array indices
element_array_buffer = c.GL_ELEMENT_ARRAY_BUFFER,
/// Pixel read target
pixel_pack_buffer = c.GL_PIXEL_PACK_BUFFER,
/// Texture data source
pixel_unpack_buffer = c.GL_PIXEL_UNPACK_BUFFER,
/// Query result buffer
query_buffer = c.GL_QUERY_BUFFER,
/// Read-write storage for shaders
shader_storage_buffer = c.GL_SHADER_STORAGE_BUFFER,
/// Texture data buffer
texture_buffer = c.GL_TEXTURE_BUFFER,
/// Transform feedback buffer
transform_feedback_buffer = c.GL_TRANSFORM_FEEDBACK_BUFFER,
/// Uniform block storage
uniform_buffer = c.GL_UNIFORM_BUFFER,
};
pub fn createBuffers(items: []Buffer) void {
c.glCreateBuffers(cs2gl(items.len), @ptrCast([*]c.GLuint, items.ptr));
checkError();
}
pub fn createBuffer() Buffer {
var buf: Buffer = undefined;
createBuffers(@ptrCast([*]Buffer, &buf)[0..1]);
return buf;
}
pub fn genBuffers(items: []Buffer) void {
c.glGenBuffers(cs2gl(items.len), @ptrCast([*]c.GLuint, items.ptr));
checkError();
}
pub fn genBuffer() Buffer {
var buf: Buffer = undefined;
genBuffers(@ptrCast([*]Buffer, &buf)[0..1]);
return buf;
}
pub fn bindBuffer(buf: Buffer, target: BufferTarget) void {
c.glBindBuffer(@enumToInt(target), @enumToInt(buf));
checkError();
}
pub fn deleteBuffers(items: []const Buffer) void {
c.glDeleteBuffers(cs2gl(items.len), @ptrCast([*]const c.GLuint, items.ptr));
}
pub fn deleteBuffer(buf: Buffer) void {
deleteBuffers(@ptrCast([*]const Buffer, &buf)[0..1]);
}
pub const BufferUsage = enum(c.GLenum) {
stream_draw = c.GL_STREAM_DRAW,
stream_read = c.GL_STREAM_READ,
stream_copy = c.GL_STREAM_COPY,
static_draw = c.GL_STATIC_DRAW,
static_read = c.GL_STATIC_READ,
static_copy = c.GL_STATIC_COPY,
dynamic_draw = c.GL_DYNAMIC_DRAW,
dynamic_read = c.GL_DYNAMIC_READ,
dynamic_copy = c.GL_DYNAMIC_COPY,
};
// using align(1) as we are not required to have aligned data here
pub fn namedBufferData(buf: Buffer, comptime T: type, items: []align(1) const T, usage: BufferUsage) void {
c.glNamedBufferData(
@enumToInt(buf),
cs2gl(@sizeOf(T) * items.len),
items.ptr,
@enumToInt(usage),
);
checkError();
}
pub fn bufferData(target: BufferTarget, comptime T: type, items: []align(1) const T, usage: BufferUsage) void {
c.glBufferData(
@enumToInt(target),
cs2gl(@sizeOf(T) * items.len),
items.ptr,
@enumToInt(usage),
);
checkError();
}
///////////////////////////////////////////////////////////////////////////////
// Shaders
pub const ShaderType = enum(c.GLenum) {
compute = c.GL_COMPUTE_SHADER,
vertex = c.GL_VERTEX_SHADER,
tess_control = c.GL_TESS_CONTROL_SHADER,
tess_evaluation = c.GL_TESS_EVALUATION_SHADER,
geometry = c.GL_GEOMETRY_SHADER,
fragment = c.GL_FRAGMENT_SHADER,
};
pub fn createShader(shaderType: ShaderType) Shader {
const shader = @intToEnum(Shader, c.glCreateShader(@enumToInt(shaderType)));
if (shader == .invalid) {
checkError();
unreachable;
}
return shader;
}
pub fn deleteShader(shader: Shader) void {
c.glDeleteShader(@enumToInt(shader));
checkError();
}
pub fn compileShader(shader: Shader) void {
c.glCompileShader(@enumToInt(shader));
checkError();
}
pub fn shaderSource(shader: Shader, comptime N: comptime_int, sources: *const [N][]const u8) void {
var lengths: [N]c.GLint = undefined;
for (lengths) |*len, i| {
len.* = @intCast(c.GLint, sources[i].len);
}
var ptrs: [N]*const c.GLchar = undefined;
for (ptrs) |*ptr, i| {
ptr.* = @ptrCast(*const c.GLchar, sources[i].ptr);
}
c.glShaderSource(@enumToInt(shader), N, &ptrs, &lengths);
checkError();
}
pub const ShaderParameter = enum(c.GLenum) {
shader_type = c.GL_SHADER_TYPE,
delete_status = c.GL_DELETE_STATUS,
compile_status = c.GL_COMPILE_STATUS,
info_log_length = c.GL_INFO_LOG_LENGTH,
shader_source_length = c.GL_SHADER_SOURCE_LENGTH,
};
pub fn getShader(shader: Shader, parameter: ShaderParameter) c.GLint {
var value: c.GLint = undefined;
c.glGetShaderiv(@enumToInt(shader), @enumToInt(parameter), &value);
checkError();
return value;
}
pub fn getShaderInfoLog(shader: Shader, allocator: *std.mem.Allocator) ![:0]const u8 {
const length = getShader(shader, .info_log_length);
const log = try allocator.allocWithOptions(u8, @intCast(usize, length) + 1, null, 0);
errdefer allocator.free(log);
var actual_length: c.GLsizei = undefined;
c.glGetShaderInfoLog(@enumToInt(shader), cs2gl(log.len), &actual_length, log.ptr);
checkError();
log[@intCast(usize, actual_length)] = 0;
return log[0..@intCast(usize, actual_length) :0];
}
///////////////////////////////////////////////////////////////////////////////
// Program
pub fn createProgram() Program {
const program = @intToEnum(Program, c.glCreateProgram());
if (program == .invalid) {
checkError();
unreachable;
}
return program;
}
pub fn deleteProgram(program: Program) void {
c.glDeleteProgram(@enumToInt(program));
checkError();
}
pub fn linkProgram(program: Program) void {
c.glLinkProgram(@enumToInt(program));
checkError();
}
pub fn attachShader(program: Program, shader: Shader) void {
c.glAttachShader(@enumToInt(program), @enumToInt(shader));
checkError();
}
pub fn detachShader(program: Program, shader: Shader) void {
c.glDetachShader(@enumToInt(program), @enumToInt(shader));
checkError();
}
pub fn useProgram(program: Program) void {
c.glUseProgram(@enumToInt(program));
checkError();
}
pub const ProgramParameter = enum(c.GLenum) {
delete_status = c.GL_DELETE_STATUS,
link_status = c.GL_LINK_STATUS,
validate_status = c.GL_VALIDATE_STATUS,
info_log_length = c.GL_INFO_LOG_LENGTH,
attached_shaders = c.GL_ATTACHED_SHADERS,
active_atomic_counter_buffers = c.GL_ACTIVE_ATOMIC_COUNTER_BUFFERS,
active_attributes = c.GL_ACTIVE_ATTRIBUTES,
active_attribute_max_length = c.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH,
active_uniforms = c.GL_ACTIVE_UNIFORMS,
active_uniform_blocks = c.GL_ACTIVE_UNIFORM_BLOCKS,
active_uniform_block_max_name_length = c.GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH,
active_uniform_max_length = c.GL_ACTIVE_UNIFORM_MAX_LENGTH,
compute_work_group_size = c.GL_COMPUTE_WORK_GROUP_SIZE,
program_binary_length = c.GL_PROGRAM_BINARY_LENGTH,
transform_feedback_buffer_mode = c.GL_TRANSFORM_FEEDBACK_BUFFER_MODE,
transform_feedback_varyings = c.GL_TRANSFORM_FEEDBACK_VARYINGS,
transform_feedback_varying_max_length = c.GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH,
geometry_vertices_out = c.GL_GEOMETRY_VERTICES_OUT,
geometry_input_type = c.GL_GEOMETRY_INPUT_TYPE,
geometry_output_type = c.GL_GEOMETRY_OUTPUT_TYPE,
};
pub fn getProgram(program: Program, parameter: ProgramParameter) c.GLint {
var value: c.GLint = undefined;
c.glGetProgramiv(@enumToInt(program), @enumToInt(parameter), &value);
checkError();
return value;
}
pub fn getProgramInfoLog(program: Program, allocator: *std.mem.Allocator) ![:0]const u8 {
const length = getProgram(program, .info_log_length);
const log = try allocator.allocWithOptions(u8, @intCast(usize, length) + 1, null, 0);
errdefer allocator.free(log);
var actual_length: c.GLsizei = undefined;
c.glGetProgramInfoLog(@enumToInt(program), cs2gl(log.len), &actual_length, log.ptr);
checkError();
log[@intCast(usize, actual_length)] = 0;
return log[0..@intCast(usize, actual_length) :0];
}
pub fn getUniformLocation(program: Program, name: [:0]const u8) ?u32 {
const loc = c.glGetUniformLocation(@enumToInt(program), name.ptr);
checkError();
if (loc < 0)
return null;
return @intCast(u32, loc);
}
///////////////////////////////////////////////////////////////////////////////
// Uniforms
pub fn programUniform1u(program: Program, location: ?u32, value: u32) void {
if (location) |loc| {
c.glProgramUniform1u(@enumToInt(program), @intCast(c.GLint, loc), value);
checkError();
}
}
pub fn programUniform1i(program: Program, location: ?u32, value: i32) void {
if (location) |loc| {
c.glProgramUniform1i(@enumToInt(program), @intCast(c.GLint, loc), value);
checkError();
}
}
pub fn programUniform1f(program: Program, location: ?u32, value: f32) void {
if (location) |loc| {
c.glProgramUniform1f(@enumToInt(program), @intCast(c.GLint, loc), value);
checkError();
}
}
pub fn programUniform3f(program: Program, location: ?u32, x: f32, y: f32, z: f32) void {
if (location) |loc| {
c.glProgramUniform3f(@enumToInt(program), @intCast(c.GLint, loc), x, y, z);
checkError();
}
}
pub fn programUniformMatrix4(program: Program, location: ?u32, transpose: bool, items: []const [4][4]f32) void {
if (location) |loc| {
c.glProgramUniformMatrix4fv(
@enumToInt(program),
@intCast(c.GLint, loc),
cs2gl(items.len),
b2gl(transpose),
@ptrCast(*const f32, items.ptr),
);
checkError();
}
}
///////////////////////////////////////////////////////////////////////////////
// Draw Calls
pub const PrimitiveType = enum(c.GLenum) {
points = c.GL_POINTS,
line_strip = c.GL_LINE_STRIP,
line_loop = c.GL_LINE_LOOP,
lines = c.GL_LINES,
line_strip_adjacency = c.GL_LINE_STRIP_ADJACENCY,
lines_adjacency = c.GL_LINES_ADJACENCY,
triangle_strip = c.GL_TRIANGLE_STRIP,
triangle_fan = c.GL_TRIANGLE_FAN,
triangles = c.GL_TRIANGLES,
triangle_strip_adjacency = c.GL_TRIANGLE_STRIP_ADJACENCY,
triangles_adjacency = c.GL_TRIANGLES_ADJACENCY,
patches = c.GL_PATCHES,
};
pub fn drawArrays(primitiveType: PrimitiveType, first: usize, count: usize) void {
c.glDrawArrays(@enumToInt(primitiveType), cs2gl(first), cs2gl(count));
checkError();
}
pub const ElementType = enum(c.GLenum) {
u8 = c.GL_UNSIGNED_BYTE,
u16 = c.GL_UNSIGNED_SHORT,
u32 = c.GL_UNSIGNED_INT,
};
pub fn drawElements(primitiveType: PrimitiveType, count: usize, element_type: ElementType, indices: ?*const c_void) void {
c.glDrawElements(
@enumToInt(primitiveType),
cs2gl(count),
@enumToInt(element_type),
indices,
);
checkError();
}
pub fn drawElementsInstanced(primitiveType: PrimitiveType, count: usize, element_type: ElementType, indices: ?*const c_void, instance_count: usize) void {
c.glDrawElementsInstanced(
@enumToInt(primitiveType),
cs2gl(count),
@enumToInt(element_type),
indices,
cs2gl(instance_count),
);
checkError();
}
///////////////////////////////////////////////////////////////////////////////
// Status Control
pub const Capabilities = enum(c.GLenum) {
blend = c.GL_BLEND,
// clip_distance = c.GL_CLIP_DISTANCE,
color_logic_op = c.GL_COLOR_LOGIC_OP,
cull_face = c.GL_CULL_FACE,
debug_output = c.GL_DEBUG_OUTPUT,
debug_output_synchronous = c.GL_DEBUG_OUTPUT_SYNCHRONOUS,
depth_clamp = c.GL_DEPTH_CLAMP,
depth_test = c.GL_DEPTH_TEST,
dither = c.GL_DITHER,
framebuffer_srgb = c.GL_FRAMEBUFFER_SRGB,
line_smooth = c.GL_LINE_SMOOTH,
multisample = c.GL_MULTISAMPLE,
polygon_offset_fill = c.GL_POLYGON_OFFSET_FILL,
polygon_offset_line = c.GL_POLYGON_OFFSET_LINE,
polygon_offset_point = c.GL_POLYGON_OFFSET_POINT,
polygon_smooth = c.GL_POLYGON_SMOOTH,
primitive_restart = c.GL_PRIMITIVE_RESTART,
primitive_restart_fixed_index = c.GL_PRIMITIVE_RESTART_FIXED_INDEX,
rasterizer_discard = c.GL_RASTERIZER_DISCARD,
sample_alpha_to_coverage = c.GL_SAMPLE_ALPHA_TO_COVERAGE,
sample_alpha_to_one = c.GL_SAMPLE_ALPHA_TO_ONE,
sample_coverage = c.GL_SAMPLE_COVERAGE,
sample_shading = c.GL_SAMPLE_SHADING,
sample_mask = c.GL_SAMPLE_MASK,
scissor_test = c.GL_SCISSOR_TEST,
stencil_test = c.GL_STENCIL_TEST,
texture_cube_map_seamless = c.GL_TEXTURE_CUBE_MAP_SEAMLESS,
program_point_size = c.GL_PROGRAM_POINT_SIZE,
};
pub fn enable(cap: Capabilities) void {
c.glEnable(@enumToInt(cap));
checkError();
}
pub fn disable(cap: Capabilities) void {
c.glDisable(@enumToInt(cap));
checkError();
}
pub fn enableI(cap: Capabilities, index: u32) void {
c.glEnablei(@enumToInt(cap), index);
checkError();
}
pub fn disableI(cap: Capabilities, index: u32) void {
c.glDisablei(@enumToInt(cap), index);
checkError();
}
pub fn depthMask(enabled: bool) void {
c.glDepthMask(if (enabled) c.GL_TRUE else c.GL_FALSE);
checkError();
}
pub const DepthFunc = enum(c.GLenum) {
never = c.GL_NEVER,
less = c.GL_LESS,
equal = c.GL_EQUAL,
less_or_equal = c.GL_LEQUAL,
greater = c.GL_GREATER,
not_equal = c.GL_NOTEQUAL,
greator_or_equal = c.GL_GEQUAL,
always = c.GL_ALWAYS,
};
pub fn depthFunc(func: DepthFunc) void {
c.glDepthFunc(@enumToInt(func));
checkError();
}
pub fn polygonOffset(factor: f32, units: f32) void {
c.glPolygonOffset(factor, units);
checkError();
}
pub fn pointSize(size: f32) void {
c.glPointSize(size);
checkError();
}
pub fn lineWidth(size: f32) void {
c.glLineWidth(size);
checkError();
}
pub const TextureTarget = enum(c.GLenum) {
@"1d" = c.GL_TEXTURE_1D,
@"2d" = c.GL_TEXTURE_2D,
@"3d" = c.GL_TEXTURE_3D,
@"1d_array" = c.GL_TEXTURE_1D_ARRAY,
@"2d_array" = c.GL_TEXTURE_2D_ARRAY,
rectangle = c.GL_TEXTURE_RECTANGLE,
cube_map = c.GL_TEXTURE_CUBE_MAP,
cube_map_array = c.GL_TEXTURE_CUBE_MAP_ARRAY,
buffer = c.GL_TEXTURE_BUFFER,
@"2d_multisample" = c.GL_TEXTURE_2D_MULTISAMPLE,
@"2d_multisample_array" = c.GL_TEXTURE_2D_MULTISAMPLE_ARRAY,
};
pub fn createTexture(texture_target: TextureTarget) Texture {
var tex_name: c.GLuint = undefined;
c.glCreateTextures(@enumToInt(texture_target), 1, &tex_name);
checkError();
const texture = @intToEnum(Texture, tex_name);
if (texture == .invalid) {
checkError();
unreachable;
}
return texture;
}
pub fn deleteTexture(texture: Texture) void {
var id = @enumToInt(texture);
c.glDeleteTextures(1, &id);
}
pub fn bindTextureUnit(texture: Texture, unit: u32) void {
c.glBindTextureUnit(unit, @enumToInt(texture));
checkError();
}
pub const TextureParameter = enum(c.GLenum) {
depth_stencil_texture_mode = c.GL_DEPTH_STENCIL_TEXTURE_MODE,
base_level = c.GL_TEXTURE_BASE_LEVEL,
compare_func = c.GL_TEXTURE_COMPARE_FUNC,
compare_mode = c.GL_TEXTURE_COMPARE_MODE,
lod_bias = c.GL_TEXTURE_LOD_BIAS,
min_filter = c.GL_TEXTURE_MIN_FILTER,
mag_filter = c.GL_TEXTURE_MAG_FILTER,
min_lod = c.GL_TEXTURE_MIN_LOD,
max_lod = c.GL_TEXTURE_MAX_LOD,
max_level = c.GL_TEXTURE_MAX_LEVEL,
swizzle_r = c.GL_TEXTURE_SWIZZLE_R,
swizzle_g = c.GL_TEXTURE_SWIZZLE_G,
swizzle_b = c.GL_TEXTURE_SWIZZLE_B,
swizzle_a = c.GL_TEXTURE_SWIZZLE_A,
wrap_s = c.GL_TEXTURE_WRAP_S,
wrap_t = c.GL_TEXTURE_WRAP_T,
wrap_r = c.GL_TEXTURE_WRAP_R,
};
fn TextureParameterType(comptime param: TextureParameter) type {
// see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexParameter.xhtml
return switch (param) {
.wrap_s, .wrap_t, .wrap_r => enum(c.GLint) {
clamp_to_edge = c.GL_CLAMP_TO_EDGE,
clamp_to_border = c.GL_CLAMP_TO_BORDER,
mirrored_repeat = c.GL_MIRRORED_REPEAT,
repeat = c.GL_REPEAT,
mirror_clamp_to_edge = c.GL_MIRROR_CLAMP_TO_EDGE,
},
.mag_filter => enum(c.GLint) {
nearest = c.GL_NEAREST,
linear = c.GL_LINEAR,
},
.min_filter => enum(c.GLint) {
nearest = c.GL_NEAREST,
linear = c.GL_LINEAR,
nearest_mipmap_nearest = c.GL_NEAREST_MIPMAP_NEAREST,
linear_mipmap_nearest = c.GL_LINEAR_MIPMAP_NEAREST,
nearest_mipmap_linear = c.GL_NEAREST_MIPMAP_LINEAR,
linear_mipmap_linear = c.GL_LINEAR_MIPMAP_LINEAR,
},
else => @compileError("textureParameter not implemented yet for " ++ @tagName(param)),
};
}
pub fn textureParameter(texture: Texture, comptime parameter: TextureParameter, value: TextureParameterType(parameter)) void {
const T = TextureParameterType(parameter);
const info = @typeInfo(T);
if (info == .Enum) {
c.glTextureParameteri(@enumToInt(texture), @enumToInt(parameter), @enumToInt(value));
} else {
@compileError(@tagName(info) ++ " is not supported yet by textureParameter");
}
checkError();
}
pub const TextureInternalFormat = enum(c.GLenum) {
r8 = c.GL_R8,
r8_snorm = c.GL_R8_SNORM,
r16 = c.GL_R16,
r16_snorm = c.GL_R16_SNORM,
rg8 = c.GL_RG8,
rg8_snorm = c.GL_RG8_SNORM,
rg16 = c.GL_RG16,
rg16_snorm = c.GL_RG16_SNORM,
r3_g3_b2 = c.GL_R3_G3_B2,
rgb4 = c.GL_RGB4,
rgb5 = c.GL_RGB5,
rgb8 = c.GL_RGB8,
rgb8_snorm = c.GL_RGB8_SNORM,
rgb10 = c.GL_RGB10,
rgb12 = c.GL_RGB12,
rgb16_snorm = c.GL_RGB16_SNORM,
rgba2 = c.GL_RGBA2,
rgba4 = c.GL_RGBA4,
rgb5_a1 = c.GL_RGB5_A1,
rgba8 = c.GL_RGBA8,
rgba8_snorm = c.GL_RGBA8_SNORM,
rgb10_a2 = c.GL_RGB10_A2,
rgb10_a2ui = c.GL_RGB10_A2UI,
rgba12 = c.GL_RGBA12,
rgba16 = c.GL_RGBA16,
srgb8 = c.GL_SRGB8,
srgb8_alpha8 = c.GL_SRGB8_ALPHA8,
r16f = c.GL_R16F,
rg16f = c.GL_RG16F,
rgb16f = c.GL_RGB16F,
rgba16f = c.GL_RGBA16F,
r32f = c.GL_R32F,
rg32f = c.GL_RG32F,
rgb32f = c.GL_RGB32F,
rgba32f = c.GL_RGBA32F,
r11f_g11f_b10f = c.GL_R11F_G11F_B10F,
rgb9_e5 = c.GL_RGB9_E5,
r8i = c.GL_R8I,
r8ui = c.GL_R8UI,
r16i = c.GL_R16I,
r16ui = c.GL_R16UI,
r32i = c.GL_R32I,
r32ui = c.GL_R32UI,
rg8i = c.GL_RG8I,
rg8ui = c.GL_RG8UI,
rg16i = c.GL_RG16I,
rg16ui = c.GL_RG16UI,
rg32i = c.GL_RG32I,
rg32ui = c.GL_RG32UI,
rgb8i = c.GL_RGB8I,
rgb8ui = c.GL_RGB8UI,
rgb16i = c.GL_RGB16I,
rgb16ui = c.GL_RGB16UI,
rgb32i = c.GL_RGB32I,
rgb32ui = c.GL_RGB32UI,
rgba8i = c.GL_RGBA8I,
rgba8ui = c.GL_RGBA8UI,
rgba16i = c.GL_RGBA16I,
rgba16ui = c.GL_RGBA16UI,
rgba32i = c.GL_RGBA32I,
rgba32ui = c.GL_RGBA32UI,
};
pub fn textureStorage2D(
texture: Texture,
levels: usize,
internalformat: TextureInternalFormat,
width: usize,
height: usize,
) void {
c.glTextureStorage2D(
@enumToInt(texture),
@intCast(c.GLsizei, levels),
@enumToInt(internalformat),
@intCast(c.GLsizei, width),
@intCast(c.GLsizei, height),
);
checkError();
}
pub fn textureStorage3D(
texture: Texture,
levels: usize,
internalformat: TextureInternalFormat,
width: usize,
height: usize,
depth: usize,
) void {
c.glTextureStorage3D(
@enumToInt(texture),
@intCast(c.GLsizei, levels),
@enumToInt(internalformat),
@intCast(c.GLsizei, width),
@intCast(c.GLsizei, height),
@intCast(c.GLsizei, depth),
);
checkError();
}
pub const PixelFormat = enum(c.GLenum) {
red = c.GL_RED,
rg = c.GL_RG,
rgb = c.GL_RGB,
bgr = c.GL_BGR,
rgba = c.GL_RGBA,
bgra = c.GL_BGRA,
depth_component = c.GL_DEPTH_COMPONENT,
stencil_index = c.GL_STENCIL_INDEX,
};
pub const PixelType = enum(c.GLenum) {
unsigned_byte = c.GL_UNSIGNED_BYTE,
byte = c.GL_BYTE,
unsigned_short = c.GL_UNSIGNED_SHORT,
short = c.GL_SHORT,
unsigned_int = c.GL_UNSIGNED_INT,
int = c.GL_INT,
float = c.GL_FLOAT,
unsigned_byte_3_3_2 = c.GL_UNSIGNED_BYTE_3_3_2,
unsigned_byte_2_3_3_rev = c.GL_UNSIGNED_BYTE_2_3_3_REV,
unsigned_short_5_6_5 = c.GL_UNSIGNED_SHORT_5_6_5,
unsigned_short_5_6_5_rev = c.GL_UNSIGNED_SHORT_5_6_5_REV,
unsigned_short_4_4_4_4 = c.GL_UNSIGNED_SHORT_4_4_4_4,
unsigned_short_4_4_4_4_rev = c.GL_UNSIGNED_SHORT_4_4_4_4_REV,
unsigned_short_5_5_5_1 = c.GL_UNSIGNED_SHORT_5_5_5_1,
unsigned_short_1_5_5_5_rev = c.GL_UNSIGNED_SHORT_1_5_5_5_REV,
unsigned_int_8_8_8_8 = c.GL_UNSIGNED_INT_8_8_8_8,
unsigned_int_8_8_8_8_rev = c.GL_UNSIGNED_INT_8_8_8_8_REV,
unsigned_int_10_10_10_2 = c.GL_UNSIGNED_INT_10_10_10_2,
unsigned_int_2_10_10_10_rev = c.GL_UNSIGNED_INT_2_10_10_10_REV,
};
pub fn textureSubImage2D(
texture: Texture,
level: GLint,
xoffset: usize,
yoffset: usize,
width: usize,
height: usize,
pixel_format: GLenum,
pixel_type: GLenum,
data: [*]const u8,
) void {
unreachable;
checkError();
}
pub fn textureSubImage3D(
texture: Texture,
level: usize,
xoffset: usize,
yoffset: usize,
zoffset: usize,
width: usize,
height: usize,
depth: usize,
pixel_format: PixelFormat,
pixel_type: PixelType,
pixels: [*]const u8,
) void {
c.glTextureSubImage3D(
@enumToInt(texture),
@intCast(c.GLint, level),
@intCast(c.GLint, xoffset),
@intCast(c.GLint, yoffset),
@intCast(c.GLint, zoffset),
@intCast(c.GLsizei, width),
@intCast(c.GLsizei, height),
@intCast(c.GLsizei, depth),
@enumToInt(pixel_format),
@enumToInt(pixel_type),
pixels,
);
checkError();
}
pub const PixelStoreParameter = enum(c.GLenum) {
pack_swap_bytes = c.GL_PACK_SWAP_BYTES,
pack_lsb_first = c.GL_PACK_LSB_FIRST,
pack_row_length = c.GL_PACK_ROW_LENGTH,
pack_image_height = c.GL_PACK_IMAGE_HEIGHT,
pack_skip_pixels = c.GL_PACK_SKIP_PIXELS,
pack_skip_rows = c.GL_PACK_SKIP_ROWS,
pack_skip_images = c.GL_PACK_SKIP_IMAGES,
pack_alignment = c.GL_PACK_ALIGNMENT,
unpack_swap_bytes = c.GL_UNPACK_SWAP_BYTES,
unpack_lsb_first = c.GL_UNPACK_LSB_FIRST,
unpack_row_length = c.GL_UNPACK_ROW_LENGTH,
unpack_image_height = c.GL_UNPACK_IMAGE_HEIGHT,
unpack_skip_pixels = c.GL_UNPACK_SKIP_PIXELS,
unpack_skip_rows = c.GL_UNPACK_SKIP_ROWS,
unpack_skip_images = c.GL_UNPACK_SKIP_IMAGES,
unpack_alignment = c.GL_UNPACK_ALIGNMENT,
};
pub fn pixelStore(param: PixelStoreParameter, value: usize) void {
c.glPixelStorei(@enumToInt(param), @intCast(c.GLint, value));
checkError();
}
|
zgl.zig
|
const std = @import("std");
const assertOrPanic = std.debug.assertOrPanic;
extern fn run_c_tests() void;
export fn zig_panic() noreturn {
@panic("zig_panic called from C");
}
test "C importing Zig ABI Tests" {
run_c_tests();
}
extern fn c_u8(u8) void;
extern fn c_u16(u16) void;
extern fn c_u32(u32) void;
extern fn c_u64(u64) void;
extern fn c_i8(i8) void;
extern fn c_i16(i16) void;
extern fn c_i32(i32) void;
extern fn c_i64(i64) void;
test "C ABI integers" {
c_u8(0xff);
c_u16(0xfffe);
c_u32(0xfffffffd);
c_u64(0xfffffffffffffffc);
c_i8(-1);
c_i16(-2);
c_i32(-3);
c_i64(-4);
}
export fn zig_u8(x: u8) void {
assertOrPanic(x == 0xff);
}
export fn zig_u16(x: u16) void {
assertOrPanic(x == 0xfffe);
}
export fn zig_u32(x: u32) void {
assertOrPanic(x == 0xfffffffd);
}
export fn zig_u64(x: u64) void {
assertOrPanic(x == 0xfffffffffffffffc);
}
export fn zig_i8(x: i8) void {
assertOrPanic(x == -1);
}
export fn zig_i16(x: i16) void {
assertOrPanic(x == -2);
}
export fn zig_i32(x: i32) void {
assertOrPanic(x == -3);
}
export fn zig_i64(x: i64) void {
assertOrPanic(x == -4);
}
extern fn c_f32(f32) void;
extern fn c_f64(f64) void;
test "C ABI floats" {
c_f32(12.34);
c_f64(56.78);
}
export fn zig_f32(x: f32) void {
assertOrPanic(x == 12.34);
}
export fn zig_f64(x: f64) void {
assertOrPanic(x == 56.78);
}
extern fn c_ptr(*c_void) void;
test "C ABI pointer" {
c_ptr(@intToPtr(*c_void, 0xdeadbeef));
}
export fn zig_ptr(x: *c_void) void {
assertOrPanic(@ptrToInt(x) == 0xdeadbeef);
}
extern fn c_bool(bool) void;
test "C ABI bool" {
c_bool(true);
}
export fn zig_bool(x: bool) void {
assertOrPanic(x);
}
extern fn c_array([10]u8) void;
test "C ABI array" {
var array: [10]u8 = "1234567890";
c_array(array);
}
export fn zig_array(x: [10]u8) void {
assertOrPanic(std.mem.eql(u8, x, "1234567890"));
}
const BigStruct = extern struct.{
a: u64,
b: u64,
c: u64,
d: u64,
e: u8,
};
extern fn c_big_struct(BigStruct) void;
test "C ABI big struct" {
var s = BigStruct.{
.a = 1,
.b = 2,
.c = 3,
.d = 4,
.e = 5,
};
c_big_struct(s);
}
export fn zig_big_struct(x: BigStruct) void {
assertOrPanic(x.a == 1);
assertOrPanic(x.b == 2);
assertOrPanic(x.c == 3);
assertOrPanic(x.d == 4);
assertOrPanic(x.e == 5);
}
const BigUnion = extern union.{
a: BigStruct,
};
extern fn c_big_union(BigUnion) void;
test "C ABI big union" {
var x = BigUnion.{
.a = BigStruct.{
.a = 1,
.b = 2,
.c = 3,
.d = 4,
.e = 5,
},
};
c_big_union(x);
}
export fn zig_big_union(x: BigUnion) void {
assertOrPanic(x.a.a == 1);
assertOrPanic(x.a.b == 2);
assertOrPanic(x.a.c == 3);
assertOrPanic(x.a.d == 4);
assertOrPanic(x.a.e == 5);
}
const SmallStructInts = extern struct.{
a: u8,
b: u8,
c: u8,
d: u8,
};
extern fn c_small_struct_ints(SmallStructInts) void;
test "C ABI small struct of ints" {
var s = SmallStructInts.{
.a = 1,
.b = 2,
.c = 3,
.d = 4,
};
c_small_struct_ints(s);
}
export fn zig_small_struct_ints(x: SmallStructInts) void {
assertOrPanic(x.a == 1);
assertOrPanic(x.b == 2);
assertOrPanic(x.c == 3);
assertOrPanic(x.d == 4);
}
const SplitStructInt = extern struct.{
a: u64,
b: u8,
c: u32,
};
extern fn c_split_struct_ints(SplitStructInt) void;
test "C ABI split struct of ints" {
var s = SplitStructInt.{
.a = 1234,
.b = 100,
.c = 1337,
};
c_split_struct_ints(s);
}
export fn zig_split_struct_ints(x: SplitStructInt) void {
assertOrPanic(x.a == 1234);
assertOrPanic(x.b == 100);
assertOrPanic(x.c == 1337);
}
extern fn c_big_struct_both(BigStruct) BigStruct;
test "C ABI sret and byval together" {
var s = BigStruct.{
.a = 1,
.b = 2,
.c = 3,
.d = 4,
.e = 5,
};
var y = c_big_struct_both(s);
assertOrPanic(y.a == 10);
assertOrPanic(y.b == 11);
assertOrPanic(y.c == 12);
assertOrPanic(y.d == 13);
assertOrPanic(y.e == 14);
}
export fn zig_big_struct_both(x: BigStruct) BigStruct {
assertOrPanic(x.a == 30);
assertOrPanic(x.b == 31);
assertOrPanic(x.c == 32);
assertOrPanic(x.d == 33);
assertOrPanic(x.e == 34);
var s = BigStruct.{
.a = 20,
.b = 21,
.c = 22,
.d = 23,
.e = 24,
};
return s;
}
|
test/stage1/c_abi/main.zig
|
const print = @import("std").debug.print;
const TripError = error{ Unreachable, EatenByAGrue };
const Place = struct {
name: []const u8,
paths: []const Path = undefined,
};
var a = Place{ .name = "Archer's Point" };
var b = Place{ .name = "Bridge" };
var c = Place{ .name = "Cottage" };
var d = Place{ .name = "Dogwood Grove" };
var e = Place{ .name = "East Pond" };
var f = Place{ .name = "Fox Pond" };
// Remember how we didn't have to declare the numeric type of the
// place_count because it is only used at compile time? That
// probably makes a lot more sense now. :-)
const place_count = 6;
const Path = struct {
from: *const Place,
to: *const Place,
dist: u8,
};
// Okay, so as you may recall, we had to create each Path struct
// by hand and each one took 5 lines of code to define:
//
// Path{
// .from = &a, // from: Archer's Point
// .to = &b, // to: Bridge
// .dist = 2,
// },
//
// Well, armed with the knowledge that we can run code at compile
// time, we can perhaps shorten this a bit with a simple function
// instead.
//
// Please fill in the body of this function!
fn makePath(from: *Place, to: *Place, dist: u8) Path {
return Path{ .from = from, .to = to, .dist = dist };
}
// Using our new function, these path definitions take up considerably less
// space in our program now!
const a_paths = [_]Path{makePath(&a, &b, 2)};
const b_paths = [_]Path{ makePath(&b, &a, 2), makePath(&b, &d, 1) };
const c_paths = [_]Path{ makePath(&c, &d, 3), makePath(&c, &e, 2) };
const d_paths = [_]Path{ makePath(&d, &b, 1), makePath(&d, &c, 3), makePath(&d, &f, 7) };
const e_paths = [_]Path{ makePath(&e, &c, 2), makePath(&e, &f, 1) };
const f_paths = [_]Path{makePath(&f, &d, 7)};
//
// But is it more readable? That could be argued either way.
//
// We've seen that it is possible to parse strings at compile
// time, so the sky's really the limit on how fancy we could get
// with this.
//
// For example, we could create our own "path language" and
// create Paths from that. Something like this, perhaps:
//
// a -> (b[2])
// b -> (a[2] d[1])
// c -> (d[3] e[2])
// ...
//
// Feel free to implement something like that as a SUPER BONUS EXERCISE!
const TripItem = union(enum) {
place: *const Place,
path: *const Path,
fn printMe(self: TripItem) void {
switch (self) {
.place => |p| print("{s}", .{p.name}),
.path => |p| print("--{}->", .{p.dist}),
}
}
};
const NotebookEntry = struct {
place: *const Place,
coming_from: ?*const Place,
via_path: ?*const Path,
dist_to_reach: u16,
};
const HermitsNotebook = struct {
entries: [place_count]?NotebookEntry = .{null} ** place_count,
next_entry: u8 = 0,
end_of_entries: u8 = 0,
fn getEntry(self: *HermitsNotebook, place: *const Place) ?*NotebookEntry {
for (self.entries) |*entry, i| {
if (i >= self.end_of_entries) break;
if (place == entry.*.?.place) return &entry.*.?;
}
return null;
}
fn checkNote(self: *HermitsNotebook, note: NotebookEntry) void {
var existing_entry = self.getEntry(note.place);
if (existing_entry == null) {
self.entries[self.end_of_entries] = note;
self.end_of_entries += 1;
} else if (note.dist_to_reach < existing_entry.?.dist_to_reach) {
existing_entry.?.* = note;
}
}
fn hasNextEntry(self: *HermitsNotebook) bool {
return self.next_entry < self.end_of_entries;
}
fn getNextEntry(self: *HermitsNotebook) *const NotebookEntry {
defer self.next_entry += 1;
return &self.entries[self.next_entry].?;
}
fn getTripTo(self: *HermitsNotebook, trip: []?TripItem, dest: *Place) TripError!void {
const destination_entry = self.getEntry(dest);
if (destination_entry == null) {
return TripError.Unreachable;
}
var current_entry = destination_entry.?;
var i: u8 = 0;
while (true) : (i += 2) {
trip[i] = TripItem{ .place = current_entry.place };
if (current_entry.coming_from == null) break;
trip[i + 1] = TripItem{ .path = current_entry.via_path.? };
const previous_entry = self.getEntry(current_entry.coming_from.?);
if (previous_entry == null) return TripError.EatenByAGrue;
current_entry = previous_entry.?;
}
}
};
pub fn main() void {
const start = &a; // Archer's Point
const destination = &f; // Fox Pond
// TODO: can we neaten this up????
a.paths = a_paths[0..];
b.paths = b_paths[0..];
c.paths = c_paths[0..];
d.paths = d_paths[0..];
e.paths = e_paths[0..];
f.paths = f_paths[0..];
var notebook = HermitsNotebook{};
var working_note = NotebookEntry{
.place = start,
.coming_from = null,
.via_path = null,
.dist_to_reach = 0,
};
notebook.checkNote(working_note);
while (notebook.hasNextEntry()) {
var place_entry = notebook.getNextEntry();
for (place_entry.place.paths) |*path| {
working_note = NotebookEntry{
.place = path.to,
.coming_from = place_entry.place,
.via_path = path,
.dist_to_reach = place_entry.dist_to_reach + path.dist,
};
notebook.checkNote(working_note);
}
}
var trip = [_]?TripItem{null} ** (place_count * 2);
notebook.getTripTo(trip[0..], destination) catch |err| {
print("Oh no! {}\n", .{err});
return;
};
printTrip(trip[0..]);
}
fn printTrip(trip: []?TripItem) void {
var i: u8 = @intCast(u8, trip.len);
while (i > 0) {
i -= 1;
if (trip[i] == null) continue;
trip[i].?.printMe();
}
print("\n", .{});
}
|
exercises/075_quiz8.zig
|
const assert = @import("std").debug.assert;
const mem = @import("std").mem;
test "int to ptr cast" {
const x = usize(13);
const y = @intToPtr(&u8, x);
const z = @ptrToInt(y);
assert(z == 13);
}
test "integer literal to pointer cast" {
const vga_mem = @intToPtr(&u16, 0xB8000);
assert(@ptrToInt(vga_mem) == 0xB8000);
}
test "pointer reinterpret const float to int" {
const float: f64 = 5.99999999999994648725e-01;
const float_ptr = &float;
const int_ptr = @ptrCast(&const i32, float_ptr);
const int_val = *int_ptr;
assert(int_val == 858993411);
}
test "implicitly cast a pointer to a const pointer of it" {
var x: i32 = 1;
const xp = &x;
funcWithConstPtrPtr(xp);
assert(x == 2);
}
fn funcWithConstPtrPtr(x: &const &i32) void {
**x += 1;
}
test "implicitly cast a container to a const pointer of it" {
const z = Struct(void) { .x = void{} };
assert(0 == @sizeOf(@typeOf(z)));
assert(void{} == Struct(void).pointer(z).x);
assert(void{} == Struct(void).pointer(&z).x);
assert(void{} == Struct(void).maybePointer(z).x);
assert(void{} == Struct(void).maybePointer(&z).x);
assert(void{} == Struct(void).maybePointer(null).x);
const s = Struct(u8) { .x = 42 };
assert(0 != @sizeOf(@typeOf(s)));
assert(42 == Struct(u8).pointer(s).x);
assert(42 == Struct(u8).pointer(&s).x);
assert(42 == Struct(u8).maybePointer(s).x);
assert(42 == Struct(u8).maybePointer(&s).x);
assert(0 == Struct(u8).maybePointer(null).x);
const u = Union { .x = 42 };
assert(42 == Union.pointer(u).x);
assert(42 == Union.pointer(&u).x);
assert(42 == Union.maybePointer(u).x);
assert(42 == Union.maybePointer(&u).x);
assert(0 == Union.maybePointer(null).x);
const e = Enum.Some;
assert(Enum.Some == Enum.pointer(e));
assert(Enum.Some == Enum.pointer(&e));
assert(Enum.Some == Enum.maybePointer(e));
assert(Enum.Some == Enum.maybePointer(&e));
assert(Enum.None == Enum.maybePointer(null));
}
fn Struct(comptime T: type) type {
return struct {
const Self = this;
x: T,
fn pointer(self: &const Self) Self {
return *self;
}
fn maybePointer(self: ?&const Self) Self {
const none = Self { .x = if (T == void) void{} else 0 };
return *(self ?? &none);
}
};
}
const Union = union {
x: u8,
fn pointer(self: &const Union) Union {
return *self;
}
fn maybePointer(self: ?&const Union) Union {
const none = Union { .x = 0 };
return *(self ?? &none);
}
};
const Enum = enum {
None,
Some,
fn pointer(self: &const Enum) Enum {
return *self;
}
fn maybePointer(self: ?&const Enum) Enum {
return *(self ?? &Enum.None);
}
};
test "implicitly cast indirect pointer to maybe-indirect pointer" {
const S = struct {
const Self = this;
x: u8,
fn constConst(p: &const &const Self) u8 {
return (*p).x;
}
fn maybeConstConst(p: ?&const &const Self) u8 {
return (*??p).x;
}
fn constConstConst(p: &const &const &const Self) u8 {
return (**p).x;
}
fn maybeConstConstConst(p: ?&const &const &const Self) u8 {
return (**??p).x;
}
};
const s = S { .x = 42 };
const p = &s;
const q = &p;
const r = &q;
assert(42 == S.constConst(p));
assert(42 == S.constConst(q));
assert(42 == S.maybeConstConst(p));
assert(42 == S.maybeConstConst(q));
assert(42 == S.constConstConst(q));
assert(42 == S.constConstConst(r));
assert(42 == S.maybeConstConstConst(q));
assert(42 == S.maybeConstConstConst(r));
}
test "explicit cast from integer to error type" {
testCastIntToErr(error.ItBroke);
comptime testCastIntToErr(error.ItBroke);
}
fn testCastIntToErr(err: error) void {
const x = usize(err);
const y = error(x);
assert(error.ItBroke == y);
}
test "peer resolve arrays of different size to const slice" {
assert(mem.eql(u8, boolToStr(true), "true"));
assert(mem.eql(u8, boolToStr(false), "false"));
comptime assert(mem.eql(u8, boolToStr(true), "true"));
comptime assert(mem.eql(u8, boolToStr(false), "false"));
}
fn boolToStr(b: bool) []const u8 {
return if (b) "true" else "false";
}
test "peer resolve array and const slice" {
testPeerResolveArrayConstSlice(true);
comptime testPeerResolveArrayConstSlice(true);
}
fn testPeerResolveArrayConstSlice(b: bool) void {
const value1 = if (b) "aoeu" else ([]const u8)("zz");
const value2 = if (b) ([]const u8)("zz") else "aoeu";
assert(mem.eql(u8, value1, "aoeu"));
assert(mem.eql(u8, value2, "zz"));
}
test "integer literal to &const int" {
const x: &const i32 = 3;
assert(*x == 3);
}
test "string literal to &const []const u8" {
const x: &const []const u8 = "hello";
assert(mem.eql(u8, *x, "hello"));
}
test "implicitly cast from T to error!?T" {
castToMaybeTypeError(1);
comptime castToMaybeTypeError(1);
}
const A = struct {
a: i32,
};
fn castToMaybeTypeError(z: i32) void {
const x = i32(1);
const y: error!?i32 = x;
assert(??(try y) == 1);
const f = z;
const g: error!?i32 = f;
const a = A{ .a = z };
const b: error!?A = a;
assert((??(b catch unreachable)).a == 1);
}
test "implicitly cast from int to error!?T" {
implicitIntLitToMaybe();
comptime implicitIntLitToMaybe();
}
fn implicitIntLitToMaybe() void {
const f: ?i32 = 1;
const g: error!?i32 = 1;
}
test "return null from fn() error!?&T" {
const a = returnNullFromMaybeTypeErrorRef();
const b = returnNullLitFromMaybeTypeErrorRef();
assert((try a) == null and (try b) == null);
}
fn returnNullFromMaybeTypeErrorRef() error!?&A {
const a: ?&A = null;
return a;
}
fn returnNullLitFromMaybeTypeErrorRef() error!?&A {
return null;
}
test "peer type resolution: ?T and T" {
assert(??peerTypeTAndMaybeT(true, false) == 0);
assert(??peerTypeTAndMaybeT(false, false) == 3);
comptime {
assert(??peerTypeTAndMaybeT(true, false) == 0);
assert(??peerTypeTAndMaybeT(false, false) == 3);
}
}
fn peerTypeTAndMaybeT(c: bool, b: bool) ?usize {
if (c) {
return if (b) null else usize(0);
}
return usize(3);
}
test "peer type resolution: [0]u8 and []const u8" {
assert(peerTypeEmptyArrayAndSlice(true, "hi").len == 0);
assert(peerTypeEmptyArrayAndSlice(false, "hi").len == 1);
comptime {
assert(peerTypeEmptyArrayAndSlice(true, "hi").len == 0);
assert(peerTypeEmptyArrayAndSlice(false, "hi").len == 1);
}
}
fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 {
if (a) {
return []const u8 {};
}
return slice[0..1];
}
test "implicitly cast from [N]T to ?[]const T" {
assert(mem.eql(u8, ??castToMaybeSlice(), "hi"));
comptime assert(mem.eql(u8, ??castToMaybeSlice(), "hi"));
}
fn castToMaybeSlice() ?[]const u8 {
return "hi";
}
test "implicitly cast from [0]T to error![]T" {
testCastZeroArrayToErrSliceMut();
comptime testCastZeroArrayToErrSliceMut();
}
fn testCastZeroArrayToErrSliceMut() void {
assert((gimmeErrOrSlice() catch unreachable).len == 0);
}
fn gimmeErrOrSlice() error![]u8 {
return []u8{};
}
test "peer type resolution: [0]u8, []const u8, and error![]u8" {
{
var data = "hi";
const slice = data[0..];
assert((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0);
assert((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1);
}
comptime {
var data = "hi";
const slice = data[0..];
assert((try peerTypeEmptyArrayAndSliceAndError(true, slice)).len == 0);
assert((try peerTypeEmptyArrayAndSliceAndError(false, slice)).len == 1);
}
}
fn peerTypeEmptyArrayAndSliceAndError(a: bool, slice: []u8) error![]u8 {
if (a) {
return []u8{};
}
return slice[0..1];
}
test "resolve undefined with integer" {
testResolveUndefWithInt(true, 1234);
comptime testResolveUndefWithInt(true, 1234);
}
fn testResolveUndefWithInt(b: bool, x: i32) void {
const value = if (b) x else undefined;
if (b) {
assert(value == x);
}
}
test "implicit cast from &const [N]T to []const T" {
testCastConstArrayRefToConstSlice();
comptime testCastConstArrayRefToConstSlice();
}
fn testCastConstArrayRefToConstSlice() void {
const blah = "aoeu";
const const_array_ref = &blah;
assert(@typeOf(const_array_ref) == &const [4]u8);
const slice: []const u8 = const_array_ref;
assert(mem.eql(u8, slice, "aoeu"));
}
test "var args implicitly casts by value arg to const ref" {
foo("hello");
}
fn foo(args: ...) void {
assert(@typeOf(args[0]) == &const [5]u8);
}
test "peer type resolution: error and [N]T" {
// TODO: implicit error!T to error!U where T can implicitly cast to U
//assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK"));
//comptime assert(mem.eql(u8, try testPeerErrorAndArray(0), "OK"));
assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK"));
comptime assert(mem.eql(u8, try testPeerErrorAndArray2(1), "OKK"));
}
//fn testPeerErrorAndArray(x: u8) error![]const u8 {
// return switch (x) {
// 0x00 => "OK",
// else => error.BadValue,
// };
//}
fn testPeerErrorAndArray2(x: u8) error![]const u8 {
return switch (x) {
0x00 => "OK",
0x01 => "OKK",
else => error.BadValue,
};
}
test "explicit cast float number literal to integer if no fraction component" {
const x = i32(1e4);
assert(x == 10000);
const y = i32(f32(1e4));
assert(y == 10000);
}
test "cast u128 to f128 and back" {
comptime testCast128();
testCast128();
}
fn testCast128() void {
assert(cast128Int(cast128Float(0x7fff0000000000000000000000000000)) == 0x7fff0000000000000000000000000000);
}
fn cast128Int(x: f128) u128 {
return @bitCast(u128, x);
}
fn cast128Float(x: u128) f128 {
return @bitCast(f128, x);
}
test "const slice widen cast" {
const bytes align(4) = []u8{0x12, 0x12, 0x12, 0x12};
const u32_value = ([]const u32)(bytes[0..])[0];
assert(u32_value == 0x12121212);
assert(@bitCast(u32, bytes) == 0x12121212);
}
|
test/cases/cast.zig
|
const clap = @import("../clap.zig");
const std = @import("std");
const testing = std.testing;
const heap = std.heap;
const mem = std.mem;
const debug = std.debug;
pub fn ComptimeClap(comptime Id: type, comptime params: []const clap.Param(Id)) type {
var flags: usize = 0;
var options: usize = 0;
var converted_params: []const clap.Param(usize) = &[_]clap.Param(usize){};
for (params) |param| {
var index: usize = 0;
if (param.names.long != null or param.names.short != null) {
const ptr = if (param.takes_value) &options else &flags;
index = ptr.*;
ptr.* += 1;
}
const converted = clap.Param(usize){
.id = index,
.names = param.names,
.takes_value = param.takes_value,
};
converted_params = converted_params ++ [_]clap.Param(usize){converted};
}
return struct {
options: [options]?[]const u8,
flags: [flags]bool,
pos: []const []const u8,
allocator: *mem.Allocator,
pub fn parse(allocator: *mem.Allocator, comptime ArgIter: type, iter: *ArgIter) !@This() {
var pos = std.ArrayList([]const u8).init(allocator);
var res = @This(){
.options = [_]?[]const u8{null} ** options,
.flags = [_]bool{false} ** flags,
.pos = undefined,
.allocator = allocator,
};
var stream = clap.StreamingClap(usize, ArgIter){
.params = converted_params,
.iter = iter,
};
while (try stream.next()) |arg| {
const param = arg.param;
if (param.names.long == null and param.names.short == null) {
try pos.append(arg.value.?);
} else if (param.takes_value) {
// If we don't have any optional parameters, then this code should
// never be reached.
debug.assert(res.options.len != 0);
// Hack: Utilize Zigs lazy analyzis to avoid a compiler error
if (res.options.len != 0)
res.options[param.id] = arg.value.?;
} else {
debug.assert(res.flags.len != 0);
if (res.flags.len != 0)
res.flags[param.id] = true;
}
}
res.pos = pos.toOwnedSlice();
return res;
}
pub fn deinit(parser: *@This()) void {
parser.allocator.free(parser.pos);
parser.* = undefined;
}
pub fn flag(parser: @This(), comptime name: []const u8) bool {
const param = comptime findParam(name);
if (param.takes_value)
@compileError(name ++ " is an option and not a flag.");
return parser.flags[param.id];
}
pub fn option(parser: @This(), comptime name: []const u8) ?[]const u8 {
const param = comptime findParam(name);
if (!param.takes_value)
@compileError(name ++ " is a flag and not an option.");
return parser.options[param.id];
}
pub fn positionals(parser: @This()) []const []const u8 {
return parser.pos;
}
fn findParam(comptime name: []const u8) clap.Param(usize) {
comptime {
for (converted_params) |param| {
if (param.names.short) |s| {
if (mem.eql(u8, name, "-" ++ [_]u8{s}))
return param;
}
if (param.names.long) |l| {
if (mem.eql(u8, name, "--" ++ l))
return param;
}
}
@compileError(name ++ " is not a parameter.");
}
}
};
}
test "clap.comptime.ComptimeClap" {
const Clap = ComptimeClap(clap.Help, comptime &[_]clap.Param(clap.Help){
clap.parseParam("-a, --aa ") catch unreachable,
clap.parseParam("-b, --bb ") catch unreachable,
clap.parseParam("-c, --cc <V>") catch unreachable,
clap.Param(clap.Help){
.takes_value = true,
},
});
var buf: [1024]u8 = undefined;
var fb_allocator = heap.FixedBufferAllocator.init(buf[0..]);
var iter = clap.args.SliceIterator{
.args = &[_][]const u8{
"-a", "-c", "0", "something",
},
};
var args = try Clap.parse(&fb_allocator.allocator, clap.args.SliceIterator, &iter);
defer args.deinit();
testing.expect(args.flag("-a"));
testing.expect(args.flag("--aa"));
testing.expect(!args.flag("-b"));
testing.expect(!args.flag("--bb"));
testing.expectEqualSlices(u8, "0", args.option("-c").?);
testing.expectEqualSlices(u8, "0", args.option("--cc").?);
testing.expectEqual(@as(usize, 1), args.positionals().len);
testing.expectEqualSlices(u8, "something", args.positionals()[0]);
}
|
clap/comptime.zig
|
const Builder = @import("std").build.Builder;
pub fn build(b: *Builder) void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("game", "src/main.zig");
const git_sub_cmd = [_][]const u8{ "git", "submodule", "update", "--init", "--recursive" };
const fetch_subs = b.addSystemCommand(&git_sub_cmd);
exe.addIncludeDir("src");
exe.linkLibC();
exe.linkSystemLibrary("c++");
exe.linkSystemLibrary("X11");
exe.linkSystemLibrary("SDL2");
exe.linkSystemLibrary("GL");
const cxx_options = [_][]const u8{
"-fno-strict-aliasing",
"-fno-exceptions",
"-fno-rtti",
"-ffast-math",
};
// Define to enable some debug prints in BGFX
//exe.defineCMacro("BGFX_CONFIG_DEBUG=1");
// bx
const bx = "submodules/bx/";
exe.addIncludeDir(bx ++ "include/");
exe.addIncludeDir(bx ++ "3rdparty/");
exe.addCSourceFile(bx ++ "src/amalgamated.cpp", &cxx_options);
// bimg
const bimg = "submodules/bimg/";
exe.addIncludeDir(bimg ++ "include/");
exe.addIncludeDir(bimg ++ "3rdparty/");
exe.addIncludeDir(bimg ++ "3rdparty/astc-codec/");
exe.addIncludeDir(bimg ++ "3rdparty/astc-codec/include/");
exe.addCSourceFile(bimg ++ "src/image.cpp", &cxx_options);
exe.addCSourceFile(bimg ++ "src/image_gnf.cpp", &cxx_options);
// FIXME: Glob?
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/astc_file.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/codec.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/endpoint_codec.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/footprint.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/integer_sequence_codec.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/intermediate_astc_block.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/logical_astc_block.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/partition.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/physical_astc_block.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/quantization.cc", &cxx_options);
exe.addCSourceFile(bimg ++ "3rdparty/astc-codec/src/decoder/weight_infill.cc", &cxx_options);
// bgfx
const bgfx = "submodules/bgfx/";
exe.addIncludeDir(bgfx ++ "include/");
exe.addIncludeDir(bgfx ++ "3rdparty/");
exe.addIncludeDir(bgfx ++ "3rdparty/dxsdk/include/");
exe.addIncludeDir(bgfx ++ "3rdparty/khronos/");
exe.addIncludeDir(bgfx ++ "src/");
exe.addCSourceFile(bgfx ++ "src/amalgamated.cpp", &cxx_options);
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
const fetch_step = b.step("fetch", "Fetch submodules");
fetch_step.dependOn(&fetch_subs.step);
}
|
build.zig
|
const std = @import("std");
const process = std.process;
const Allocator = std.mem.Allocator;
const print = std.debug.print;
const mem = std.mem;
fn interpret(stdin: anytype, stdout: anytype, code: []const u8) !void {
var tape = [_]u8{0} ** 30_000;
var pdata: u32 = 0;
var pinst: u32 = 0;
while (pinst < code.len) {
var inst = code[pinst];
switch (inst) {
'>' => {
if (pdata < tape.len - 1) pdata += 1;
},
'<' => {
if (pdata > 0) pdata -= 1;
},
'+' => {
if (tape[pdata] < @bitSizeOf(u8) - 1) tape[pdata] += 1;
},
'-' => {
if (tape[pdata] > 0) tape[pdata] -= 1;
},
'.' => {
try stdout.writeByte(tape[pdata]);
},
',' => {
_ = try stdout.write("Input>");
tape[pdata] = stdin.readByte() catch tape[pdata];
},
'[' => {
if (tape[pdata] == 0) {
var bracket_stack: u32 = 0;
while (pinst < code.len) {
pinst += 1;
if (code[pinst] == '[') {
bracket_stack += 1;
} else if (code[pinst] == ']' and bracket_stack > 0) {
bracket_stack -= 1;
} else if (code[pinst] == ']' and bracket_stack == 0) {
pinst += 1;
break;
}
}
}
},
']' => {
if (tape[pdata] > 0) {
var bracket_stack: u32 = 0;
while (pinst > 0) {
pinst -= 1;
if (code[pinst] == ']') {
bracket_stack += 1;
} else if (code[pinst] == '[' and bracket_stack > 0) {
bracket_stack -= 1;
} else if (code[pinst] == '[' and bracket_stack == 0) {
break;
}
}
}
},
else => {},
}
pinst += 1;
}
}
fn readLine(stdin: anytype, buffer: []u8) []u8 {
return stdin.readUntilDelimiterOrEof(buffer, '\n') catch buffer orelse buffer;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer gpa.deinit();
var alloc = &gpa.allocator;
const args = try process.argsAlloc(alloc);
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
if (args.len > 1) {
try interpret(stdin, stdout, args[1]);
} else {
while (true) {
try stdout.writeByte('>');
var buffer: [1024]u8 = undefined;
const data = readLine(stdin, buffer[0..]);
if (data.len == 0) continue;
if (mem.eql(u8, data, "quit")) {
break;
} else {
try interpret(stdin, stdout, data);
}
try stdout.writeByte('\n');
}
}
}
|
bf.zig
|
const std = @import("std");
const mem = std.mem;
const stdin = std.io.getStdIn();
const stdout = std.io.getStdOut().writer();
const exit = std.process.exit;
const Error = error{
CommandFailed,
UnknownCommand,
EmptyCommand,
};
// split arguments by white space
fn getArgs(allocator: mem.Allocator, cmd: []const u8) !?[]const []const u8 {
if (cmd.len == 0) {
return null;
}
// convert iterator to an array of strings
var args = std.ArrayList([]const u8).init(allocator);
defer args.deinit();
var splits = mem.split(u8, cmd, " ");
while (splits.next()) |string| {
try args.append(string);
}
return args.toOwnedSlice();
}
// evulate commands
fn evaluateCmd(args: []const []const u8) !void {
if (args.len == 0) {
return Error.EmptyCommand;
}
// `clear` and `exit` are builtin commands
else if (mem.eql(u8, args[0], "clear")) {
try stdout.writeAll("\x1b[1;1H\x1b[2J");
} else if (mem.eql(u8, args[0], "exit")) {
exit(0);
} else {
// execute command
const res = std.ChildProcess.exec(.{ .allocator = std.heap.page_allocator, .argv = args }) catch |err| {
switch (err) {
error.FileNotFound => return Error.UnknownCommand,
else => {
try stdout.writeAll(@errorName(err));
return Error.CommandFailed;
},
}
};
// write output
try stdout.writeAll(res.stdout);
}
}
pub fn main() !void {
var cmd_buf: [1024]u8 = undefined;
while (true) {
try stdout.writeAll("\x1b[92;1m$ \x1b[0m"); // $
if (stdin.reader().readUntilDelimiterOrEof(&cmd_buf, '\n') catch |err| {
try stdout.print("Unable to parse command: {s}\n", .{@errorName(err)});
continue;
}) |line| {
const actual_line = mem.trim(u8, line, "\r\n ");
if (try getArgs(std.testing.allocator, actual_line)) |args| {
evaluateCmd(args) catch |err| {
if (err == Error.UnknownCommand) {
stdout.print("Unknown Command `{s}`\n", .{actual_line}) catch {};
} else {
return err;
}
};
}
}
}
}
|
code/shell.zig
|
const base = @import("base.zig");
const letter = @import("letter.zig");
const tables = @import("tables.zig");
const unicode = @import("index.zig");
const t = @import("../testing/index.zig");
const warn = @import("std").debug.warn;
const notletterTest = []u32{
0x20,
0x35,
0x375,
0x619,
0x700,
0x1885,
0xfffe,
0x1ffff,
0x10ffff,
};
const upper_test = []u32{
0x41,
0xc0,
0xd8,
0x100,
0x139,
0x14a,
0x178,
0x181,
0x376,
0x3cf,
0x13bd,
0x1f2a,
0x2102,
0x2c00,
0x2c10,
0x2c20,
0xa650,
0xa722,
0xff3a,
0x10400,
0x1d400,
0x1d7ca,
};
const notupperTest = []u32{
0x40,
0x5b,
0x61,
0x185,
0x1b0,
0x377,
0x387,
0x2150,
0xab7d,
0xffff,
0x10000,
};
test "isUpper" {
for (upper_test) |r, i| {
if (!unicode.isUpper(r)) {
try t.terrorf("\nexpected {} to be upper i={}\n", r, i);
}
}
for (notupperTest) |r, i| {
if (unicode.isUpper(r)) {
try t.terrorf("\nexpected {} not to be upper i={}\n", r, i);
}
}
for (notletterTest) |r, i| {
if (unicode.isUpper(r)) {
try t.terrorf("\nexpected {} not to be upper i={}\n", r, i);
}
}
}
const caseT = struct{
case: base.Case,
in: u32,
out: u32,
fn init(case: base.Case, in: u32, out: u32) caseT {
return caseT{ .case = case, .in = in, .out = out };
}
};
const case_test = []caseT{
// ASCII (special-cased so test carefully)
caseT.init(base.Case.Upper, '\n', '\n'),
caseT.init(base.Case.Upper, 'a', 'A'),
caseT.init(base.Case.Upper, 'A', 'A'),
caseT.init(base.Case.Upper, '7', '7'),
caseT.init(base.Case.Lower, '\n', '\n'),
caseT.init(base.Case.Lower, 'a', 'a'),
caseT.init(base.Case.Lower, 'A', 'a'),
caseT.init(base.Case.Lower, '7', '7'),
caseT.init(base.Case.Title, '\n', '\n'),
caseT.init(base.Case.Title, 'a', 'A'),
caseT.init(base.Case.Title, 'A', 'A'),
caseT.init(base.Case.Title, '7', '7'),
// Latin-1: easy to read the tests!
caseT.init(base.Case.Upper, 0x80, 0x80),
// caseT.init(base.Case.Upper, 'Å', 'Å'),
// caseT.init(base.Case.Upper, 'å', 'Å'),
caseT.init(base.Case.Lower, 0x80, 0x80),
// caseT.init(base.Case.Lower, 'Å', 'å'),
// caseT.init(base.Case.Lower, 'å', 'å'),
caseT.init(base.Case.Title, 0x80, 0x80),
// caseT.init(base.Case.Title, 'Å', 'Å'),
// caseT.init(base.Case.Title, 'å', 'Å'),
// 0131;LATIN SMALL LETTER DOTLESS I;Ll;0;L;;;;;N;;;0049;;0049
caseT.init(base.Case.Upper, 0x0131, 'I'),
caseT.init(base.Case.Lower, 0x0131, 0x0131),
caseT.init(base.Case.Title, 0x0131, 'I'),
// 0133;LATIN SMALL LIGATURE IJ;Ll;0;L;<compat> 0069 006A;;;;N;LATIN SMALL LETTER I J;;0132;;0132
caseT.init(base.Case.Upper, 0x0133, 0x0132),
caseT.init(base.Case.Lower, 0x0133, 0x0133),
caseT.init(base.Case.Title, 0x0133, 0x0132),
// 212A;KELVIN SIGN;Lu;0;L;004B;;;;N;DEGREES KELVIN;;;006B;
caseT.init(base.Case.Upper, 0x212A, 0x212A),
caseT.init(base.Case.Lower, 0x212A, 'k'),
caseT.init(base.Case.Title, 0x212A, 0x212A),
// From an UpperLower sequence
// A640;CYRILLIC CAPITAL LETTER ZEMLYA;Lu;0;L;;;;;N;;;;A641;
caseT.init(base.Case.Upper, 0xA640, 0xA640),
caseT.init(base.Case.Lower, 0xA640, 0xA641),
caseT.init(base.Case.Title, 0xA640, 0xA640),
// A641;CYRILLIC SMALL LETTER ZEMLYA;Ll;0;L;;;;;N;;;A640;;A640
caseT.init(base.Case.Upper, 0xA641, 0xA640),
caseT.init(base.Case.Lower, 0xA641, 0xA641),
caseT.init(base.Case.Title, 0xA641, 0xA640),
// A64E;CYRILLIC CAPITAL LETTER NEUTRAL YER;Lu;0;L;;;;;N;;;;A64F;
caseT.init(base.Case.Upper, 0xA64E, 0xA64E),
caseT.init(base.Case.Lower, 0xA64E, 0xA64F),
caseT.init(base.Case.Title, 0xA64E, 0xA64E),
// A65F;CYRILLIC SMALL LETTER YN;Ll;0;L;;;;;N;;;A65E;;A65E
caseT.init(base.Case.Upper, 0xA65F, 0xA65E),
caseT.init(base.Case.Lower, 0xA65F, 0xA65F),
caseT.init(base.Case.Title, 0xA65F, 0xA65E),
// From another UpperLower sequence
// 0139;LATIN CAPITAL LETTER L WITH ACUTE;Lu;0;L;004C 0301;;;;N;LATIN CAPITAL LETTER L ACUTE;;;013A;
caseT.init(base.Case.Upper, 0x0139, 0x0139),
caseT.init(base.Case.Lower, 0x0139, 0x013A),
caseT.init(base.Case.Title, 0x0139, 0x0139),
// 013F;LATIN CAPITAL LETTER L WITH MIDDLE DOT;Lu;0;L;<compat> 004C 00B7;;;;N;;;;0140;
caseT.init(base.Case.Upper, 0x013f, 0x013f),
caseT.init(base.Case.Lower, 0x013f, 0x0140),
caseT.init(base.Case.Title, 0x013f, 0x013f),
// 0148;LATIN SMALL LETTER N WITH CARON;Ll;0;L;006E 030C;;;;N;LATIN SMALL LETTER N HACEK;;0147;;0147
caseT.init(base.Case.Upper, 0x0148, 0x0147),
caseT.init(base.Case.Lower, 0x0148, 0x0148),
caseT.init(base.Case.Title, 0x0148, 0x0147),
// base.Case.Lower lower than base.Case.Upper.
// AB78;CHEROKEE SMALL LETTER GE;Ll;0;L;;;;;N;;;13A8;;13A8
caseT.init(base.Case.Upper, 0xab78, 0x13a8),
caseT.init(base.Case.Lower, 0xab78, 0xab78),
caseT.init(base.Case.Title, 0xab78, 0x13a8),
caseT.init(base.Case.Upper, 0x13a8, 0x13a8),
caseT.init(base.Case.Lower, 0x13a8, 0xab78),
caseT.init(base.Case.Title, 0x13a8, 0x13a8),
// Last block in the 5.1.0 table
// 10400;DESERET CAPITAL LETTER LONG I;Lu;0;L;;;;;N;;;;10428;
caseT.init(base.Case.Upper, 0x10400, 0x10400),
caseT.init(base.Case.Lower, 0x10400, 0x10428),
caseT.init(base.Case.Title, 0x10400, 0x10400),
// 10427;DESERET CAPITAL LETTER EW;Lu;0;L;;;;;N;;;;1044F;
caseT.init(base.Case.Upper, 0x10427, 0x10427),
caseT.init(base.Case.Lower, 0x10427, 0x1044F),
caseT.init(base.Case.Title, 0x10427, 0x10427),
// 10428;DESERET SMALL LETTER LONG I;Ll;0;L;;;;;N;;;10400;;10400
caseT.init(base.Case.Upper, 0x10428, 0x10400),
caseT.init(base.Case.Lower, 0x10428, 0x10428),
caseT.init(base.Case.Title, 0x10428, 0x10400),
// 1044F;DESERET SMALL LETTER EW;Ll;0;L;;;;;N;;;10427;;10427
caseT.init(base.Case.Upper, 0x1044F, 0x10427),
caseT.init(base.Case.Lower, 0x1044F, 0x1044F),
caseT.init(base.Case.Title, 0x1044F, 0x10427),
// First one not in the 5.1.0 table
// 10450;SHAVIAN LETTER PEEP;Lo;0;L;;;;;N;;;;;
caseT.init(base.Case.Upper, 0x10450, 0x10450),
caseT.init(base.Case.Lower, 0x10450, 0x10450),
caseT.init(base.Case.Title, 0x10450, 0x10450),
// Non-letters with case.
caseT.init(base.Case.Lower, 0x2161, 0x2171),
caseT.init(base.Case.Upper, 0x0345, 0x0399),
};
test "toUpper" {
for (case_test) |c, idx| {
switch (c.case) {
base.Case.Upper => {
const r = unicode.toUpper(c.in);
if (r != c.out) {
try t.terrorf("expected {} got {}\n", c.out, r);
}
},
else => {},
}
}
}
test "toLower" {
for (case_test) |c, idx| {
switch (c.case) {
base.Case.Lower => {
const r = unicode.toLower(c.in);
if (r != c.out) {
try t.terrorf("expected {} got {}\n", c.out, r);
}
},
else => {},
}
}
}
test "toLower" {
for (case_test) |c, idx| {
switch (c.case) {
base.Case.Title => {
const r = unicode.toTitle(c.in);
if (r != c.out) {
try t.terrorf("expected {} got {}\n", c.out, r);
}
},
else => {},
}
}
}
test "to" {
for (case_test) |c| {
const r = unicode.to(c.case, c.in);
if (r != c.out) {
try t.terrorf("expected {} got {}\n", c.out, r);
}
}
}
test "isControlLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isControl(i);
var want: bool = false;
if (0x00 <= i and i <= 0x1F) {
want = true;
} else if (0x7F <= i and i <= 0x9F) {
want = true;
}
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isLetterLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isLetter(i);
const want = letter.is(tables.Letter, i);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isUpperLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isUpper(i);
const want = letter.is(tables.Upper, i);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isLowerLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isLower(i);
const want = letter.is(tables.Lower, i);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isNumberLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isNumber(i);
const want = letter.is(tables.Number, i);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isPrintLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isPrint(i);
var want = unicode.in(i, unicode.print_ranges[0..]);
if (i == ' ') {
want = true;
}
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isGraphicLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isGraphic(i);
var want = unicode.in(i, unicode.graphic_ranges[0..]);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isPunctLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isPunct(i);
const want = letter.is(tables.Punct, i);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isSpaceLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isSpace(i);
const want = letter.is(tables.White_Space, i);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
test "isSymbolLatin1" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isSymbol(i);
const want = letter.is(tables.Symbol, i);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
const test_digit = []u32{
0x0030,
0x0039,
0x0661,
0x06F1,
0x07C9,
0x0966,
0x09EF,
0x0A66,
0x0AEF,
0x0B66,
0x0B6F,
0x0BE6,
0x0BEF,
0x0C66,
0x0CEF,
0x0D66,
0x0D6F,
0x0E50,
0x0E59,
0x0ED0,
0x0ED9,
0x0F20,
0x0F29,
0x1040,
0x1049,
0x1090,
0x1091,
0x1099,
0x17E0,
0x17E9,
0x1810,
0x1819,
0x1946,
0x194F,
0x19D0,
0x19D9,
0x1B50,
0x1B59,
0x1BB0,
0x1BB9,
0x1C40,
0x1C49,
0x1C50,
0x1C59,
0xA620,
0xA629,
0xA8D0,
0xA8D9,
0xA900,
0xA909,
0xAA50,
0xAA59,
0xFF10,
0xFF19,
0x104A1,
0x1D7CE,
};
const test_letter = []u32{
0x0041,
0x0061,
0x00AA,
0x00BA,
0x00C8,
0x00DB,
0x00F9,
0x02EC,
0x0535,
0x06E6,
0x093D,
0x0A15,
0x0B99,
0x0DC0,
0x0EDD,
0x1000,
0x1200,
0x1312,
0x1401,
0x1885,
0x2C00,
0xA800,
0xF900,
0xFA30,
0xFFDA,
0xFFDC,
0x10000,
0x10300,
0x10400,
0x20000,
0x2F800,
0x2FA1D,
};
test "isDigit" {
for (test_digit) |r| {
if (!unicode.isDigit(r)) {
try t.terrorf("expected {} to be a digit\n", r);
}
}
for (test_letter) |r| {
if (unicode.isDigit(r)) {
try t.terrorf("expected {} not to be a digit\n", r);
}
}
}
test "DigitOptimization" {
var i: u32 = 0;
while (i <= base.max_latin1) {
const got = unicode.isDigit(i);
const want = letter.is(tables.Digit, i);
if (got != want) {
try t.terrorf("{} got {} wanted {}\n", i, got, want);
}
i += 1;
}
}
|
src/unicode/index_test.zig
|
const std = @import("std");
const debug = std.debug;
const fmt = std.fmt;
const math = std.math;
const mem = std.mem;
const unicode = std.unicode;
const testing = std.testing;
pub const ascii = @import("src/ascii.zig");
pub const utf8 = @import("src/utf8.zig");
/// The result of a successful parse
pub fn Result(comptime T: type) type {
return struct {
const Value = T;
value: T,
rest: []const u8,
pub fn init(v: T, _rest: []const u8) @This() {
return .{ .value = v, .rest = _rest };
}
};
}
/// The type of all parser that can work with `mecha`
pub fn Parser(comptime T: type) type {
return fn ([]const u8) ?Result(T);
}
fn ReturnType(comptime P: type) type {
return @typeInfo(P).Fn.return_type.?;
}
/// The reverse of `Parser`. Give it a `Parser` type
/// and this function will give you `T`.
pub fn ParserResult(comptime P: type) type {
return @typeInfo(ReturnType(P)).Optional.child.Value;
}
/// A parser that only succeeds on the end of the string.
pub fn eos(str: []const u8) ?Result(void) {
if (str.len != 0)
return null;
return Result(void).init({}, str);
}
test "eos" {
expectResult(void, .{ .value = {}, .rest = "" }, eos(""));
expectResult(void, null, eos("a"));
}
/// A parser that always succeeds with the result being the
/// entire string. The same as the '.*$' regex.
pub fn rest(str: []const u8) ?Result([]const u8) {
return Result([]const u8).init(str, str[str.len..]);
}
test "rest" {
expectResult([]const u8, .{ .value = "", .rest = "" }, rest(""));
expectResult([]const u8, .{ .value = "a", .rest = "" }, rest("a"));
}
/// Construct a parser that succeeds if the string passed in starts
/// with `str`.
pub fn string(comptime str: []const u8) Parser(void) {
return struct {
const Res = Result(void);
fn func(s: []const u8) ?Res {
if (!mem.startsWith(u8, s, str))
return null;
return Res.init({}, s[str.len..]);
}
}.func;
}
test "string" {
expectResult(void, .{ .value = {}, .rest = "" }, string("aa")("aa"));
expectResult(void, .{ .value = {}, .rest = "a" }, string("aa")("aaa"));
expectResult(void, null, string("aa")("ba"));
expectResult(void, null, string("aa")(""));
}
/// Construct a parser that repeatedly uses `parser` until `n` iterations is reached.
/// The parsers result will be an array of the results from the repeated parser.
pub fn manyN(
comptime n: usize,
comptime parser: anytype,
) Parser([n]ParserResult(@TypeOf(parser))) {
return struct {
const Array = [n]ParserResult(@TypeOf(parser));
const Res = Result(Array);
fn func(str: []const u8) ?Res {
var rem = str;
var res: Array = undefined;
for (res) |*value| {
const r = parser(rem) orelse return null;
rem = r.rest;
value.* = r.value;
}
return Res.init(res, rem);
}
}.func;
}
/// Construct a parser that repeatedly uses `parser` until it fails
/// or `m` iterations is reached. The parser constructed will only
/// succeed if `parser` succeeded at least `n` times. The parsers
/// result will be a string containing everything parsed.
pub fn manyRange(
comptime n: usize,
comptime m: usize,
comptime parser: anytype,
) Parser([]const u8) {
return struct {
const Res = Result([]const u8);
fn func(str: []const u8) ?Res {
const first_n = manyN(n, parser)(str) orelse return null;
var rem = first_n.rest;
var i: usize = n;
while (i < m) : (i += 1) {
const r = parser(rem) orelse break;
rem = r.rest;
}
return Res.init(str[0 .. str.len - rem.len], rem);
}
}.func;
}
/// Construct a parser that repeatedly uses `parser` until it fails.
/// The parsers result will be a string containing everything parsed.
pub fn many(comptime parser: anytype) Parser([]const u8) {
return manyRange(0, math.maxInt(usize), parser);
}
test "many" {
const parser1 = comptime many(string("ab"));
expectResult([]const u8, .{ .value = "", .rest = "" }, parser1(""));
expectResult([]const u8, .{ .value = "", .rest = "a" }, parser1("a"));
expectResult([]const u8, .{ .value = "ab", .rest = "" }, parser1("ab"));
expectResult([]const u8, .{ .value = "ab", .rest = "a" }, parser1("aba"));
expectResult([]const u8, .{ .value = "abab", .rest = "" }, parser1("abab"));
expectResult([]const u8, .{ .value = "abab", .rest = "a" }, parser1("ababa"));
expectResult([]const u8, .{ .value = "ababab", .rest = "" }, parser1("ababab"));
const parser2 = comptime manyRange(1, 2, string("ab"));
expectResult([]const u8, null, parser2(""));
expectResult([]const u8, null, parser2("a"));
expectResult([]const u8, .{ .value = "ab", .rest = "" }, parser2("ab"));
expectResult([]const u8, .{ .value = "ab", .rest = "a" }, parser2("aba"));
expectResult([]const u8, .{ .value = "abab", .rest = "" }, parser2("abab"));
expectResult([]const u8, .{ .value = "abab", .rest = "a" }, parser2("ababa"));
expectResult([]const u8, .{ .value = "abab", .rest = "ab" }, parser2("ababab"));
const parser3 = comptime many(utf8.char(0x100));
expectResult([]const u8, .{ .value = "ĀĀĀ", .rest = "āāā" }, parser3("ĀĀĀāāā"));
const parser4 = comptime manyN(3, ascii.range('a', 'b'));
expectResult([3]u8, .{ .value = "aba".*, .rest = "bab" }, parser4("ababab"));
}
/// Construct a parser that will call `parser` on the string
/// but never fails to parser. The parsers result will be the
/// result of `parser` on success and `null` on failure.
pub fn opt(comptime parser: anytype) Parser(?ParserResult(@TypeOf(parser))) {
return struct {
const Res = Result(?ParserResult(@TypeOf(parser)));
fn func(str: []const u8) ?Res {
if (parser(str)) |r|
return Res.init(r.value, r.rest);
return Res.init(null, str);
}
}.func;
}
test "opt" {
const parser1 = comptime opt(ascii.range('a', 'z'));
expectResult(?u8, .{ .value = 'a', .rest = "" }, parser1("a"));
expectResult(?u8, .{ .value = 'a', .rest = "a" }, parser1("aa"));
expectResult(?u8, .{ .value = null, .rest = "1" }, parser1("1"));
}
fn ParsersTypes(comptime parsers: anytype) []const type {
var types: []const type = &[_]type{};
for (parsers) |parser| {
const T = ParserResult(@TypeOf(parser));
if (T != void)
types = types ++ [_]type{T};
}
return types;
}
fn Combine(comptime parsers: anytype) type {
const types = ParsersTypes(parsers);
if (types.len == 0)
return void;
if (types.len == 1)
return types[0];
return Tuple(types.len, types[0..types.len].*);
}
/// HACK: Zig cannot cache functions that takes pointers (slices)
/// so we have to passed the types as an array by value.
fn Tuple(comptime n: usize, comptime types: [n]type) type {
return std.meta.Tuple(&types);
}
/// Takes a tuple of `Parser(any)` and constructs a parser that
/// only succeeds if all parsers succeed to parse. The parsers
/// will be called in order and parser `N` will use the `rest`
/// from parser `N-1`. The parsers result will be a `Tuple` of
/// all parser not of type `Parser(void)`. If only one parser
/// is not of type `Parser(void)` then this parsers result is
/// returned instead of a tuple.
pub fn combine(comptime parsers: anytype) Parser(Combine(parsers)) {
return struct {
const types = ParsersTypes(parsers);
const Res = Result(Combine(parsers));
fn func(str: []const u8) ?Res {
var res: Res = undefined;
res.rest = str;
comptime var i = 0;
comptime var j = 0;
inline while (i < parsers.len) : (i += 1) {
const r = parsers[i](res.rest) orelse return null;
res.rest = r.rest;
if (@TypeOf(r.value) != void) {
if (types.len == 1) {
res.value = r.value;
} else {
res.value[j] = r.value;
}
j += 1;
}
}
return res;
}
}.func;
}
test "combine" {
const parser1 = comptime combine(.{ opt(ascii.range('a', 'b')), opt(ascii.range('d', 'e')) });
const Res = ParserResult(@TypeOf(parser1));
expectResult(Res, .{ .value = .{ .@"0" = 'a', .@"1" = 'd' }, .rest = "" }, parser1("ad"));
expectResult(Res, .{ .value = .{ .@"0" = 'a', .@"1" = null }, .rest = "a" }, parser1("aa"));
expectResult(Res, .{ .value = .{ .@"0" = null, .@"1" = 'd' }, .rest = "a" }, parser1("da"));
expectResult(Res, .{ .value = .{ .@"0" = null, .@"1" = null }, .rest = "qa" }, parser1("qa"));
const parser2 = comptime combine(.{ opt(ascii.range('a', 'b')), ascii.char('d') });
expectResult(?u8, .{ .value = 'a', .rest = "" }, parser2("ad"));
expectResult(?u8, .{ .value = 'a', .rest = "a" }, parser2("ada"));
expectResult(?u8, .{ .value = null, .rest = "a" }, parser2("da"));
expectResult(?u8, null, parser2("qa"));
}
/// Takes a tuple of `Parser(T)` and constructs a parser that
/// only succeeds if one of the parsers succeed to parse. The
/// parsers will be called in order all with `str` as input.
/// The parser will return with the result of the first parser
/// that succeeded. The parsers result will be `Result(T)`
pub fn oneOf(comptime parsers: anytype) Parser(ParserResult(@TypeOf(parsers[0]))) {
return struct {
fn func(str: []const u8) ?Result(ParserResult(@TypeOf(parsers[0]))) {
inline for (parsers) |p| {
if (p(str)) |res|
return res;
}
return null;
}
}.func;
}
test "oneOf" {
const parser1 = comptime oneOf(.{ ascii.range('a', 'b'), ascii.range('d', 'e') });
expectResult(u8, .{ .value = 'a', .rest = "" }, parser1("a"));
expectResult(u8, .{ .value = 'b', .rest = "" }, parser1("b"));
expectResult(u8, .{ .value = 'd', .rest = "" }, parser1("d"));
expectResult(u8, .{ .value = 'e', .rest = "" }, parser1("e"));
expectResult(u8, .{ .value = 'a', .rest = "a" }, parser1("aa"));
expectResult(u8, .{ .value = 'b', .rest = "a" }, parser1("ba"));
expectResult(u8, .{ .value = 'd', .rest = "a" }, parser1("da"));
expectResult(u8, .{ .value = 'e', .rest = "a" }, parser1("ea"));
expectResult(u8, null, parser1("q"));
}
/// Takes any parser (preferable not of type `Parser([]const u8)`)
/// and converts it to a parser where the result is a string that
/// contains all characters parsed by `parser`.
pub fn asStr(comptime parser: anytype) Parser([]const u8) {
return struct {
const Res = Result([]const u8);
fn func(str: []const u8) ?Res {
const r = parser(str) orelse return null;
return Res.init(str[0 .. str.len - r.rest.len], r.rest);
}
}.func;
}
test "asStr" {
const parser1 = comptime asStr(ascii.char('a'));
expectResult([]const u8, .{ .value = "a", .rest = "" }, parser1("a"));
expectResult([]const u8, .{ .value = "a", .rest = "a" }, parser1("aa"));
expectResult([]const u8, null, parser1("ba"));
const parser2 = comptime asStr(combine(.{ opt(ascii.range('a', 'b')), opt(ascii.range('d', 'e')) }));
expectResult([]const u8, .{ .value = "ad", .rest = "" }, parser2("ad"));
expectResult([]const u8, .{ .value = "a", .rest = "a" }, parser2("aa"));
expectResult([]const u8, .{ .value = "d", .rest = "a" }, parser2("da"));
expectResult([]const u8, .{ .value = "", .rest = "qa" }, parser2("qa"));
}
/// Constructs a parser that has its result converted with the
/// `conv` function. The ´conv` functions signature is
/// `fn (ParserResult(parser)) ?T`. The parser constructed will
/// fail if `conv` fails.
pub fn convert(
comptime T: type,
comptime conv: anytype,
comptime parser: anytype,
) Parser(T) {
return struct {
const Res = Result(T);
fn func(str: []const u8) ?Res {
const r = parser(str) orelse return null;
const v = conv(r.value) orelse return null;
return Res.init(v, r.rest);
}
}.func;
}
/// Constructs a convert function for `convert` that takes a
/// string and parses it to an int of type `Int`.
pub fn toInt(comptime Int: type, comptime base: u8) fn ([]const u8) ?Int {
return struct {
fn func(str: []const u8) ?Int {
return fmt.parseInt(Int, str, base) catch return null;
}
}.func;
}
/// Constructs a convert function for `convert` that takes a
/// string and parses it to a float of type `Float`.
pub fn toFloat(comptime Float: type) fn ([]const u8) ?Float {
return struct {
fn func(str: []const u8) ?Float {
return fmt.parseFloat(Float, str) catch return null;
}
}.func;
}
/// A convert function for `convert` that takes a string and
/// returns the first codepoint.
pub fn toChar(str: []const u8) ?u21 {
if (str.len > 1) {
const cp_len = unicode.utf8ByteSequenceLength(str[0]) catch return null;
if (cp_len > str.len)
return null;
return unicode.utf8Decode(str[0..cp_len]) catch null;
}
return @as(u21, str[0]);
}
/// Constructs a convert function for `convert` that takes a
/// string and converts it to an `Enum` with `std.meta.stringToEnum`.
pub fn toEnum(comptime Enum: type) fn ([]const u8) ?Enum {
return struct {
fn func(str: []const u8) ?Enum {
return std.meta.stringToEnum(Enum, str);
}
}.func;
}
/// A convert function for `convert` that takes a string
/// and returns `true` if it is `"true"` and `false` if it
/// is `"false"`.
pub fn toBool(str: []const u8) ?bool {
const r = toEnum(enum { @"false", @"true" })(str) orelse return null;
return r == .@"true";
}
test "convert" {
const parser1 = comptime convert(u8, toInt(u8, 10), asStr(string("123")));
expectResult(u8, .{ .value = 123, .rest = "" }, parser1("123"));
expectResult(u8, .{ .value = 123, .rest = "a" }, parser1("123a"));
expectResult(u8, null, parser1("12"));
const parser2 = comptime convert(u21, toChar, asStr(string("a")));
expectResult(u21, .{ .value = 'a', .rest = "" }, parser2("a"));
expectResult(u21, .{ .value = 'a', .rest = "a" }, parser2("aa"));
expectResult(u21, null, parser2("b"));
const parser3 = comptime convert(bool, toBool, rest);
expectResult(bool, .{ .value = true, .rest = "" }, parser3("true"));
expectResult(bool, .{ .value = false, .rest = "" }, parser3("false"));
expectResult(bool, null, parser3("b"));
const parser4 = comptime convert(f32, toFloat(f32), asStr(string("1.23")));
expectResult(f32, .{ .value = 1.23, .rest = "" }, parser4("1.23"));
expectResult(f32, .{ .value = 1.23, .rest = "a" }, parser4("1.23a"));
expectResult(f32, null, parser4("1.2"));
const E = packed enum(u8) { a, b, _ };
const parser5 = comptime convert(E, toEnum(E), rest);
expectResult(E, .{ .value = E.a, .rest = "" }, parser5("a"));
expectResult(E, .{ .value = E.b, .rest = "" }, parser5("b"));
expectResult(E, null, parser5("2"));
const parser6 = comptime convert(u21, toChar, asStr(string("Āā")));
expectResult(u21, .{ .value = 0x100, .rest = "" }, parser6("Āā"));
}
/// Constructs a parser that has its result converted with the
/// `conv` function. The ´conv` functions signature is
/// `fn (ParserResult(parser)) T`, so this function should only
/// be used for conversions that cannot fail. See `convert`.
pub fn map(
comptime T: type,
comptime conv: anytype,
comptime parser: anytype,
) Parser(T) {
return struct {
const Res = Result(T);
fn func(str: []const u8) ?Res {
const r = parser(str) orelse return null;
return Res.init(conv(r.value), r.rest);
}
}.func;
}
fn ToStructResult(comptime T: type) type {
return @TypeOf(struct {
fn func(tuple: anytype) T {
return undefined;
}
}.func);
}
/// Constructs a convert function for `as` that takes a tuple or an array and
/// converts it into the struct `T`. Fields will be assigned in order,
/// so `tuple[i]` will be assigned to the ith field of `T`. This function
/// will give a compile error if `T` and the tuple does not have the same
/// number of fields, or if the items of the tuple cannot be coerced into
/// the fields of the struct.
pub fn toStruct(comptime T: type) ToStructResult(T) {
return struct {
fn func(tuple: anytype) T {
const struct_fields = @typeInfo(T).Struct.fields;
if (struct_fields.len != tuple.len)
@compileError(@typeName(T) ++ " and " ++ @typeName(@TypeOf(tuple)) ++ " does not have " ++
"same number of fields. Convertion is not possible.");
var res: T = undefined;
inline for (struct_fields) |field, i|
@field(res, field.name) = tuple[i];
return res;
}
}.func;
}
test "map" {
const Point = struct {
x: usize,
y: usize,
};
const parser1 = comptime map(Point, toStruct(Point), combine(.{ int(usize, 10), ascii.char(' '), int(usize, 10) }));
expectResult(Point, .{ .value = .{ .x = 10, .y = 10 }, .rest = "" }, parser1("10 10"));
expectResult(Point, .{ .value = .{ .x = 20, .y = 20 }, .rest = "aa" }, parser1("20 20aa"));
expectResult(Point, null, parser1("12"));
const parser2 = comptime map(Point, toStruct(Point), manyN(2, combine(.{ int(usize, 10), ascii.char(' ') })));
expectResult(Point, .{ .value = .{ .x = 10, .y = 10 }, .rest = "" }, parser2("10 10 "));
expectResult(Point, .{ .value = .{ .x = 20, .y = 20 }, .rest = "aa" }, parser2("20 20 aa"));
expectResult(Point, null, parser1("12"));
}
/// Constructs a parser that discards the result returned from the parser
/// it warps.
pub fn discard(comptime parser: anytype) Parser(void) {
return convert(void, struct {
fn d(_: anytype) ?void {}
}.d, parser);
}
test "discard" {
const parser = comptime discard(many(ascii.char(' ')));
expectResult(void, .{ .value = {}, .rest = "abc" }, parser(" abc"));
expectResult(void, .{ .value = {}, .rest = "abc" }, parser(" abc"));
expectResult(void, .{ .value = {}, .rest = "abc" }, parser(" abc"));
}
/// Construct a parser that succeeds if it parser an integer of
/// `base`. The result of this parser will be the string containing
/// the match.
pub fn intToken(comptime base: u8) Parser([]const u8) {
return comptime asStr(combine(.{
opt(ascii.char('-')),
manyRange(1, math.maxInt(usize), ascii.digit(base)),
}));
}
/// Same as `intToken` but also converts the parsed string
/// to an integer.
pub fn int(comptime Int: type, comptime base: u8) Parser(Int) {
return comptime convert(Int, toInt(Int, base), intToken(base));
}
test "int" {
const parser1 = int(u8, 10);
expectResult(u8, .{ .value = 0, .rest = "" }, parser1("0"));
expectResult(u8, .{ .value = 1, .rest = "" }, parser1("1"));
expectResult(u8, .{ .value = 1, .rest = "a" }, parser1("1a"));
expectResult(u8, .{ .value = 255, .rest = "" }, parser1("255"));
expectResult(u8, null, parser1("256"));
const parser2 = int(u8, 16);
expectResult(u8, .{ .value = 0x00, .rest = "" }, parser2("0"));
expectResult(u8, .{ .value = 0x01, .rest = "" }, parser2("1"));
expectResult(u8, .{ .value = 0x1a, .rest = "" }, parser2("1a"));
expectResult(u8, .{ .value = 0x01, .rest = "g" }, parser2("1g"));
expectResult(u8, .{ .value = 0xff, .rest = "" }, parser2("ff"));
expectResult(u8, .{ .value = 0xff, .rest = "" }, parser2("FF"));
expectResult(u8, null, parser2("100"));
}
/// Creates a parser that calls a function to optain its underlying parser.
/// This function introduces the indirection required for recursive grammars.
/// ```
/// const digit_10 = discard(digit(10));
/// const digits = oneOf(.{ combine(.{ digit_10, ref(digits_ref) }), digit_10 });
/// fn digits_ref() Parser(void) {
/// return digits;
/// };
/// ```
pub fn ref(comptime func: anytype) Parser(ParserResult(ReturnType(@TypeOf(func)))) {
return struct {
const P = ReturnType(@TypeOf(func));
const T = ParserResult(P);
fn res(str: []const u8) ?Result(T) {
return func()(str);
}
}.res;
}
test "ref" {
const Scope = struct {
const digit = discard(ascii.digit(10));
const digits = oneOf(.{ combine(.{ digit, ref(digits_ref) }), digit });
fn digits_ref() Parser(void) {
return digits;
}
};
expectResult(void, .{ .value = {}, .rest = "" }, Scope.digits("0"));
}
pub fn expectResult(comptime T: type, m_expect: ?Result(T), m_actual: ?Result(T)) void {
const expect = m_expect orelse {
testing.expectEqual(@as(?Result(T), null), m_actual);
return;
};
testing.expect(m_actual != null);
const actual = m_actual.?;
testing.expectEqualStrings(expect.rest, actual.rest);
switch (T) {
[]const u8 => testing.expectEqualStrings(expect.value, actual.value),
else => testing.expectEqual(expect.value, actual.value),
}
}
|
src/mecha/mecha.zig
|
usingnamespace @import("root").preamble;
const libalign = lib.libalign;
const allocator = os.memory.vmm.backed(.Ephemeral);
const pmm = os.memory.pmm;
const paging = os.memory.paging;
const pci = os.platform.pci;
const assert = std.debug.assert;
/// Descriptor iterator helper.
pub const DescIter = struct {
drv: *Driver,
i: u8,
curr: Descriptor,
next: Descriptor,
/// Put the head of a descriptor chain on the available ring
pub fn begin(iter: *@This()) void {
var i = &iter.drv.queues[iter.i];
iter.next = iter.drv.descr(iter.i);
i.avail.rings(i.wrap(i.avail.idx +% i.pending)).* = iter.next;
i.pending += 1;
}
/// Put a descriptor to be part of the descriptor chain
pub fn putPhys(iter: *@This(), addr: u64, len: u32, flags: u16) void {
iter.curr = iter.next;
iter.next = if ((flags & vring_desc_flag_next) != 0) iter.drv.descr(iter.i) else 0xFFFF;
iter.drv.queues[iter.i].desc[iter.curr] = .{
.addr = addr,
.len = len,
.flags = flags,
.next = iter.next,
};
}
/// Put a descriptor to be part of the descriptor chain
pub fn put(iter: *@This(), a: anytype, len: u32, flags: u16) void {
assert(len <= 0x1000);
const addr = paging.translateVirt(.{ .virt = @ptrToInt(a) }) catch |err| {
@panic("virtio-pci: can't get the physical address");
};
iter.putPhys(addr, len, flags);
}
};
/// The actual driver structure for the modern virtio-pci transport.
/// It expects already-initialized BARs. There is no support for the legacy PIO-only interface.
pub const Driver = struct {
/// Find PCI BARs and initialize device
pub fn init(a: pci.Addr, reqFeatures: u64, optFeatures: u64) !Driver {
var drv: Driver = initPCI(a);
drv.cfg.device_status = 0; // reset
drv.cfg.device_status |= virtio_acknowledge; // guest acknowledged device
drv.cfg.device_status |= virtio_driver; // driver has been loaded
// set the failed bit on unrecoverable errors
errdefer drv.cfg.device_status |= virtio_failed;
// negotiate features
var req = reqFeatures | (1 << virtio_feature_version_1); // legacy devices aren't supported
try drv.feature(0, @truncate(u32, req), @truncate(u32, optFeatures));
try drv.feature(1, @truncate(u32, req >> 32), @truncate(u32, optFeatures >> 32));
drv.cfg.device_status |= virtio_features_ok; // features acknowledged
if ((drv.cfg.device_status & virtio_features_ok) == 0) return error.FeaturesNotAccepted;
for (drv.queues) |_, i| drv.setupQueue(@truncate(u16, i));
drv.cfg.device_status |= virtio_driver_ok; // driver initialized, start normal operation
return drv;
}
/// Create descriptor iterator
pub fn iter(drv: *@This(), i: u8) DescIter {
return .{ .drv = drv, .i = i, .curr = 0xFFFF, .next = 0xFFFF };
}
/// Free the chain which starts at `head`
pub fn freeChain(drv: *@This(), i: u8, head: Descriptor) void {
var q: *VirtQueue = &drv.queues[i];
var last = &q.desc[head];
while ((last.flags & vring_desc_flag_next) != 0) { // follow descriptor chain
q.num_unused += 1;
last = &q.desc[last.next];
} // last is now the descriptor *after* the chain
q.num_unused += 1;
last.next = q.first_unused;
// add the freed chain before the current freelist
last.flags = if (q.first_unused != 0xFFFF) vring_desc_flag_next else 0;
q.first_unused = head;
}
/// Process incoming events.
pub fn process(drv: *@This(), i: u8) void {
var q = &drv.queues[i];
while (q.last_in_used != q.used.idx) {
var elem = q.used.rings(q.wrap(q.last_in_used));
q.last_in_used = q.last_in_used +% 1;
drv.freeChain(i, @truncate(Descriptor, elem.id));
}
}
/// Get one event from the used queue
pub fn processOne(drv: *@This(), i: u8) ?Descriptor {
var q = &drv.queues[i];
if (q.last_in_used != q.used.idx) {
var elem = q.used.rings(q.wrap(q.last_in_used));
q.last_in_used = q.last_in_used +% 1;
return @truncate(u16, elem.id);
}
return null;
}
/// Make the descriptors available to the device and notify it.
pub fn start(drv: *@This(), i: u8) void {
// The virtio spec requires me to send values modulo 2^16, and not modulo size
// This explains the ugly overflowing-adds
drv.queues[i].avail.idx = drv.queues[i].avail.idx +% drv.queues[i].pending;
drv.queues[i].pending = 0;
drv.notify[i * drv.notify_mul] = drv.queues[i].avail.idx;
}
/// Acknowledge virtio interrupt
pub fn acknowledge(drv: *@This()) void {
// Doesn't look very robust, but it works. Definitively look here if something break
var result = drv.isr.*;
}
/// Allocate a descriptor
pub fn descr(drv: *@This(), i: u8) Descriptor {
var q = &drv.queues[i];
var first_un = q.first_unused;
if ((first_un == 0xFFFF) or (q.num_unused == 0)) {
@panic("virtio-pci: not enough descriptors");
}
q.first_unused = q.desc[first_un].next;
drv.queues[i].num_unused -= 1;
return first_un;
}
const fconv = if (@hasField(std.builtin.CallingConvention, "Inline")) .Inline else .Unspecified;
/// Negotiate feature bitmask with device, ZIG BUG, bad codegen without .Inline, no issue open
fn feature(drv: *Driver, i: u32, req: u32, opt: u32) callconv(fconv) !void {
drv.cfg.device_feature_select = i;
const f = drv.cfg.device_feature & (req | opt);
if ((f & req) != req) {
return error.FeatureNotAvailable;
}
drv.cfg.guest_feature_select = i;
drv.cfg.guest_feature = f;
}
pub fn addIRQ(drv: *Driver, queue: u16, fun: anytype, ctx: anytype) void {
const vec = os.platform.irq_with_ctx(@ptrToInt(fun), @ptrToInt(ctx));
const addr = 0xFEE00000; // TODO: this routes using the lapic on core 0
drv.msix_table[drv.msix_table_idx] = .{ .addr = addr, .data = vec };
const old = drv.cfg.queue_select;
drv.cfg.queue_select = queue;
drv.cfg.queue_msix_vector = drv.msix_table_idx;
drv.cfg.queue_select = old;
drv.msix_table_idx += 1;
}
/// Detect BARs and capabilities and set up the cfg/notify/isr/dev structures
fn initPCI(a: pci.Addr) Driver {
var drv: Driver = undefined;
a.command().write(a.command().read() | 0b110); // enable bus master and memory space
switch (pci.msi_enable(a)) {
.msix => |*m| {
drv.msix_table = m.table;
drv.msix_table_size = m.size;
drv.msix_table_idx = 0;
},
else => @panic("Virtio without MSI-X should not be available"),
}
var cap = a.cap();
while (cap.off != 0) {
if (cap.id() == 0x09) {
const cfg_typ = cap.read(u8, virtio_pci_cap_cfg_type);
const bar = cap.read(u8, virtio_pci_cap_bar);
const off = cap.read(u32, virtio_pci_cap_offset);
const len = cap.read(u32, virtio_pci_cap_length);
const phy = a.barinfo(bar).phy + off;
switch (cfg_typ) {
virtio_pci_cap_common_cfg => {
const commonCfgPtr = os.platform.phys_ptr(*volatile CommonCfg);
drv.cfg = commonCfgPtr.from_int(phy).get_uncached();
},
virtio_pci_cap_notify_cfg => {
// virtio_pci_notify_cap_mult is a byte offset, each field is u16
drv.notify_mul = cap.read(u32, virtio_pci_notify_cap_mult) / 2;
const notifyPtr = os.platform.phys_ptr([*]volatile u16);
drv.notify = notifyPtr.from_int(phy).get_uncached();
},
virtio_pci_cap_jsr_cfg => {
drv.isr = os.platform.phys_ptr(*volatile u32).from_int(phy).get_uncached();
},
virtio_pci_cap_device_cfg => {
drv.dev = os.platform.phys_ptr([*]volatile u8).from_int(phy).get_uncached();
},
virtio_pci_cap_pci_cfg => {},
else => {}, // ignore
}
}
cap.next();
}
return drv;
}
/// Set up a specific queue
fn setupQueue(drv: *Driver, i: u16) void {
drv.cfg.queue_select = i;
const size = drv.cfg.queue_size;
if (size == 0) return;
drv.cfg.queue_msix_vector = i;
const desc_siz: u32 = @sizeOf(VirtqDesc) * size;
const avail_siz: u32 = @sizeOf(VirtqAvail) + 2 + 2 * size;
const used_siz: u32 = @sizeOf(VirtqUsed) + 2 + @sizeOf(VirtqUsedItem) * size;
const total_siz = desc_siz + avail_siz + used_siz;
const phys = os.memory.pmm.allocPhys(size) catch unreachable;
const virt = os.platform.phys_ptr([*]volatile u8).from_int(phys).get_uncached();
@memset(virt, 0x00, total_siz);
drv.queues[i] = .{
.desc = @ptrCast([*]VirtqDesc, virt),
.avail = @ptrCast(*VirtqAvail, virt + desc_siz),
.used = @ptrCast(*VirtqUsed, virt + desc_siz + avail_siz),
.size = size,
.num_unused = size,
.first_unused = 0,
.last_in_used = 0,
.pending = 0,
};
var m: u16 = 0;
while (m < size - 1) : (m += 1) {
drv.queues[i].desc[m] = .{
.flags = vring_desc_flag_next,
.next = m + 1,
.addr = 0,
.len = 0,
};
}
drv.queues[i].desc[m].next = 0xFFFF;
drv.cfg.queue_desc = phys;
drv.cfg.queue_avail = phys + desc_siz;
drv.cfg.queue_used = phys + desc_siz + avail_siz;
drv.cfg.queue_enable = 1; // important: this enables the queue
}
cfg: *volatile CommonCfg,
notify: [*]volatile Descriptor,
notify_mul: u32,
isr: *volatile u32,
dev: [*]volatile u8,
queues: [16]VirtQueue = undefined,
msix_table: [*]volatile pci.MsixTableEntry,
msix_table_size: u32,
msix_table_idx: u16 = 0,
};
pub const Descriptor = u16; // descriptor id
/// Ring descriptor, actual structure (`Descriptor` is only its id)
const VirtqDesc = packed struct {
addr: u64, // guest phyaddr
len: u32,
flags: u16,
next: Descriptor,
};
const VirtqAvail = packed struct {
flags: u16,
idx: Descriptor, // important: virtio requires this field to have the index without wraparound
pub fn rings(self: *volatile VirtqAvail, desc: Descriptor) *volatile u16 {
return @intToPtr(*volatile u16, @ptrToInt(self) + @sizeOf(VirtqAvail) + desc * 2);
}
};
const VirtqUsedItem = packed struct {
id: u32, // descriptor chain head
len: u32,
};
const VirtqUsed = packed struct {
flags: u16,
idx: u16, // last used idx, the driver keeps the first in last_in_used
pub fn rings(self: *volatile VirtqUsed, desc: Descriptor) *volatile VirtqUsedItem {
return @intToPtr(
*volatile VirtqUsedItem,
@ptrToInt(self) + @sizeOf(VirtqUsed) + desc * @sizeOf(VirtqUsedItem),
);
}
};
const VirtQueue = struct {
desc: [*]volatile VirtqDesc,
avail: *volatile VirtqAvail,
used: *volatile VirtqUsed,
size: u16,
first_unused: Descriptor,
last_in_used: u16, // index into used.rings()
num_unused: u16,
pending: u16,
// the size of a queue is guaranteed to be a power of two, so it's possible to save on a modulo
// and instead get the mask to AND
pub fn wrap(self: *@This(), val: u16) u16 {
return val & (self.size - 1);
}
};
const CommonCfg = packed struct {
device_feature_select: u32,
device_feature: u32,
guest_feature_select: u32,
guest_feature: u32,
config_msix_vector: u16,
num_queues: u16,
device_status: u8,
config_generation: u8,
queue_select: u16,
queue_size: u16,
queue_msix_vector: u16,
queue_enable: u16,
queue_notify_off: u16,
queue_desc: u64,
queue_avail: u64,
queue_used: u64,
};
const virtio_acknowledge: u8 = 1;
const virtio_driver: u8 = 2;
const virtio_failed: u8 = 128;
const virtio_features_ok: u8 = 8;
const virtio_driver_ok: u8 = 4;
const virtio_device_needs_reset: u8 = 64;
// Capability config types
const virtio_pci_cap_common_cfg = 1;
const virtio_pci_cap_notify_cfg = 2;
const virtio_pci_cap_jsr_cfg = 3;
const virtio_pci_cap_device_cfg = 4;
const virtio_pci_cap_pci_cfg = 5;
// PCI capability list record offsets
const virtio_pci_cap_len = 2;
const virtio_pci_cap_cfg_type = 3;
const virtio_pci_cap_bar = 4;
const virtio_pci_cap_offset = 8;
const virtio_pci_cap_length = 12;
const virtio_pci_notify_cap_mult = 16;
// Feature bits
const virtio_feature_version_1 = 32;
const virtio_feature_access_platform = 33;
const virtio_feature_ring_packed = 34;
const virtio_feature_order_platform = 36;
const virtio_feature_sr_iov = 37;
// Ring flags
pub const vring_desc_flag_next: u32 = 1;
pub const vring_desc_flag_write: u32 = 2;
pub const vring_desc_flag_indirect: u32 = 4;
|
subprojects/flork/src/drivers/misc/virtio_pci.zig
|
const std = @import("std");
const expect = std.testing.expect;
const expectError = std.testing.expectError;
const expectEqual = std.testing.expectEqual;
test "switch with numbers" {
try testSwitchWithNumbers(13);
}
fn testSwitchWithNumbers(x: u32) !void {
const result = switch (x) {
1, 2, 3, 4...8 => false,
13 => true,
else => false,
};
try expect(result);
}
test "switch with all ranges" {
try expect(testSwitchWithAllRanges(50, 3) == 1);
try expect(testSwitchWithAllRanges(101, 0) == 2);
try expect(testSwitchWithAllRanges(300, 5) == 3);
try expect(testSwitchWithAllRanges(301, 6) == 6);
}
fn testSwitchWithAllRanges(x: u32, y: u32) u32 {
return switch (x) {
0...100 => 1,
101...200 => 2,
201...300 => 3,
else => y,
};
}
test "implicit comptime switch" {
const x = 3 + 4;
const result = switch (x) {
3 => 10,
4 => 11,
5, 6 => 12,
7, 8 => 13,
else => 14,
};
comptime {
try expect(result + 1 == 14);
}
}
test "switch on enum" {
const fruit = Fruit.Orange;
nonConstSwitchOnEnum(fruit);
}
const Fruit = enum {
Apple,
Orange,
Banana,
};
fn nonConstSwitchOnEnum(fruit: Fruit) void {
switch (fruit) {
Fruit.Apple => unreachable,
Fruit.Orange => {},
Fruit.Banana => unreachable,
}
}
test "switch statement" {
try nonConstSwitch(SwitchStatementFoo.C);
}
fn nonConstSwitch(foo: SwitchStatementFoo) !void {
const val = switch (foo) {
SwitchStatementFoo.A => @as(i32, 1),
SwitchStatementFoo.B => 2,
SwitchStatementFoo.C => 3,
SwitchStatementFoo.D => 4,
};
try expect(val == 3);
}
const SwitchStatementFoo = enum { A, B, C, D };
test "switch with multiple expressions" {
const x = switch (returnsFive()) {
1, 2, 3 => 1,
4, 5, 6 => 2,
else => @as(i32, 3),
};
try expect(x == 2);
}
fn returnsFive() i32 {
return 5;
}
test "switch on type" {
try expect(trueIfBoolFalseOtherwise(bool));
try expect(!trueIfBoolFalseOtherwise(i32));
}
fn trueIfBoolFalseOtherwise(comptime T: type) bool {
return switch (T) {
bool => true,
else => false,
};
}
test "switching on booleans" {
try testSwitchOnBools();
comptime try testSwitchOnBools();
}
fn testSwitchOnBools() !void {
try expect(testSwitchOnBoolsTrueAndFalse(true) == false);
try expect(testSwitchOnBoolsTrueAndFalse(false) == true);
try expect(testSwitchOnBoolsTrueWithElse(true) == false);
try expect(testSwitchOnBoolsTrueWithElse(false) == true);
try expect(testSwitchOnBoolsFalseWithElse(true) == false);
try expect(testSwitchOnBoolsFalseWithElse(false) == true);
}
fn testSwitchOnBoolsTrueAndFalse(x: bool) bool {
return switch (x) {
true => false,
false => true,
};
}
fn testSwitchOnBoolsTrueWithElse(x: bool) bool {
return switch (x) {
true => false,
else => true,
};
}
fn testSwitchOnBoolsFalseWithElse(x: bool) bool {
return switch (x) {
false => true,
else => false,
};
}
test "u0" {
var val: u0 = 0;
switch (val) {
0 => try expect(val == 0),
}
}
test "undefined.u0" {
var val: u0 = undefined;
switch (val) {
0 => try expect(val == 0),
}
}
test "switch with disjoint range" {
var q: u8 = 0;
switch (q) {
0...125 => {},
127...255 => {},
126...126 => {},
}
}
test "switch variable for range and multiple prongs" {
const S = struct {
fn doTheTest() !void {
var u: u8 = 16;
try doTheSwitch(u);
comptime try doTheSwitch(u);
var v: u8 = 42;
try doTheSwitch(v);
comptime try doTheSwitch(v);
}
fn doTheSwitch(q: u8) !void {
switch (q) {
0...40 => |x| try expect(x == 16),
41, 42, 43 => |x| try expect(x == 42),
else => try expect(false),
}
}
};
_ = S;
}
var state: u32 = 0;
fn poll() void {
switch (state) {
0 => {
state = 1;
},
else => {
state += 1;
},
}
}
test "switch on global mutable var isn't constant-folded" {
while (state < 2) {
poll();
}
}
const SwitchProngWithVarEnum = union(enum) {
One: i32,
Two: f32,
Meh: void,
};
test "switch prong with variable" {
try switchProngWithVarFn(SwitchProngWithVarEnum{ .One = 13 });
try switchProngWithVarFn(SwitchProngWithVarEnum{ .Two = 13.0 });
try switchProngWithVarFn(SwitchProngWithVarEnum{ .Meh = {} });
}
fn switchProngWithVarFn(a: SwitchProngWithVarEnum) !void {
switch (a) {
SwitchProngWithVarEnum.One => |x| {
try expect(x == 13);
},
SwitchProngWithVarEnum.Two => |x| {
try expect(x == 13.0);
},
SwitchProngWithVarEnum.Meh => |x| {
const v: void = x;
_ = v;
},
}
}
test "switch on enum using pointer capture" {
try testSwitchEnumPtrCapture();
comptime try testSwitchEnumPtrCapture();
}
fn testSwitchEnumPtrCapture() !void {
var value = SwitchProngWithVarEnum{ .One = 1234 };
switch (value) {
SwitchProngWithVarEnum.One => |*x| x.* += 1,
else => unreachable,
}
switch (value) {
SwitchProngWithVarEnum.One => |x| try expect(x == 1235),
else => unreachable,
}
}
test "switch handles all cases of number" {
try testSwitchHandleAllCases();
comptime try testSwitchHandleAllCases();
}
fn testSwitchHandleAllCases() !void {
try expect(testSwitchHandleAllCasesExhaustive(0) == 3);
try expect(testSwitchHandleAllCasesExhaustive(1) == 2);
try expect(testSwitchHandleAllCasesExhaustive(2) == 1);
try expect(testSwitchHandleAllCasesExhaustive(3) == 0);
try expect(testSwitchHandleAllCasesRange(100) == 0);
try expect(testSwitchHandleAllCasesRange(200) == 1);
try expect(testSwitchHandleAllCasesRange(201) == 2);
try expect(testSwitchHandleAllCasesRange(202) == 4);
try expect(testSwitchHandleAllCasesRange(230) == 3);
}
fn testSwitchHandleAllCasesExhaustive(x: u2) u2 {
return switch (x) {
0 => @as(u2, 3),
1 => 2,
2 => 1,
3 => 0,
};
}
fn testSwitchHandleAllCasesRange(x: u8) u8 {
return switch (x) {
0...100 => @as(u8, 0),
101...200 => 1,
201, 203 => 2,
202 => 4,
204...255 => 3,
};
}
test "switch on union with some prongs capturing" {
const X = union(enum) {
a,
b: i32,
};
var x: X = X{ .b = 10 };
var y: i32 = switch (x) {
.a => unreachable,
.b => |b| b + 1,
};
try expect(y == 11);
}
|
test/behavior/switch.zig
|
const std = @import("std");
const c = @import("internal/c.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
pub const Credential = extern struct {
credtype: CredentialType,
free: fn (*Credential) callconv(.C) void,
pub fn deinit(self: *Credential) void {
log.debug("Credential.deinit called", .{});
if (internal.has_credential) {
c.git_credential_free(@ptrCast(*internal.RawCredentialType, self));
} else {
c.git_cred_free(@ptrCast(*internal.RawCredentialType, self));
}
log.debug("credential freed successfully", .{});
}
pub fn hasUsername(self: *Credential) bool {
log.debug("Credential.hasUsername called", .{});
var ret: bool = undefined;
if (internal.has_credential) {
ret = c.git_credential_has_username(@ptrCast(*internal.RawCredentialType, self)) != 0;
} else {
ret = c.git_cred_has_username(@ptrCast(*internal.RawCredentialType, self)) != 0;
}
log.debug("credential has username: {}", .{ret});
return ret;
}
pub fn getUsername(self: *Credential) ?[:0]const u8 {
log.debug("Credential.getUsername called", .{});
const opt_username = if (internal.has_credential)
c.git_credential_get_username(@ptrCast(*internal.RawCredentialType, self))
else
c.git_cred_get_username(@ptrCast(*internal.RawCredentialType, self));
if (opt_username) |username| {
const slice = std.mem.sliceTo(username, 0);
log.debug("credential has username: {s}", .{slice});
return slice;
} else {
log.debug("credential has no username", .{});
return null;
}
}
/// A plaintext username and password
pub const CredentialUserpassPlaintext = extern struct {
/// The parent credential
parent: Credential,
/// The username to authenticate as
username: [*:0]const u8,
/// The password to use
password: [*:0]const u8,
test {
try std.testing.expectEqual(@sizeOf(c.git_credential_userpass_plaintext), @sizeOf(CredentialUserpassPlaintext));
try std.testing.expectEqual(@bitSizeOf(c.git_credential_userpass_plaintext), @bitSizeOf(CredentialUserpassPlaintext));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Username-only credential information
pub const CredentialUsername = extern struct {
/// The parent credential
parent: Credential,
/// Use `username()`
z_username: [1]u8,
/// The username to authenticate as
pub fn username(self: CredentialUsername) [:0]const u8 {
return std.mem.sliceTo(@ptrCast([*:0]const u8, &self.z_username), 0);
}
test {
try std.testing.expectEqual(@sizeOf(c.git_credential_username), @sizeOf(CredentialUsername));
try std.testing.expectEqual(@bitSizeOf(c.git_credential_username), @bitSizeOf(CredentialUsername));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// A ssh key from disk
pub const CredentialSshKey = extern struct {
/// The parent credential
parent: Credential,
/// The username to authenticate as
username: [*:0]const u8,
/// The path to a public key
publickey: [*:0]const u8,
/// The path to a private key
privatekey: [*:0]const u8,
/// Passphrase to decrypt the private key
passphrase: ?[*:0]const u8,
test {
try std.testing.expectEqual(@sizeOf(c.git_credential_ssh_key), @sizeOf(CredentialSshKey));
try std.testing.expectEqual(@bitSizeOf(c.git_credential_ssh_key), @bitSizeOf(CredentialSshKey));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// A plaintext username and password
pub const CredentialSshInteractive = extern struct {
/// The parent credential
parent: Credential,
/// The username to authenticate as
username: [*:0]const u8,
/// Callback used for authentication.
prompt_callback: fn (
name: [*]const u8,
name_len: c_int,
instruction: [*]const u8,
instruction_len: c_int,
num_prompts: c_int,
prompts: ?*const c.LIBSSH2_USERAUTH_KBDINT_PROMPT,
responses: ?*c.LIBSSH2_USERAUTH_KBDINT_RESPONSE,
abstract: ?*?*anyopaque,
) callconv(.C) void,
/// Payload passed to prompt_callback
payload: ?*anyopaque,
test {
try std.testing.expectEqual(@sizeOf(c.git_credential_ssh_interactive), @sizeOf(CredentialSshInteractive));
try std.testing.expectEqual(@bitSizeOf(c.git_credential_ssh_interactive), @bitSizeOf(CredentialSshInteractive));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// A ssh key from disk
pub const CredentialSshCustom = extern struct {
/// The parent credential
parent: Credential,
/// The username to authenticate as
username: [*:0]const u8,
/// The public key data
publickey: [*:0]const u8,
/// Length of the public key
publickey_len: usize,
sign_callback: fn (
session: ?*c.LIBSSH2_SESSION,
sig: *[*:0]u8,
sig_len: *usize,
data: [*]const u8,
data_len: usize,
abstract: ?*?*anyopaque,
) callconv(.C) c_int,
payload: ?*anyopaque,
test {
try std.testing.expectEqual(@sizeOf(c.git_credential_ssh_custom), @sizeOf(CredentialSshCustom));
try std.testing.expectEqual(@bitSizeOf(c.git_credential_ssh_custom), @bitSizeOf(CredentialSshCustom));
}
comptime {
std.testing.refAllDecls(@This());
}
};
test {
try std.testing.expectEqual(@sizeOf(c.git_cred), @sizeOf(Credential));
try std.testing.expectEqual(@bitSizeOf(c.git_cred), @bitSizeOf(Credential));
}
comptime {
std.testing.refAllDecls(@This());
}
};
pub const CredentialType = packed struct {
/// A vanilla user/password request
userpass_plaintext: bool = false,
/// An SSH key-based authentication request
ssh_key: bool = false,
/// An SSH key-based authentication request, with a custom signature
ssh_custom: bool = false,
/// An NTLM/Negotiate-based authentication request.
default: bool = false,
/// An SSH interactive authentication request
ssh_interactive: bool = false,
/// Username-only authentication request
///
/// Used as a pre-authentication step if the underlying transport (eg. SSH, with no username in its URL) does not know
/// which username to use.
username: bool = false,
/// An SSH key-based authentication request
///
/// Allows credentials to be read from memory instead of files.
/// Note that because of differences in crypto backend support, it might not be functional.
ssh_memory: bool = false,
z_padding: u25 = 0,
pub fn format(
value: CredentialType,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
return internal.formatWithoutFields(
value,
options,
writer,
&.{"z_padding"},
);
}
test {
try std.testing.expectEqual(@sizeOf(c_uint), @sizeOf(CredentialType));
try std.testing.expectEqual(@bitSizeOf(c_uint), @bitSizeOf(CredentialType));
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
}
|
src/credential.zig
|
const std = @import("std");
/// Entry in the param list
pub const Entry = struct {
key: []const u8,
value: []const u8,
};
/// Small radix trie used for routing
/// This radix trie works different from regular radix tries
/// as each node is made up from a piece rather than a singular character
pub fn Trie(comptime T: type) type {
return struct {
const Self = @This();
const max_params: usize = 10;
/// Node within the Trie, contains links to child nodes
/// also contains a path piece and whether it's a wildcard
const Node = struct {
childs: []*Node,
label: enum { none, all, param },
path: []const u8,
data: ?T,
};
/// Root node, which is '/'
root: Node = Node{
.childs = &.{},
.label = .none,
.path = "/",
.data = null,
},
size: usize = 0,
/// Result is an union which is returned when trying to find
/// from a path
const Result = union(ResultTag) {
none: void,
static: T,
with_params: struct {
data: T,
params: [max_params]Entry,
param_count: usize,
},
const ResultTag = enum { none, static, with_params };
};
/// Inserts new nodes based on the given path
/// `path`[0] must be '/'
pub fn insert(comptime self: *Self, comptime path: []const u8, comptime data: T) void {
if (path.len == 1 and path[0] == '/') {
self.root.data = data;
return;
}
if (path[0] != '/') @compileError("Path must start with /");
if (comptime std.mem.count(u8, path, ":") > max_params) @compileError("This path contains too many parameters");
comptime var it = std.mem.split(u8, path[1..], "/");
comptime var current = &self.root;
comptime {
loop: while (it.next()) |component| {
for (current.childs) |child| {
if (std.mem.eql(u8, child.path, component)) {
current = child;
continue :loop;
}
}
self.size += 1;
var new_node = Node{
.path = component,
.childs = &[_]*Node{},
.label = .none,
.data = null,
};
if (component.len > 0) {
new_node.label = switch (component[0]) {
':' => .param,
'*' => .all,
else => .none,
};
}
var childs: [current.childs.len + 1]*Node = undefined;
std.mem.copy(*Node, &childs, current.childs ++ [_]*Node{&new_node});
current.childs = &childs;
current = &new_node;
if (current.label == .all) break;
}
}
current.data = data;
}
/// Retrieves T based on the given path
/// when a wildcard such as * is found, it will return T
/// If a colon is found, it will add the path piece onto the param list
pub fn get(self: *Self, path: []const u8) Result {
if (path.len == 1) {
return .{ .static = self.root.data.? };
}
var params: [max_params]Entry = undefined;
var param_count: usize = 0;
var current = &self.root;
var it = std.mem.split(u8, path[1..], "/");
var index: usize = 0;
loop: while (it.next()) |component| {
index += component.len + 1;
for (current.childs) |child| {
if (std.mem.eql(u8, component, child.path) or child.label == .param or child.label == .all) {
if (child.label == .all) {
if (child.data == null) return .none;
var result = Result{
.with_params = .{
.data = child.data.?,
.params = undefined,
.param_count = param_count,
},
};
// Add the wildcard as param as well
// returns full result from wildcard onwards
params[param_count] = .{ .key = child.path, .value = path[index - component.len ..] };
std.mem.copy(Entry, &result.with_params.params, ¶ms);
return result;
}
if (child.label == .param) {
params[param_count] = .{ .key = child.path[1..], .value = component };
param_count += @boolToInt(param_count < max_params);
}
current = child;
continue :loop;
}
}
return .none;
}
if (current.data == null) return .none;
if (param_count == 0) return .{ .static = current.data.? };
var result = Result{
.with_params = .{
.data = current.data.?,
.params = undefined,
.param_count = param_count,
},
};
std.mem.copy(Entry, &result.with_params.params, ¶ms);
return result;
}
};
}
test "Insert and retrieve" {
comptime var trie = Trie(u32){};
comptime trie.insert("/posts/:id", 1);
comptime trie.insert("/messages/*", 2);
comptime trie.insert("/topics/:id/messages/:msg", 3);
comptime trie.insert("/topics/:id/*", 4);
comptime trie.insert("/bar", 5);
const res = trie.get("/posts/5");
const res2 = trie.get("/messages/bla");
const res2a = trie.get("/messages/bla/bla");
const res3 = trie.get("/topics/25/messages/20");
const res4 = trie.get("/foo");
const res5 = trie.get("/topics/5/foo");
const res6 = trie.get("/topics/5/");
const res7 = trie.get("/bar");
std.testing.expectEqual(@as(u32, 1), res.with_params.data);
std.testing.expectEqual(@as(u32, 2), res2.with_params.data);
std.testing.expectEqual(@as(u32, 2), res2a.with_params.data);
std.testing.expectEqual(@as(u32, 3), res3.with_params.data);
std.testing.expect(res4 == .none);
std.testing.expectEqual(@as(u32, 4), res5.with_params.data);
std.testing.expectEqual(@as(u32, 4), res6.with_params.data);
std.testing.expectEqual(@as(u32, 5), res7.static);
std.testing.expectEqualStrings("5", res.with_params.params[0].value);
std.testing.expectEqualStrings("bla", res2.with_params.params[0].value);
std.testing.expectEqualStrings("bla/bla", res2a.with_params.params[0].value);
std.testing.expectEqualStrings("25", res3.with_params.params[0].value);
std.testing.expectEqualStrings("20", res3.with_params.params[1].value);
std.testing.expectEqualStrings("5", res5.with_params.params[0].value);
std.testing.expectEqualStrings("foo", res5.with_params.params[1].value);
}
test "Insert and retrieve paths with same prefix" {
comptime var trie = Trie(u32){};
comptime trie.insert("/api", 1);
comptime trie.insert("/api/users", 2);
comptime trie.insert("/api/events", 3);
comptime trie.insert("/api/events/:id", 4);
const res = trie.get("/api");
const res2 = trie.get("/api/users");
const res3 = trie.get("/api/events");
const res4 = trie.get("/api/events/1337");
const res5 = trie.get("/foo");
const res6 = trie.get("/api/api/events");
std.testing.expectEqual(@as(u32, 1), res.static);
std.testing.expectEqual(@as(u32, 2), res2.static);
std.testing.expectEqual(@as(u32, 3), res3.static);
std.testing.expectEqual(@as(u32, 4), res4.with_params.data);
std.testing.expect(res5 == .none);
std.testing.expect(res6 == .none);
std.testing.expectEqualStrings("1337", res4.with_params.params[0].value);
}
|
src/trie.zig
|
const c = @cImport({
@cInclude("SDL.h");
});
const assert = @import("std").debug.assert;
// See https://github.com/zig-lang/zig/issues/565
// SDL_video.h:#define SDL_WINDOWPOS_UNDEFINED SDL_WINDOWPOS_UNDEFINED_DISPLAY(0)
// SDL_video.h:#define SDL_WINDOWPOS_UNDEFINED_DISPLAY(X) (SDL_WINDOWPOS_UNDEFINED_MASK|(X))
// SDL_video.h:#define SDL_WINDOWPOS_UNDEFINED_MASK 0x1FFF0000u
const SDL_WINDOWPOS_UNDEFINED = @bitCast(c_int, c.SDL_WINDOWPOS_UNDEFINED_MASK);
extern fn SDL_PollEvent(event: *c.SDL_Event) c_int;
// SDL_RWclose is fundamentally unrepresentable in Zig, because `ctx` is
// evaluated twice. One could make the case that this is a bug in SDL,
// especially since the docs list a real function prototype that would not
// have this double-evaluation of the parameter.
// If SDL would instead of a macro use a static inline function,
// it would resolve the SDL bug as well as make the function visible to Zig
// and to debuggers.
// SDL_rwops.h:#define SDL_RWclose(ctx) (ctx)->close(ctx)
inline fn SDL_RWclose(ctx: [*]c.SDL_RWops) c_int {
return ctx[0].close.?(ctx);
}
pub fn main() !void {
if (c.SDL_Init(c.SDL_INIT_VIDEO) != 0) {
c.SDL_Log(c"Unable to initialize SDL: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
}
defer c.SDL_Quit();
const screen = c.SDL_CreateWindow(c"My Game Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 300, 73, c.SDL_WINDOW_OPENGL) orelse
{
c.SDL_Log(c"Unable to create window: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyWindow(screen);
const renderer = c.SDL_CreateRenderer(screen, -1, 0) orelse {
c.SDL_Log(c"Unable to create renderer: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyRenderer(renderer);
const zig_bmp = @embedFile("zig.bmp");
const rw = c.SDL_RWFromConstMem(
@ptrCast(*const c_void, &zig_bmp[0]),
@intCast(c_int, zig_bmp.len),
);
if (rw == 0) {
c.SDL_Log(c"Unable to get RWFromConstMem: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
}
defer assert(SDL_RWclose(rw) == 0);
const zig_surface = c.SDL_LoadBMP_RW(rw, 0);
if (zig_surface == 0) {
c.SDL_Log(c"Unable to load bmp: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
}
defer c.SDL_FreeSurface(zig_surface);
const zig_texture = c.SDL_CreateTextureFromSurface(renderer, zig_surface) orelse {
c.SDL_Log(c"Unable to create texture from surface: %s", c.SDL_GetError());
return error.SDLInitializationFailed;
};
defer c.SDL_DestroyTexture(zig_texture);
var quit = false;
while (!quit) {
var event: c.SDL_Event = undefined;
while (SDL_PollEvent(&event) != 0) {
switch (event.@"type") {
c.SDL_QUIT => {
quit = true;
},
else => {},
}
}
_ = c.SDL_RenderClear(renderer);
_ = c.SDL_RenderCopy(renderer, zig_texture, 0, 0);
c.SDL_RenderPresent(renderer);
c.SDL_Delay(17);
}
}
|
example/main.zig
|
const std = @import("std");
const stdx = @import("stdx");
const builtin = @import("builtin");
const build_options = @import("build_options");
const string = stdx.string;
const graphics = @import("graphics");
const Graphics = graphics.Graphics;
const StdColor = graphics.Color;
const ds = stdx.ds;
const v8 = @import("v8");
const uv = @import("uv");
const h2o = @import("h2o");
const runtime = @import("runtime.zig");
const SizedJsString = runtime.SizedJsString;
const RuntimeContext = runtime.RuntimeContext;
const V8Context = runtime.V8Context;
const ContextBuilder = runtime.ContextBuilder;
const RuntimeValue = runtime.RuntimeValue;
const printFmt = runtime.printFmt;
const errorFmt = runtime.errorFmt;
const adapter = @import("adapter.zig");
const ManagedSlice = adapter.ManagedSlice;
const ManagedStruct = adapter.ManagedStruct;
const This = runtime.This;
const Data = runtime.Data;
const log = stdx.log.scoped(.js_env);
const tasks = @import("tasks.zig");
const work_queue = @import("work_queue.zig");
const TaskOutput = work_queue.TaskOutput;
const _server = @import("server.zig");
const HttpServer = _server.HttpServer;
const ResponseWriter = _server.ResponseWriter;
const api = @import("api.zig");
const cs_graphics = @import("api_graphics.zig").cs_graphics;
const cs_graphics_pkg = @import("api_graphics.zig");
const v8x = @import("v8x.zig");
// TODO: Implement fast api calls using CFunction. See include/v8-fast-api-calls.h
/// Initializes the js global context. Sets up modules and binds api functions.
/// A parent HandleScope should capture and clean up any redundant v8 vars created here.
pub fn initContext(rt: *RuntimeContext, iso: v8.Isolate) v8.Context {
const ctx = ContextBuilder{
.rt = rt,
.isolate = iso,
};
// We set with the same undef values for each type, it might help the optimizing compiler if it knows the field types ahead of time.
const undef_u32 = v8.Integer.initU32(iso, 0);
// GenericHandle
// First field is for the handle id.
// Second field is id*2 for setWeakFinalizer.
const handle_class = v8.Persistent(v8.ObjectTemplate).init(iso, v8.ObjectTemplate.initDefault(iso));
handle_class.inner.setInternalFieldCount(2);
rt.handle_class = handle_class;
// Runtime-context template.
// First field contains rt pointer.
// Second field contains a custom pointer or value.
// Used to create function data when the functions don't accept a user object param. eg. Promise fulfill/reject callbacks.
rt.rt_ctx_tmpl = iso.initPersistent(v8.ObjectTemplate, iso.initObjectTemplateDefault());
rt.rt_ctx_tmpl.inner.setInternalFieldCount(2);
// GenericObject
rt.default_obj_t = v8.Persistent(v8.ObjectTemplate).init(iso, v8.ObjectTemplate.initDefault(iso));
// JsWindow
const window_class = v8.Persistent(v8.FunctionTemplate).init(iso, v8.FunctionTemplate.initDefault(iso));
{
const inst = window_class.inner.getInstanceTemplate();
inst.setInternalFieldCount(1);
const proto = window_class.inner.getPrototypeTemplate();
ctx.setFuncT(proto, "onUpdate", api.cs_window.Window.onUpdate);
ctx.setFuncT(proto, "onMouseDown", api.cs_window.Window.onMouseDown);
ctx.setFuncT(proto, "onMouseUp", api.cs_window.Window.onMouseUp);
ctx.setFuncT(proto, "onMouseMove", api.cs_window.Window.onMouseMove);
ctx.setFuncT(proto, "onKeyDown", api.cs_window.Window.onKeyDown);
ctx.setFuncT(proto, "onKeyUp", api.cs_window.Window.onKeyUp);
ctx.setFuncT(proto, "onResize", api.cs_window.Window.onResize);
ctx.setFuncT(proto, "getGraphics", api.cs_window.Window.getGraphics);
ctx.setFuncT(proto, "getLastFrameDuration", api.cs_window.Window.getLastFrameDuration);
ctx.setFuncT(proto, "getLastUpdateDuration", api.cs_window.Window.getLastUpdateDuration);
ctx.setFuncT(proto, "getFps", api.cs_window.Window.getFps);
ctx.setFuncT(proto, "close", api.cs_window.Window.close);
ctx.setFuncT(proto, "minimize", api.cs_window.Window.minimize);
ctx.setFuncT(proto, "maximize", api.cs_window.Window.maximize);
ctx.setFuncT(proto, "restore", api.cs_window.Window.restore);
ctx.setFuncT(proto, "setFullscreenMode", api.cs_window.Window.setFullscreenMode);
ctx.setFuncT(proto, "setPseudoFullscreenMode", api.cs_window.Window.setPseudoFullscreenMode);
ctx.setFuncT(proto, "setWindowedMode", api.cs_window.Window.setWindowedMode);
ctx.setFuncT(proto, "createChild", api.cs_window.Window.createChild);
ctx.setFuncT(proto, "position", api.cs_window.Window.position);
ctx.setFuncT(proto, "center", api.cs_window.Window.center);
ctx.setFuncT(proto, "focus", api.cs_window.Window.focus);
ctx.setFuncT(proto, "getWidth", api.cs_window.Window.getWidth);
ctx.setFuncT(proto, "getHeight", api.cs_window.Window.getHeight);
ctx.setFuncT(proto, "setTitle", api.cs_window.Window.setTitle);
ctx.setFuncT(proto, "getTitle", api.cs_window.Window.getTitle);
ctx.setFuncT(proto, "resize", api.cs_window.Window.resize);
}
rt.window_class = window_class;
// JsGraphics
const graphics_class = v8.Persistent(v8.FunctionTemplate).init(iso, v8.FunctionTemplate.initDefault(iso));
graphics_class.inner.setClassName(v8.String.initUtf8(iso, "Graphics"));
{
const inst = graphics_class.inner.getInstanceTemplate();
inst.setInternalFieldCount(1);
const proto = graphics_class.inner.getPrototypeTemplate();
// NOTE: Accessors are callbacks anyway so it's probably not that much faster than a function call.
// Although, I have not explored if there exists a native binding to some memory location.
// For now, eep things consistent and use functions for fillColor/strokeColor/lineWidth. One less thing to gen docs for too.
// ctx.setAccessor(proto, "fillColor", Graphics.getFillColor, Graphics.setFillColor);
// ctx.setAccessor(proto, "strokeColor", Graphics.getStrokeColor, Graphics.setStrokeColor);
// ctx.setAccessor(proto, "lineWidth", Graphics.getLineWidth, Graphics.setLineWidth);
const Context = cs_graphics.Context;
ctx.setConstFuncT(proto, "defaultFont", Context.defaultFont);
ctx.setConstFuncT(proto, "fillColor", Context.fillColor);
ctx.setConstFuncT(proto, "getFillColor", Context.getFillColor);
ctx.setConstFuncT(proto, "strokeColor", Context.strokeColor);
ctx.setConstFuncT(proto, "getStrokeColor", Context.getStrokeColor);
ctx.setConstFuncT(proto, "lineWidth", Context.lineWidth);
ctx.setConstFuncT(proto, "getLineWidth", Context.getLineWidth);
ctx.setConstFuncT(proto, "rect", Context.rect);
ctx.setConstFuncT(proto, "rectOutline", Context.rectOutline);
ctx.setConstFuncT(proto, "translate", Context.translate);
ctx.setConstFuncT(proto, "scale", Context.scale);
ctx.setConstFuncT(proto, "rotate", Context.rotate);
ctx.setConstFuncT(proto, "rotateDeg", Context.rotateDeg);
ctx.setConstFuncT(proto, "resetTransform", Context.resetTransform);
ctx.setConstFuncT(proto, "pushState", Context.pushState);
ctx.setConstFuncT(proto, "popState", Context.popState);
ctx.setConstFuncT(proto, "getViewTransform", Context.getViewTransform);
ctx.setConstFuncT(proto, "newImage", Context.newImage);
ctx.setConstFuncT(proto, "addTtfFont", Context.addTtfFont);
ctx.setConstFuncT(proto, "addFallbackFont", Context.addFallbackFont);
ctx.setConstFuncT(proto, "font", Context.font);
ctx.setConstFuncT(proto, "fontSize", Context.fontSize);
ctx.setConstFuncT(proto, "textAlign", Context.textAlign);
ctx.setConstFuncT(proto, "textBaseline", Context.textBaseline);
ctx.setConstFuncT(proto, "text", Context.text);
ctx.setConstFuncT(proto, "circle", Context.circle);
ctx.setConstFuncT(proto, "circleSector", Context.circleSector);
ctx.setConstFuncT(proto, "circleSectorDeg", Context.circleSectorDeg);
ctx.setConstFuncT(proto, "circleOutline", Context.circleOutline);
ctx.setConstFuncT(proto, "circleArc", Context.circleArc);
ctx.setConstFuncT(proto, "circleArcDeg", Context.circleArcDeg);
ctx.setConstFuncT(proto, "ellipse", Context.ellipse);
ctx.setConstFuncT(proto, "ellipseSector", Context.ellipseSector);
ctx.setConstFuncT(proto, "ellipseSectorDeg", Context.ellipseSectorDeg);
ctx.setConstFuncT(proto, "ellipseOutline", Context.ellipseOutline);
ctx.setConstFuncT(proto, "ellipseArc", Context.ellipseArc);
ctx.setConstFuncT(proto, "ellipseArcDeg", Context.ellipseArcDeg);
ctx.setConstFuncT(proto, "triangle", Context.triangle);
ctx.setConstFuncT(proto, "convexPolygon", Context.convexPolygon);
ctx.setConstFuncT(proto, "polygon", Context.polygon);
ctx.setConstFuncT(proto, "polygonOutline", Context.polygonOutline);
ctx.setConstFuncT(proto, "roundRect", Context.roundRect);
ctx.setConstFuncT(proto, "roundRectOutline", Context.roundRectOutline);
ctx.setConstFuncT(proto, "point", Context.point);
ctx.setConstFuncT(proto, "line", Context.line);
ctx.setConstFuncT(proto, "svgContent", Context.svgContent);
ctx.setConstFuncT(proto, "compileSvgContent", Context.compileSvgContent);
ctx.setConstFuncT(proto, "executeDrawList", Context.executeDrawList);
ctx.setConstFuncT(proto, "quadraticBezierCurve", Context.quadraticBezierCurve);
ctx.setConstFuncT(proto, "cubicBezierCurve", Context.cubicBezierCurve);
ctx.setConstFuncT(proto, "imageSized", Context.imageSized);
if (builtin.mode == .Debug) {
ctx.setConstFuncT(proto, "debugTriangulatePolygon", cs_graphics_pkg.debugTriangulatePolygon);
ctx.setConstFuncT(proto, "debugTriangulateProcessNext", cs_graphics_pkg.debugTriangulateProcessNext);
}
if (build_options.has_lyon) {
ctx.setConstFuncT(proto, "executeDrawListLyon", cs_graphics_pkg.executeDrawListLyon);
}
if (build_options.has_tess2) {
ctx.setConstFuncT(proto, "executeDrawListTess2", cs_graphics_pkg.executeDrawListTess2);
}
}
rt.graphics_class = graphics_class;
// JsImage
const image_class = v8.Persistent(v8.FunctionTemplate).init(iso, ctx.initFuncT("Image"));
{
const inst = image_class.inner.getInstanceTemplate();
ctx.setProp(inst, "width", undef_u32);
ctx.setProp(inst, "height", undef_u32);
// For image id.
inst.setInternalFieldCount(1);
}
rt.image_class = image_class;
rt.transform_class = iso.initPersistent(v8.FunctionTemplate, iso.initFunctionTemplateDefault());
{
const proto = rt.transform_class.inner.getPrototypeTemplate();
ctx.setFuncT(proto, "interpolate", cs_graphics.Transform.interpolate);
}
// JsColor
const color_class = iso.initPersistent(v8.FunctionTemplate, iso.initFunctionTemplateDefault());
{
const proto = color_class.inner.getPrototypeTemplate();
ctx.setFuncT(proto, "darker", cs_graphics.Color.darker);
ctx.setFuncT(proto, "lighter", cs_graphics.Color.lighter);
ctx.setFuncT(proto, "withAlpha", cs_graphics.Color.withAlpha);
}
var instance = color_class.inner.getInstanceTemplate();
ctx.setProp(instance, "r", undef_u32);
ctx.setProp(instance, "g", undef_u32);
ctx.setProp(instance, "b", undef_u32);
ctx.setProp(instance, "a", undef_u32);
const Color = cs_graphics.Color;
const colors = &[_]std.meta.Tuple(&.{ []const u8, Color }){
.{ "lightGray", Color.lightGray },
.{ "gray", Color.gray },
.{ "darkGray", Color.darkGray },
.{ "yellow", Color.yellow },
.{ "gold", Color.gold },
.{ "orange", Color.orange },
.{ "pink", Color.pink },
.{ "red", Color.red },
.{ "maroon", Color.maroon },
.{ "green", Color.green },
.{ "lime", Color.lime },
.{ "darkGreen", Color.darkGreen },
.{ "skyBlue", Color.skyBlue },
.{ "blue", Color.blue },
.{ "royalBlue", Color.royalBlue },
.{ "darkBlue", Color.darkBlue },
.{ "purple", Color.purple },
.{ "violet", Color.violet },
.{ "darkPurple", Color.darkPurple },
.{ "beige", Color.beige },
.{ "brown", Color.brown },
.{ "darkBrown", Color.darkBrown },
.{ "white", Color.white },
.{ "black", Color.black },
.{ "transparent", Color.transparent },
.{ "magenta", Color.magenta },
};
inline for (colors) |it| {
ctx.setFuncGetter(color_class.inner, it.@"0", it.@"1");
}
rt.color_class = color_class;
const global_constructor = iso.initFunctionTemplateDefault();
global_constructor.setClassName(iso.initStringUtf8("Global"));
// Since Context.init only accepts ObjectTemplate, we can still name the global by using a FunctionTemplate as the constructor.
const global = v8.ObjectTemplate.init(iso, global_constructor);
// cs
const cs_constructor = iso.initFunctionTemplateDefault();
cs_constructor.setClassName(iso.initStringUtf8("cosmic"));
const cs = v8.ObjectTemplate.init(iso, cs_constructor);
// cs.window
const window_constructor = iso.initFunctionTemplateDefault();
window_constructor.setClassName(iso.initStringUtf8("window"));
const window = iso.initObjectTemplate(window_constructor);
ctx.setConstFuncT(window, "create", api.cs_window.create);
ctx.setConstProp(cs, "window", window);
// cs.files
const files_constructor = iso.initFunctionTemplateDefault();
files_constructor.setClassName(iso.initStringUtf8("files"));
const files = iso.initObjectTemplate(files_constructor);
ctx.setConstFuncT(files, "read", api.cs_files.read);
ctx.setConstFuncT(files, "readText", api.cs_files.readText);
ctx.setConstFuncT(files, "write", api.cs_files.write);
ctx.setConstFuncT(files, "writeText", api.cs_files.writeText);
ctx.setConstFuncT(files, "append", api.cs_files.append);
ctx.setConstFuncT(files, "appendText", api.cs_files.appendText);
ctx.setConstFuncT(files, "remove", api.cs_files.remove);
ctx.setConstFuncT(files, "ensurePath", api.cs_files.ensurePath);
ctx.setConstFuncT(files, "pathExists", api.cs_files.pathExists);
ctx.setConstFuncT(files, "removeDir", api.cs_files.removeDir);
ctx.setConstFuncT(files, "expandPath", api.cs_files.expandPath);
ctx.setConstFuncT(files, "realPath", api.cs_files.realPath);
ctx.setConstFuncT(files, "symLink", api.cs_files.symLink);
ctx.setConstFuncT(files, "copy", api.cs_files.copy);
ctx.setConstFuncT(files, "move", api.cs_files.move);
ctx.setConstFuncT(files, "cwd", api.cs_files.cwd);
ctx.setConstFuncT(files, "getPathInfo", api.cs_files.getPathInfo);
ctx.setConstFuncT(files, "listDir", api.cs_files.listDir);
// ctx.setConstFuncT(files, "openFile", files_OpenFile);
ctx.setConstProp(cs, "files", files);
ctx.setConstFuncT(files, "_readAsync", api.cs_files.readAsync);
ctx.setConstFuncT(files, "_readTextAsync", api.cs_files.readTextAsync);
ctx.setConstFuncT(files, "_writeAsync", api.cs_files.writeAsync);
ctx.setConstFuncT(files, "_writeTextAsync", api.cs_files.writeTextAsync);
ctx.setConstFuncT(files, "_appendAsync", api.cs_files.appendAsync);
ctx.setConstFuncT(files, "_appendTextAsync", api.cs_files.appendTextAsync);
ctx.setConstFuncT(files, "_removeAsync", api.cs_files.removeAsync);
ctx.setConstFuncT(files, "_removeDirAsync", api.cs_files.removeDirAsync);
ctx.setConstFuncT(files, "_ensurePathAsync", api.cs_files.ensurePathAsync);
ctx.setConstFuncT(files, "_pathExistsAsync", api.cs_files.pathExistsAsync);
ctx.setConstFuncT(files, "_copyAsync", api.cs_files.copyAsync);
ctx.setConstFuncT(files, "_moveAsync", api.cs_files.moveAsync);
ctx.setConstFuncT(files, "_getPathInfoAsync", api.cs_files.getPathInfoAsync);
ctx.setConstFuncT(files, "_listDirAsync", api.cs_files.listDirAsync);
// TODO: chmod op
const filekind = iso.initObjectTemplateDefault();
ctx.setProp(filekind, "blockDevice", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.blockDevice)));
ctx.setProp(filekind, "characterDevice", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.characterDevice)));
ctx.setProp(filekind, "directory", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.directory)));
ctx.setProp(filekind, "namedPipe", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.namedPipe)));
ctx.setProp(filekind, "symLink", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.symLink)));
ctx.setProp(filekind, "file", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.file)));
ctx.setProp(filekind, "unixDomainSocket", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.unixDomainSocket)));
ctx.setProp(filekind, "whiteout", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.whiteout)));
ctx.setProp(filekind, "door", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.door)));
ctx.setProp(filekind, "eventPort", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.eventPort)));
ctx.setProp(filekind, "unknown", iso.initIntegerU32(@enumToInt(api.cs_files.FileKind.unknown)));
ctx.setConstProp(files, "FileKind", filekind);
// cs.http
const http_constructor = iso.initFunctionTemplateDefault();
http_constructor.setClassName(iso.initStringUtf8("http"));
const http = iso.initObjectTemplate(http_constructor);
ctx.setConstFuncT(http, "get", api.cs_http.get);
ctx.setConstFuncT(http, "_getAsync", api.cs_http.getAsync);
ctx.setConstFuncT(http, "post", api.cs_http.post);
ctx.setConstFuncT(http, "_postAsync", api.cs_http.postAsync);
ctx.setConstFuncT(http, "_request", api.cs_http.request);
ctx.setConstFuncT(http, "_requestAsync", api.cs_http.requestAsync);
ctx.setConstFuncT(http, "serveHttp", api.cs_http.serveHttp);
ctx.setConstFuncT(http, "serveHttps", api.cs_http.serveHttps);
// cs.http.Response
const response_class = v8.FunctionTemplate.initDefault(iso);
response_class.setClassName(v8.String.initUtf8(iso, "Response"));
ctx.setConstProp(http, "Response", response_class);
rt.http_response_class = v8.Persistent(v8.FunctionTemplate).init(iso, response_class);
{
// cs.http.Server
const server_class = iso.initFunctionTemplateDefault();
server_class.setClassName(iso.initStringUtf8("Server"));
const inst = server_class.getInstanceTemplate();
inst.setInternalFieldCount(1);
const proto = server_class.getPrototypeTemplate();
ctx.setConstFuncT(proto, "setHandler", api.cs_http.Server.setHandler);
ctx.setConstFuncT(proto, "requestClose", api.cs_http.Server.requestClose);
ctx.setConstFuncT(proto, "closeAsync", api.cs_http.Server.closeAsync);
ctx.setConstFuncT(proto, "getBindAddress", api.cs_http.Server.getBindAddress);
ctx.setConstProp(http, "Server", server_class);
rt.http_server_class = v8.Persistent(v8.FunctionTemplate).init(iso, server_class);
}
{
// cs.http.ResponseWriter
const constructor = iso.initFunctionTemplateDefault();
constructor.setClassName(iso.initStringUtf8("ResponseWriter"));
const obj_t = iso.initObjectTemplate(constructor);
ctx.setConstFuncT(obj_t, "setStatus", api.cs_http.ResponseWriter.setStatus);
ctx.setConstFuncT(obj_t, "setHeader", api.cs_http.ResponseWriter.setHeader);
ctx.setConstFuncT(obj_t, "send", api.cs_http.ResponseWriter.send);
ctx.setConstFuncT(obj_t, "sendBytes", api.cs_http.ResponseWriter.sendBytes);
rt.http_response_writer = v8.Persistent(v8.ObjectTemplate).init(iso, obj_t);
}
ctx.setConstProp(cs, "http", http);
if (rt.is_test_env or builtin.is_test or rt.env.include_test_api) {
// cs.test
const cs_test = iso.initObjectTemplateDefault();
ctx.setConstFuncT(cs_test, "create", api.cs_test.create);
ctx.setConstFuncT(cs_test, "createIsolated", api.cs_test.createIsolated);
// ctx.setConstProp(cs, "asserts", cs_asserts);
ctx.setConstProp(cs, "test", cs_test);
}
// cs.graphics
{
const mod = v8.ObjectTemplate.initDefault(iso);
// cs.graphics.Color
ctx.setConstProp(mod, "Color", color_class.inner);
// cs.graphics.TextAlign
const text_align = iso.initObjectTemplateDefault();
ctx.setProp(text_align, "left", iso.initIntegerU32(@enumToInt(cs_graphics.TextAlign.left)));
ctx.setProp(text_align, "center", iso.initIntegerU32(@enumToInt(cs_graphics.TextAlign.center)));
ctx.setProp(text_align, "right", iso.initIntegerU32(@enumToInt(cs_graphics.TextAlign.right)));
ctx.setConstProp(mod, "TextAlign", text_align);
// cs.graphics.TextBaseline
const text_baseline = iso.initObjectTemplateDefault();
ctx.setProp(text_baseline, "top", iso.initIntegerU32(@enumToInt(cs_graphics.TextBaseline.top)));
ctx.setProp(text_baseline, "middle", iso.initIntegerU32(@enumToInt(cs_graphics.TextBaseline.middle)));
ctx.setProp(text_baseline, "alphabetic", iso.initIntegerU32(@enumToInt(cs_graphics.TextBaseline.alphabetic)));
ctx.setProp(text_baseline, "bottom", iso.initIntegerU32(@enumToInt(cs_graphics.TextBaseline.bottom)));
ctx.setConstProp(mod, "TextBaseline", text_baseline);
ctx.setConstFuncT(mod, "hsvToRgb", cs_graphics.hsvToRgb);
ctx.setConstProp(cs, "graphics", mod);
}
const rt_data = iso.initExternal(rt);
// cs.audio
const cs_audio = iso.initObjectTemplateDefault();
ctx.setConstFuncT(cs_audio, "loadWav", api.cs_audio.loadWav);
ctx.setConstFuncT(cs_audio, "loadWavFile", api.cs_audio.loadWavFile);
ctx.setConstFuncT(cs_audio, "loadMp3", api.cs_audio.loadMp3);
ctx.setConstFuncT(cs_audio, "loadMp3File", api.cs_audio.loadMp3File);
ctx.setConstFuncT(cs_audio, "loadFlac", api.cs_audio.loadFlac);
ctx.setConstFuncT(cs_audio, "loadFlacFile", api.cs_audio.loadFlacFile);
ctx.setConstFuncT(cs_audio, "loadOgg", api.cs_audio.loadOgg);
ctx.setConstFuncT(cs_audio, "loadOggFile", api.cs_audio.loadOggFile);
ctx.setConstFuncT(cs_audio, "load", api.cs_audio.load);
ctx.setConstFuncT(cs_audio, "loadFile", api.cs_audio.loadFile);
ctx.setConstFuncT(cs_audio, "getListenerPos", api.cs_audio.getListenerPos);
ctx.setConstFuncT(cs_audio, "setListenerPos", api.cs_audio.setListenerPos);
ctx.setConstFuncT(cs_audio, "getListenerDir", api.cs_audio.getListenerDir);
ctx.setConstFuncT(cs_audio, "setListenerDir", api.cs_audio.setListenerDir);
ctx.setConstFuncT(cs_audio, "getListenerUpDir", api.cs_audio.getListenerUpDir);
ctx.setConstFuncT(cs_audio, "setListenerUpDir", api.cs_audio.setListenerUpDir);
ctx.setConstFuncT(cs_audio, "getListenerVel", api.cs_audio.getListenerVel);
ctx.setConstFuncT(cs_audio, "setListenerVel", api.cs_audio.setListenerVel);
{
// Sound
const sound_class = iso.initPersistent(v8.ObjectTemplate, iso.initObjectTemplateDefault());
sound_class.inner.setInternalFieldCount(2);
ctx.setConstFuncT(sound_class.inner, "play", api.cs_audio.Sound.play);
ctx.setConstFuncT(sound_class.inner, "playBg", api.cs_audio.Sound.playBg);
ctx.setConstFuncT(sound_class.inner, "isPlayingBg", api.cs_audio.Sound.isPlayingBg);
ctx.setConstFuncT(sound_class.inner, "loopBg", api.cs_audio.Sound.loopBg);
ctx.setConstFuncT(sound_class.inner, "isLoopingBg", api.cs_audio.Sound.isLoopingBg);
ctx.setConstFuncT(sound_class.inner, "pauseBg", api.cs_audio.Sound.pauseBg);
ctx.setConstFuncT(sound_class.inner, "resumeBg", api.cs_audio.Sound.resumeBg);
ctx.setConstFuncT(sound_class.inner, "stopBg", api.cs_audio.Sound.stopBg);
ctx.setConstFuncT(sound_class.inner, "setVolume", api.cs_audio.Sound.setVolume);
ctx.setConstFuncT(sound_class.inner, "getVolume", api.cs_audio.Sound.getVolume);
ctx.setConstFuncT(sound_class.inner, "setGain", api.cs_audio.Sound.setGain);
ctx.setConstFuncT(sound_class.inner, "getGain", api.cs_audio.Sound.getGain);
ctx.setConstFuncT(sound_class.inner, "setPitch", api.cs_audio.Sound.setPitch);
ctx.setConstFuncT(sound_class.inner, "getPitch", api.cs_audio.Sound.getPitch);
ctx.setConstFuncT(sound_class.inner, "setPan", api.cs_audio.Sound.setPan);
ctx.setConstFuncT(sound_class.inner, "getPan", api.cs_audio.Sound.getPan);
ctx.setConstFuncT(sound_class.inner, "getLengthInPcmFrames", api.cs_audio.Sound.getLengthInPcmFrames);
ctx.setConstFuncT(sound_class.inner, "getLength", api.cs_audio.Sound.getLength);
ctx.setConstFuncT(sound_class.inner, "getCursorPcmFrame", api.cs_audio.Sound.getCursorPcmFrame);
ctx.setConstFuncT(sound_class.inner, "seekToPcmFrame", api.cs_audio.Sound.seekToPcmFrame);
ctx.setConstFuncT(sound_class.inner, "setPosition", api.cs_audio.Sound.setPosition);
ctx.setConstFuncT(sound_class.inner, "getPosition", api.cs_audio.Sound.getPosition);
ctx.setConstFuncT(sound_class.inner, "setDirection", api.cs_audio.Sound.setDirection);
ctx.setConstFuncT(sound_class.inner, "getDirection", api.cs_audio.Sound.getDirection);
ctx.setConstFuncT(sound_class.inner, "setVelocity", api.cs_audio.Sound.setVelocity);
ctx.setConstFuncT(sound_class.inner, "getVelocity", api.cs_audio.Sound.getVelocity);
ctx.setConstProp(cs_audio, "Sound", sound_class.inner);
rt.sound_class = sound_class;
}
ctx.setConstProp(cs, "audio", cs_audio);
if (rt.dev_mode) {
// cs.dev
const cs_dev = iso.initObjectTemplateDefault();
ctx.setConstFuncT(cs_dev, "hideHud", api.cs_dev.hideHud);
ctx.setConstFuncT(cs_dev, "showHud", api.cs_dev.showHud);
ctx.setConstProp(cs, "dev", cs_dev);
}
// cs.core
const cs_core = iso.initObjectTemplateDefault();
ctx.setConstFuncT(cs_core, "getCliArgs", api.cs_core.getCliArgs);
if (!rt.dev_mode) {
ctx.setConstProp(cs_core, "print", iso.initFunctionTemplateCallbackData(api.cs_core.print, rt_data));
ctx.setConstProp(cs_core, "puts", iso.initFunctionTemplateCallbackData(api.cs_core.puts, rt_data));
ctx.setConstProp(cs_core, "dump", iso.initFunctionTemplateCallbackData(api.cs_core.dump, rt_data));
} else {
ctx.setConstProp(cs_core, "print", iso.initFunctionTemplateCallbackData(api.cs_core.print_DEV, rt_data));
ctx.setConstProp(cs_core, "puts", iso.initFunctionTemplateCallbackData(api.cs_core.puts_DEV, rt_data));
ctx.setConstProp(cs_core, "dump", iso.initFunctionTemplateCallbackData(api.cs_core.dump_DEV, rt_data));
}
ctx.setConstFuncT(cs_core, "gets", api.cs_core.gets);
ctx.setConstFuncT(cs_core, "timerNow", api.cs_core.timerNow);
ctx.setConstFuncT(cs_core, "bufferToUtf8", api.cs_core.bufferToUtf8);
{
// Random
const random_class = iso.initPersistent(v8.ObjectTemplate, iso.initObjectTemplateDefault());
random_class.inner.setInternalFieldCount(2);
ctx.setConstFuncT(random_class.inner, "next", api.cs_core.Random.next);
ctx.setConstProp(cs_core, "Random", random_class.inner);
rt.random_class = random_class;
}
ctx.setConstFuncT(cs_core, "createRandom", api.cs_core.createRandom);
ctx.setConstFuncT(cs_core, "setTimeout", api.cs_core.setTimeout);
ctx.setConstFuncT(cs_core, "errCode", api.cs_core.errCode);
ctx.setConstFuncT(cs_core, "errString", api.cs_core.errString);
ctx.setConstFuncT(cs_core, "clearError", api.cs_core.clearError);
ctx.setConstFuncT(cs_core, "getMainScriptPath", api.cs_core.getMainScriptPath);
ctx.setConstFuncT(cs_core, "getMainScriptDir", api.cs_core.getMainScriptDir);
ctx.setConstFuncT(cs_core, "getAppDir", api.cs_core.getAppDir);
ctx.setConstFuncT(cs_core, "getClipboardText", api.cs_core.getClipboardText);
ctx.setConstFuncT(cs_core, "setClipboardText", api.cs_core.setClipboardText);
ctx.setConstFuncT(cs_core, "panic", api.cs_core.panic);
ctx.setConstFuncT(cs_core, "exit", api.cs_core.exit);
ctx.setConstFuncT(cs_core, "getOs", api.cs_core.getOs);
ctx.setConstFuncT(cs_core, "getOsVersion", api.cs_core.getOsVersion);
ctx.setConstFuncT(cs_core, "getCpu", api.cs_core.getCpu);
ctx.setConstFuncT(cs_core, "getResourceUsage", api.cs_core.getResourceUsage);
ctx.setConstFuncT(cs_core, "gc", api.cs_core.gc);
{
const cs_os = iso.initObjectTemplateDefault();
ctx.setProp(cs_os, "linux", iso.initIntegerU32(@enumToInt(api.cs_core.Os.linux)));
ctx.setProp(cs_os, "macos", iso.initIntegerU32(@enumToInt(api.cs_core.Os.macos)));
ctx.setProp(cs_os, "windows", iso.initIntegerU32(@enumToInt(api.cs_core.Os.windows)));
ctx.setProp(cs_os, "web", iso.initIntegerU32(@enumToInt(api.cs_core.Os.web)));
ctx.setConstProp(cs_core, "Os", cs_os);
}
{
const cs_err = iso.initObjectTemplateDefault();
ctx.setProp(cs_err, "NoError", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.NoError)));
ctx.setProp(cs_err, "FileNotFound", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.FileNotFound)));
ctx.setProp(cs_err, "PathExists", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.PathExists)));
ctx.setProp(cs_err, "IsDir", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.IsDir)));
ctx.setProp(cs_err, "ConnectFailed", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.ConnectFailed)));
ctx.setProp(cs_err, "CertVerify", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.CertVerify)));
ctx.setProp(cs_err, "CertBadFile", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.CertBadFile)));
ctx.setProp(cs_err, "CantResolveHost", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.CantResolveHost)));
ctx.setProp(cs_err, "InvalidFormat", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.InvalidFormat)));
ctx.setProp(cs_err, "Unsupported", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.Unsupported)));
ctx.setProp(cs_err, "Unknown", iso.initIntegerU32(@enumToInt(api.cs_core.CsError.Unknown)));
ctx.setConstProp(cs_core, "CsError", cs_err);
}
ctx.setConstProp(cs, "core", cs_core);
ctx.setConstProp(global, "cs", cs);
// cs.input
const cs_input = iso.initObjectTemplateDefault();
const mouse_button = iso.initObjectTemplateDefault();
ctx.setProp(mouse_button, "left", iso.initIntegerU32(@enumToInt(api.cs_input.MouseButton.left)));
ctx.setProp(mouse_button, "middle", iso.initIntegerU32(@enumToInt(api.cs_input.MouseButton.middle)));
ctx.setProp(mouse_button, "right", iso.initIntegerU32(@enumToInt(api.cs_input.MouseButton.right)));
ctx.setProp(mouse_button, "x1", iso.initIntegerU32(@enumToInt(api.cs_input.MouseButton.x1)));
ctx.setProp(mouse_button, "x2", iso.initIntegerU32(@enumToInt(api.cs_input.MouseButton.x2)));
ctx.setConstProp(cs_input, "MouseButton", mouse_button);
const key_obj = iso.initObjectTemplateDefault();
for (std.enums.values(api.cs_input.Key)) |key| {
ctx.setProp(key_obj, @tagName(key), iso.initIntegerU32(@enumToInt(key)));
}
ctx.setConstProp(cs_input, "Key", key_obj);
ctx.setConstProp(cs, "input", cs_input);
const res = iso.initContext(global, null);
// Attach rt pointer for callbacks that don't have user data. eg. ResolveModuleCallback
res.setEmbedderData(0, rt_data);
// const rt_global = res.getGlobal();
// const rt_cs = rt_global.getValue(res, v8.String.initUtf8(iso, "cs")).castToObject();
return res;
}
|
runtime/js_env.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const assert = std.debug.assert;
const leb = std.leb;
const mem = std.mem;
const wasm = std.wasm;
const Module = @import("../Module.zig");
const Decl = Module.Decl;
const ir = @import("../ir.zig");
const Inst = ir.Inst;
const Type = @import("../type.zig").Type;
const Value = @import("../value.zig").Value;
const Compilation = @import("../Compilation.zig");
const AnyMCValue = @import("../codegen.zig").AnyMCValue;
const LazySrcLoc = Module.LazySrcLoc;
/// Wasm Value, created when generating an instruction
const WValue = union(enum) {
none: void,
/// Index of the local variable
local: u32,
/// Instruction holding a constant `Value`
constant: *Inst,
/// Offset position in the list of bytecode instructions
code_offset: usize,
/// The label of the block, used by breaks to find its relative distance
block_idx: u32,
};
/// Hashmap to store generated `WValue` for each `Inst`
pub const ValueTable = std.AutoHashMapUnmanaged(*Inst, WValue);
/// Code represents the `Code` section of wasm that
/// belongs to a function
pub const Context = struct {
/// Reference to the function declaration the code
/// section belongs to
decl: *Decl,
gpa: *mem.Allocator,
/// Table to save `WValue`'s generated by an `Inst`
values: ValueTable,
/// `bytes` contains the wasm bytecode belonging to the 'code' section.
code: ArrayList(u8),
/// Contains the generated function type bytecode for the current function
/// found in `decl`
func_type_data: ArrayList(u8),
/// The index the next local generated will have
/// NOTE: arguments share the index with locals therefore the first variable
/// will have the index that comes after the last argument's index
local_index: u32 = 0,
/// If codegen fails, an error messages will be allocated and saved in `err_msg`
err_msg: *Module.ErrorMsg,
/// Current block depth. Used to calculate the relative difference between a break
/// and block
block_depth: u32 = 0,
/// List of all locals' types generated throughout this declaration
/// used to emit locals count at start of 'code' section.
locals: std.ArrayListUnmanaged(u8),
const InnerError = error{
OutOfMemory,
CodegenFail,
};
pub fn deinit(self: *Context) void {
self.values.deinit(self.gpa);
self.locals.deinit(self.gpa);
self.* = undefined;
}
/// Sets `err_msg` on `Context` and returns `error.CodegemFail` which is caught in link/Wasm.zig
fn fail(self: *Context, src: LazySrcLoc, comptime fmt: []const u8, args: anytype) InnerError {
const src_loc = src.toSrcLocWithDecl(self.decl);
self.err_msg = try Module.ErrorMsg.create(self.gpa, src_loc, fmt, args);
return error.CodegenFail;
}
/// Resolves the `WValue` for the given instruction `inst`
/// When the given instruction has a `Value`, it returns a constant instead
fn resolveInst(self: Context, inst: *Inst) WValue {
if (!inst.ty.hasCodeGenBits()) return .none;
if (inst.value()) |_| {
return WValue{ .constant = inst };
}
return self.values.get(inst).?; // Instruction does not dominate all uses!
}
/// Using a given `Type`, returns the corresponding wasm value type
fn genValtype(self: *Context, src: LazySrcLoc, ty: Type) InnerError!u8 {
return switch (ty.tag()) {
.f32 => wasm.valtype(.f32),
.f64 => wasm.valtype(.f64),
.u32, .i32, .bool => wasm.valtype(.i32),
.u64, .i64 => wasm.valtype(.i64),
else => self.fail(src, "TODO - Wasm genValtype for type '{s}'", .{ty.tag()}),
};
}
/// Using a given `Type`, returns the corresponding wasm value type
/// Differently from `genValtype` this also allows `void` to create a block
/// with no return type
fn genBlockType(self: *Context, src: LazySrcLoc, ty: Type) InnerError!u8 {
return switch (ty.tag()) {
.void, .noreturn => wasm.block_empty,
else => self.genValtype(src, ty),
};
}
/// Writes the bytecode depending on the given `WValue` in `val`
fn emitWValue(self: *Context, val: WValue) InnerError!void {
const writer = self.code.writer();
switch (val) {
.block_idx => unreachable,
.none, .code_offset => {},
.local => |idx| {
try writer.writeByte(wasm.opcode(.local_get));
try leb.writeULEB128(writer, idx);
},
.constant => |inst| try self.emitConstant(inst.castTag(.constant).?), // creates a new constant onto the stack
}
}
fn genFunctype(self: *Context) InnerError!void {
const ty = self.decl.typed_value.most_recent.typed_value.ty;
const writer = self.func_type_data.writer();
try writer.writeByte(wasm.function_type);
// param types
try leb.writeULEB128(writer, @intCast(u32, ty.fnParamLen()));
if (ty.fnParamLen() != 0) {
const params = try self.gpa.alloc(Type, ty.fnParamLen());
defer self.gpa.free(params);
ty.fnParamTypes(params);
for (params) |param_type| {
// Can we maybe get the source index of each param?
const val_type = try self.genValtype(.{ .node_offset = 0 }, param_type);
try writer.writeByte(val_type);
}
}
// return type
const return_type = ty.fnReturnType();
switch (return_type.tag()) {
.void, .noreturn => try leb.writeULEB128(writer, @as(u32, 0)),
else => |ret_type| {
try leb.writeULEB128(writer, @as(u32, 1));
// Can we maybe get the source index of the return type?
const val_type = try self.genValtype(.{ .node_offset = 0 }, return_type);
try writer.writeByte(val_type);
},
}
}
/// Generates the wasm bytecode for the function declaration belonging to `Context`
pub fn gen(self: *Context) InnerError!void {
assert(self.code.items.len == 0);
try self.genFunctype();
// Write instructions
// TODO: check for and handle death of instructions
const tv = self.decl.typed_value.most_recent.typed_value;
const mod_fn = blk: {
if (tv.val.castTag(.function)) |func| break :blk func.data;
if (tv.val.castTag(.extern_fn)) |ext_fn| return; // don't need codegen for extern functions
return self.fail(.{ .node_offset = 0 }, "TODO: Wasm codegen for decl type '{s}'", .{tv.ty.tag()});
};
// Reserve space to write the size after generating the code as well as space for locals count
try self.code.resize(10);
try self.genBody(mod_fn.body);
// finally, write our local types at the 'offset' position
{
leb.writeUnsignedFixed(5, self.code.items[5..10], @intCast(u32, self.locals.items.len));
// offset into 'code' section where we will put our locals types
var local_offset: usize = 10;
// emit the actual locals amount
for (self.locals.items) |local| {
var buf: [6]u8 = undefined;
leb.writeUnsignedFixed(5, buf[0..5], @as(u32, 1));
buf[5] = local;
try self.code.insertSlice(local_offset, &buf);
local_offset += 6;
}
}
const writer = self.code.writer();
try writer.writeByte(wasm.opcode(.end));
// Fill in the size of the generated code to the reserved space at the
// beginning of the buffer.
const size = self.code.items.len - 5 + self.decl.fn_link.wasm.?.idx_refs.items.len * 5;
leb.writeUnsignedFixed(5, self.code.items[0..5], @intCast(u32, size));
}
fn genInst(self: *Context, inst: *Inst) InnerError!WValue {
return switch (inst.tag) {
.add => self.genAdd(inst.castTag(.add).?),
.alloc => self.genAlloc(inst.castTag(.alloc).?),
.arg => self.genArg(inst.castTag(.arg).?),
.block => self.genBlock(inst.castTag(.block).?),
.breakpoint => self.genBreakpoint(inst.castTag(.breakpoint).?),
.br => self.genBr(inst.castTag(.br).?),
.call => self.genCall(inst.castTag(.call).?),
.cmp_eq => self.genCmp(inst.castTag(.cmp_eq).?, .eq),
.cmp_gte => self.genCmp(inst.castTag(.cmp_gte).?, .gte),
.cmp_gt => self.genCmp(inst.castTag(.cmp_gt).?, .gt),
.cmp_lte => self.genCmp(inst.castTag(.cmp_lte).?, .lte),
.cmp_lt => self.genCmp(inst.castTag(.cmp_lt).?, .lt),
.cmp_neq => self.genCmp(inst.castTag(.cmp_neq).?, .neq),
.condbr => self.genCondBr(inst.castTag(.condbr).?),
.constant => unreachable,
.dbg_stmt => WValue.none,
.load => self.genLoad(inst.castTag(.load).?),
.loop => self.genLoop(inst.castTag(.loop).?),
.not => self.genNot(inst.castTag(.not).?),
.ret => self.genRet(inst.castTag(.ret).?),
.retvoid => WValue.none,
.store => self.genStore(inst.castTag(.store).?),
.unreach => self.genUnreachable(inst.castTag(.unreach).?),
else => self.fail(inst.src, "TODO: Implement wasm inst: {s}", .{inst.tag}),
};
}
fn genBody(self: *Context, body: ir.Body) InnerError!void {
for (body.instructions) |inst| {
const result = try self.genInst(inst);
try self.values.putNoClobber(self.gpa, inst, result);
}
}
fn genRet(self: *Context, inst: *Inst.UnOp) InnerError!WValue {
// TODO: Implement tail calls
const operand = self.resolveInst(inst.operand);
try self.emitWValue(operand);
return .none;
}
fn genCall(self: *Context, inst: *Inst.Call) InnerError!WValue {
const func_inst = inst.func.castTag(.constant).?;
const func_val = inst.func.value().?;
const target = blk: {
if (func_val.castTag(.function)) |func| {
break :blk func.data.owner_decl;
} else if (func_val.castTag(.extern_fn)) |ext_fn| {
break :blk ext_fn.data;
}
return self.fail(inst.base.src, "Expected a function, but instead found type '{s}'", .{func_val.tag()});
};
for (inst.args) |arg| {
const arg_val = self.resolveInst(arg);
try self.emitWValue(arg_val);
}
try self.code.append(wasm.opcode(.call));
// The function index immediate argument will be filled in using this data
// in link.Wasm.flush().
try self.decl.fn_link.wasm.?.idx_refs.append(self.gpa, .{
.offset = @intCast(u32, self.code.items.len),
.decl = target,
});
return .none;
}
fn genAlloc(self: *Context, inst: *Inst.NoOp) InnerError!WValue {
const elem_type = inst.base.ty.elemType();
const valtype = try self.genValtype(inst.base.src, elem_type);
try self.locals.append(self.gpa, valtype);
defer self.local_index += 1;
return WValue{ .local = self.local_index };
}
fn genStore(self: *Context, inst: *Inst.BinOp) InnerError!WValue {
const writer = self.code.writer();
const lhs = self.resolveInst(inst.lhs);
const rhs = self.resolveInst(inst.rhs);
try self.emitWValue(rhs);
try writer.writeByte(wasm.opcode(.local_set));
try leb.writeULEB128(writer, lhs.local);
return .none;
}
fn genLoad(self: *Context, inst: *Inst.UnOp) InnerError!WValue {
return self.resolveInst(inst.operand);
}
fn genArg(self: *Context, inst: *Inst.Arg) InnerError!WValue {
// arguments share the index with locals
defer self.local_index += 1;
return WValue{ .local = self.local_index };
}
fn genAdd(self: *Context, inst: *Inst.BinOp) InnerError!WValue {
const lhs = self.resolveInst(inst.lhs);
const rhs = self.resolveInst(inst.rhs);
try self.emitWValue(lhs);
try self.emitWValue(rhs);
const opcode: wasm.Opcode = switch (inst.base.ty.tag()) {
.u32, .i32 => .i32_add,
.u64, .i64 => .i64_add,
.f32 => .f32_add,
.f64 => .f64_add,
else => return self.fail(inst.base.src, "TODO - Implement wasm genAdd for type '{s}'", .{inst.base.ty.tag()}),
};
try self.code.append(wasm.opcode(opcode));
return .none;
}
fn emitConstant(self: *Context, inst: *Inst.Constant) InnerError!void {
const writer = self.code.writer();
switch (inst.base.ty.tag()) {
.u32 => {
try writer.writeByte(wasm.opcode(.i32_const));
try leb.writeILEB128(writer, inst.val.toUnsignedInt());
},
.i32, .bool => {
try writer.writeByte(wasm.opcode(.i32_const));
try leb.writeILEB128(writer, inst.val.toSignedInt());
},
.u64 => {
try writer.writeByte(wasm.opcode(.i64_const));
try leb.writeILEB128(writer, inst.val.toUnsignedInt());
},
.i64 => {
try writer.writeByte(wasm.opcode(.i64_const));
try leb.writeILEB128(writer, inst.val.toSignedInt());
},
.f32 => {
try writer.writeByte(wasm.opcode(.f32_const));
// TODO: enforce LE byte order
try writer.writeAll(mem.asBytes(&inst.val.toFloat(f32)));
},
.f64 => {
try writer.writeByte(wasm.opcode(.f64_const));
// TODO: enforce LE byte order
try writer.writeAll(mem.asBytes(&inst.val.toFloat(f64)));
},
.void => {},
else => |ty| return self.fail(inst.base.src, "Wasm TODO: emitConstant for type {s}", .{ty}),
}
}
fn genBlock(self: *Context, block: *Inst.Block) InnerError!WValue {
const block_ty = try self.genBlockType(block.base.src, block.base.ty);
try self.startBlock(.block, block_ty, null);
block.codegen = .{
// we don't use relocs, so using `relocs` is illegal behaviour.
.relocs = undefined,
// Here we set the current block idx, so breaks know the depth to jump
// to when breaking out.
.mcv = @bitCast(AnyMCValue, WValue{ .block_idx = self.block_depth }),
};
try self.genBody(block.body);
try self.endBlock();
return .none;
}
/// appends a new wasm block to the code section and increases the `block_depth` by 1
fn startBlock(self: *Context, block_type: wasm.Opcode, valtype: u8, with_offset: ?usize) !void {
self.block_depth += 1;
if (with_offset) |offset| {
try self.code.insert(offset, wasm.opcode(block_type));
try self.code.insert(offset + 1, valtype);
} else {
try self.code.append(wasm.opcode(block_type));
try self.code.append(valtype);
}
}
/// Ends the current wasm block and decreases the `block_depth` by 1
fn endBlock(self: *Context) !void {
try self.code.append(wasm.opcode(.end));
self.block_depth -= 1;
}
fn genLoop(self: *Context, loop: *Inst.Loop) InnerError!WValue {
const loop_ty = try self.genBlockType(loop.base.src, loop.base.ty);
try self.startBlock(.loop, loop_ty, null);
try self.genBody(loop.body);
// breaking to the index of a loop block will continue the loop instead
try self.code.append(wasm.opcode(.br));
try leb.writeULEB128(self.code.writer(), @as(u32, 0));
try self.endBlock();
return .none;
}
fn genCondBr(self: *Context, condbr: *Inst.CondBr) InnerError!WValue {
const condition = self.resolveInst(condbr.condition);
const writer = self.code.writer();
// TODO: Handle death instructions for then and else body
// insert blocks at the position of `offset` so
// the condition can jump to it
const offset = switch (condition) {
.code_offset => |offset| offset,
else => blk: {
const offset = self.code.items.len;
try self.emitWValue(condition);
break :blk offset;
},
};
const block_ty = try self.genBlockType(condbr.base.src, condbr.base.ty);
try self.startBlock(.block, block_ty, offset);
// we inserted the block in front of the condition
// so now check if condition matches. If not, break outside this block
// and continue with the then codepath
try writer.writeByte(wasm.opcode(.br_if));
try leb.writeULEB128(writer, @as(u32, 0));
try self.genBody(condbr.else_body);
try self.endBlock();
// Outer block that matches the condition
try self.genBody(condbr.then_body);
return .none;
}
fn genCmp(self: *Context, inst: *Inst.BinOp, op: std.math.CompareOperator) InnerError!WValue {
const ty = inst.lhs.ty.tag();
// save offset, so potential conditions can insert blocks in front of
// the comparison that we can later jump back to
const offset = self.code.items.len;
const lhs = self.resolveInst(inst.lhs);
const rhs = self.resolveInst(inst.rhs);
try self.emitWValue(lhs);
try self.emitWValue(rhs);
const opcode_maybe: ?wasm.Opcode = switch (op) {
.lt => @as(?wasm.Opcode, switch (ty) {
.i32 => .i32_lt_s,
.u32 => .i32_lt_u,
.i64 => .i64_lt_s,
.u64 => .i64_lt_u,
.f32 => .f32_lt,
.f64 => .f64_lt,
else => null,
}),
.lte => @as(?wasm.Opcode, switch (ty) {
.i32 => .i32_le_s,
.u32 => .i32_le_u,
.i64 => .i64_le_s,
.u64 => .i64_le_u,
.f32 => .f32_le,
.f64 => .f64_le,
else => null,
}),
.eq => @as(?wasm.Opcode, switch (ty) {
.i32, .u32 => .i32_eq,
.i64, .u64 => .i64_eq,
.f32 => .f32_eq,
.f64 => .f64_eq,
else => null,
}),
.gte => @as(?wasm.Opcode, switch (ty) {
.i32 => .i32_ge_s,
.u32 => .i32_ge_u,
.i64 => .i64_ge_s,
.u64 => .i64_ge_u,
.f32 => .f32_ge,
.f64 => .f64_ge,
else => null,
}),
.gt => @as(?wasm.Opcode, switch (ty) {
.i32 => .i32_gt_s,
.u32 => .i32_gt_u,
.i64 => .i64_gt_s,
.u64 => .i64_gt_u,
.f32 => .f32_gt,
.f64 => .f64_gt,
else => null,
}),
.neq => @as(?wasm.Opcode, switch (ty) {
.i32, .u32 => .i32_ne,
.i64, .u64 => .i64_ne,
.f32 => .f32_ne,
.f64 => .f64_ne,
else => null,
}),
};
const opcode = opcode_maybe orelse
return self.fail(inst.base.src, "TODO - Wasm genCmp for type '{s}' and operator '{s}'", .{ ty, @tagName(op) });
try self.code.append(wasm.opcode(opcode));
return WValue{ .code_offset = offset };
}
fn genBr(self: *Context, br: *Inst.Br) InnerError!WValue {
// if operand has codegen bits we should break with a value
if (br.operand.ty.hasCodeGenBits()) {
const operand = self.resolveInst(br.operand);
try self.emitWValue(operand);
}
// every block contains a `WValue` with its block index.
// We then determine how far we have to jump to it by substracting it from current block depth
const wvalue = @bitCast(WValue, br.block.codegen.mcv);
const idx: u32 = self.block_depth - wvalue.block_idx;
const writer = self.code.writer();
try writer.writeByte(wasm.opcode(.br));
try leb.writeULEB128(writer, idx);
return .none;
}
fn genNot(self: *Context, not: *Inst.UnOp) InnerError!WValue {
const offset = self.code.items.len;
const operand = self.resolveInst(not.operand);
try self.emitWValue(operand);
// wasm does not have booleans nor the `not` instruction, therefore compare with 0
// to create the same logic
const writer = self.code.writer();
try writer.writeByte(wasm.opcode(.i32_const));
try leb.writeILEB128(writer, @as(i32, 0));
try writer.writeByte(wasm.opcode(.i32_eq));
return WValue{ .code_offset = offset };
}
fn genBreakpoint(self: *Context, breakpoint: *Inst.NoOp) InnerError!WValue {
// unsupported by wasm itself. Can be implemented once we support DWARF
// for wasm
return .none;
}
fn genUnreachable(self: *Context, unreach: *Inst.NoOp) InnerError!WValue {
try self.code.append(wasm.opcode(.@"unreachable"));
return .none;
}
};
|
src/codegen/wasm.zig
|
const aoc = @import("../aoc.zig");
const std = @import("std");
const TokenState = enum {
turn_toggle, on_off, start_coord, through, end_coord
};
const Command = enum {
turn_on, turn_off, toggle
};
const Light = struct {
p1: u1 = 0, p2: u8 = 0,
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var lights = [_]Light{ .{} } ** 1_000_000;
while (problem.line()) |line| {
var range = aoc.CoordRange2D.init();
var state = TokenState.turn_toggle;
var command: Command = undefined;
var tokens = std.mem.tokenize(u8, line, " ");
while (tokens.next()) |token| {
switch (state) {
.turn_toggle => {
if (std.mem.eql(u8, token, "turn")) {
state = .on_off;
}
else {
state = .start_coord;
command = .toggle;
}
},
.on_off => {
state = .start_coord;
command = if (std.mem.eql(u8, token, "on")) .turn_on else .turn_off;
},
.start_coord => {
range.amend(try parseCoord(token));
state = .through;
},
.through => { state = .end_coord; },
.end_coord => range.amend(try parseCoord(token)),
}
}
var iter = range.iterator();
while (iter.next()) |coord| {
var light = &lights[@intCast(usize, coord.y * 1000 + coord.x)];
switch (command) {
.turn_on => {light.p1 = 1; light.p2 += 1;},
.turn_off => {light.p1 = 0; if (light.p2 > 0) light.p2 -= 1;},
.toggle => {light.p1 ^= 1; light.p2 += 2;},
}
}
}
var lights_on: u32 = 0;
var brightness: u32 = 0;
for (lights) |light| {
lights_on += light.p1;
brightness += light.p2;
}
return problem.solution(lights_on, brightness);
}
fn parseCoord(token: []const u8) !aoc.Coord2D {
var vals = std.mem.tokenize(u8, token, ",");
return aoc.Coord2D.init(.{
try std.fmt.parseInt(u16, vals.next().?, 10),
try std.fmt.parseInt(u16, vals.next().?, 10)
});
}
|
src/main/zig/2015/day06.zig
|
const std = @import("std");
const utils = @import("utils");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const print = utils.print;
pub fn readInput(arena: *ArenaAllocator, lines_it: *utils.FileLineIterator) anyerror![][]const u8 {
var allocator = &arena.allocator;
var numbers = try std.ArrayList([]const u8).initCapacity(allocator, 4096);
while (lines_it.next()) |line| {
try numbers.append(line);
}
print("File ok :) Number of inputs: {d}", .{numbers.items.len});
return numbers.items;
}
pub fn part1(numbers: [][]const u8) i64 {
if (numbers.len == 0) {
return @intCast(i64, -1); // ???
}
var popcount = std.mem.zeroes([32]u32);
for (numbers) |number| {
for (number) |bit, index| {
if (bit == '1') {
popcount[index] += 1;
}
}
}
const num_size = numbers[0].len;
var gamma: u32 = 0;
var i: usize = 0;
while (i < num_size) : (i += 1) {
if (popcount[i] > numbers.len / 2) {
gamma = (gamma << 1) | 1;
} else {
gamma = gamma << 1;
}
}
var mask: u32 = 0;
for (numbers[0]) |_| {
mask = (mask << 1) | 1;
}
const epsilon = ~gamma & mask;
const power_consumption = gamma * epsilon;
return power_consumption;
}
const Strategy = enum { MostCommon, LeastCommon };
pub fn getRemainingNumber(arena: *ArenaAllocator, strategy: Strategy, numbers: [][]const u8) anyerror!i64 {
var allocator = &arena.allocator;
var remaining = try std.ArrayList(usize).initCapacity(allocator, numbers.len);
for (numbers) |_, i| {
remaining.appendAssumeCapacity(i);
}
var bitpos: usize = 0;
while (bitpos < numbers[0].len) : (bitpos += 1) {
var popcount: usize = 0;
var i: usize = 0;
for (remaining.items) |index| {
if (numbers[index][bitpos] == '1') {
popcount += 1;
}
}
var bit_to_keep: u8 = undefined;
if (strategy == Strategy.MostCommon and popcount >= (remaining.items.len - popcount)) {
bit_to_keep = '1';
} else if (strategy == Strategy.LeastCommon and popcount < (remaining.items.len - popcount)) {
bit_to_keep = '1';
} else {
bit_to_keep = '0';
}
var j: isize = 0;
while (j < remaining.items.len and remaining.items.len > 1) : (j += 1) {
i = @intCast(usize, j);
if (numbers[remaining.items[i]][bitpos] != bit_to_keep) {
_ = remaining.swapRemove(i);
//_ = remaining.orderedRemove(i);
j -= 1;
}
}
if (remaining.items.len == 1) {
break;
}
}
if (remaining.items.len == 1) {
const number = numbers[remaining.items[0]];
var integer: u32 = 0;
for (number) |bit| {
if (bit == '1') {
integer = (integer << 1) | 1;
} else {
integer = integer << 1;
}
}
return integer;
}
unreachable; // :)
}
pub fn part2(arena: *ArenaAllocator, numbers: [][]const u8) anyerror!i64 {
const oxygen_generator_rating = try getRemainingNumber(arena, Strategy.MostCommon, numbers);
const co2_scrubber_rating = try getRemainingNumber(arena, Strategy.LeastCommon, numbers);
return oxygen_generator_rating * co2_scrubber_rating;
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var lines_it = try utils.iterateLinesInFile(&arena.allocator, "input.txt");
defer lines_it.deinit();
const input = try readInput(&arena, &lines_it);
const part1_result = part1(input);
print("Part 1: {d}", .{part1_result});
const part2_result = try part2(&arena, input);
print("Part 2: {d}", .{part2_result});
}
|
day3/src/main.zig
|
const std = @import("std");
const vl = @import("value.zig");
const stack = @import("stack.zig");
const debug = @import("debug.zig");
const OpCode = @import("chunk.zig").OpCode;
const Chunk = @import("chunk.zig").Chunk;
const Value = vl.Value;
const Obj = vl.Obj;
const String = vl.String;
const Function = vl.Function;
const Closure = vl.Closure;
const Native = vl.Native;
const Upvalue = vl.Upvalue;
const Allocator = std.mem.Allocator;
const compile = @import("compiler.zig").compile;
// TODO remove me
// I think we possibly want an "ObjStore" object to manage this stuff
pub fn getAllocator() *Allocator {
return vm.allocator;
}
// TODO sort out error handling
pub const InterpretError = error{
Runtime,
Compilation,
};
const CallFrame = struct {
closure: *Closure,
ip: usize,
slots: []Value,
};
/// The lox virtual machine
const Vm = struct {
const Self = @This();
pub const Stack = stack.Stack(Value, 256);
pub const CallStack = stack.Stack(CallFrame, 64);
pub const Internment = std.StringHashMap(*Obj);
pub const Globals = std.AutoHashMap(*String, Value);
allocator: *std.mem.Allocator,
/// Stack of function calls
frames: CallStack,
/// Runtime stack of values
stack: Stack,
/// Global variables
globals: Globals,
/// Linked list of open upvalues
open_upvalues: ?*Upvalue,
/// Linked list of all objects
objects: ?*Obj,
/// Internment camp for all the strings in the lox program
strings: Internment,
};
var vm: Vm = undefined;
/// Create an object managed by the VM.
pub fn createObj(comptime T: type) !*T {
var ptr = try vm.allocator.create(T);
ptr.base = Obj{
.ty = T.base_type,
.next = vm.objects,
};
vm.objects = &ptr.base;
return ptr;
}
pub fn newFunction() !*Function {
const function = try createObj(Function);
function.arity = 0;
function.name = null;
function.chunk = Chunk.init(vm.allocator);
function.upvalue_count = undefined;
return function;
}
pub fn newClosure(func: *Function) !*Closure {
const closure = try createObj(Closure);
closure.function = func;
closure.upvalues = try vm.allocator.alloc(?*Upvalue, @intCast(usize, func.upvalue_count));
for (closure.upvalues) |*upvalue| {
upvalue.* = null;
}
return closure;
}
pub fn newUpvalue(slot: *Value) !*Upvalue {
const upvalue = try createObj(Upvalue);
upvalue.location = slot;
upvalue.next = null;
upvalue.closed = .nil;
return upvalue;
}
pub fn createString(chars: []const u8) !*Obj {
var interned = vm.strings.get(chars);
if (interned != null) {
return interned.?;
} else {
var duped = try vm.allocator.dupe(u8, chars);
errdefer vm.allocator.free(duped);
var obj = try createStringNoDupe(duped);
try vm.strings.putNoClobber(duped, obj);
return obj;
}
}
fn createStringNoDupe(chars: []const u8) !*Obj {
var obj = try createObj(String);
obj.chars = chars;
return &obj.base;
}
/// Free an object managed by the VM
pub fn destroyObj(obj: *Obj) void {
vm.allocator.destroy(obj);
}
/// Free the allocated memebers of a managed object
pub fn deallocateObj(obj: *Obj) void {
switch (obj.ty) {
.string => {
const string = obj.cast(String).?;
vm.allocator.free(string.chars);
},
.function => {
const function = obj.cast(Function).?;
function.chunk.deinit();
},
.closure => {
const closure = obj.cast(Closure).?;
vm.allocator.free(closure.upvalues);
},
.native,
.upvalue,
=> {
// Nothing to do
},
}
}
pub fn init(allocator: *Allocator) !void {
vm.allocator = allocator;
vm.frames = .{};
vm.stack = .{};
vm.open_upvalues = null;
vm.objects = null;
vm.strings = Vm.Internment.init(allocator);
vm.globals = Vm.Globals.init(allocator);
try defineNative("clock", clockNative);
}
pub fn deinit() void {
vm.strings.deinit();
vm.globals.deinit();
var obj = vm.objects;
while (obj != null) {
var next = obj.?.next;
deallocateObj(obj.?);
destroyObj(obj.?);
obj = next;
}
}
pub fn interpret(source_code: []const u8) !void {
std.debug.assert(vm.stack.top == 0);
defer std.debug.assert(vm.stack.top == 0);
errdefer vm.stack.top = 0;
const func = try compile(vm.allocator, source_code);
vm.stack.push(Value{ .obj = &func.base });
const closure = try newClosure(func);
_ = vm.stack.pop();
vm.stack.push(Value{ .obj = &closure.base });
try callValue(Value{ .obj = &closure.base }, 0);
try run();
}
fn readByte(frame: *CallFrame) u8 {
const result = frame.closure.function.chunk.code.items[frame.ip];
frame.ip += 1;
return result;
}
fn readShort(frame: *CallFrame) u16 {
var result: u16 = @as(u16, frame.closure.function.chunk.code.items[frame.ip]) << 8;
result |= frame.closure.function.chunk.code.items[frame.ip + 1];
frame.ip += 2;
return result;
}
fn readConstant(frame: *CallFrame) Value {
return frame.closure.function.chunk.constants.items[readByte(frame)];
}
fn binaryOp(comptime ops: anytype, comptime op_name: []const u8) !void {
const Dispatcher = struct {
const CheckFn = fn (Value.Type, Value.Type) bool;
const ExecuteFn = fn (Value, Value) Op.Error!Value;
check: CheckFn,
execute: ExecuteFn,
fn makeCheck(comptime Ta: type, comptime Tb: type) CheckFn {
const C = struct {
fn check(a: Value.Type, b: Value.Type) bool {
switch (Ta) {
f64 => if (a != .number) return false,
bool => if (a != .boolean) return false,
[]const u8 => if (a != .string) return false,
else => unreachable,
}
switch (Tb) {
f64 => return b == .number,
bool => return b == .boolean,
[]const u8 => return b == .string,
else => unreachable,
}
}
};
return C.check;
}
fn makeExecute(comptime op: anytype, comptime Ta: type, comptime Tb: type, comptime R: type) ExecuteFn {
const C = struct {
fn execute(a: Value, b: Value) Op.Error!Value {
const a_inner = a.cast(Ta).?;
const b_inner = b.cast(Tb).?;
switch (R) {
f64 => return Value{ .number = try op(a_inner, b_inner) },
bool => return Value{ .boolean = try op(a_inner, b_inner) },
[]const u8 => {
const chars = try op(a_inner, b_inner);
errdefer vm.allocator.free(chars);
var interned = vm.strings.get(chars);
if (interned != null) {
vm.allocator.free(chars);
return Value{ .obj = interned.? };
} else {
var obj = try createStringNoDupe(chars);
try vm.strings.putNoClobber(chars, obj);
return Value{ .obj = obj };
}
},
else => unreachable,
}
}
};
return C.execute;
}
};
const ops_info = @typeInfo(@TypeOf(ops)).Struct;
const dispatchers = blk: {
var disps: [ops_info.fields.len]Dispatcher = undefined;
inline for (ops) |op, i| {
const fn_info = @typeInfo(@TypeOf(op)).Fn;
const args = fn_info.args;
const Ta = args[0].arg_type.?;
const Tb = args[1].arg_type.?;
const R = @typeInfo(fn_info.return_type.?).ErrorUnion.payload;
disps[i] = .{
.check = Dispatcher.makeCheck(Ta, Tb),
.execute = Dispatcher.makeExecute(op, Ta, Tb, R),
};
}
break :blk disps;
};
const b = vm.stack.pop();
const a = vm.stack.pop();
for (dispatchers) |d| {
if (d.check(a.ty(), b.ty())) {
vm.stack.push(try d.execute(a, b));
return;
}
}
try runtimeError("Binary operator '{}' not supported for types '{}' and '{}'", .{
op_name,
a.ty(),
b.ty(),
});
return InterpretError.Runtime;
}
fn callValue(callee: Value, arg_count: u8) !void {
if (callee.cast(*Closure)) |closure| {
const func = closure.function;
if (arg_count != func.arity) {
try runtimeError("Expected {} arguments but got {}.", .{ func.arity, arg_count });
return InterpretError.Runtime;
}
if (vm.frames.full()) {
try runtimeError("Stack overflow.", .{});
return InterpretError.Runtime;
}
vm.frames.push(CallFrame{
.closure = closure,
.ip = 0,
.slots = vm.stack.buffer[vm.stack.top - arg_count - 1 ..],
});
} else if (callee.cast(*Native)) |native| {
const result = native.function(vm.stack.buffer[vm.stack.top - arg_count - 1 ..]);
vm.stack.top -= arg_count + 1;
vm.stack.push(result);
} else {
try runtimeError("Can only call functions and classes.", .{});
return InterpretError.Runtime;
}
}
fn captureUpvalue(local: *Value) !*Upvalue {
const last = @ptrToInt(local) - @ptrToInt(&vm.stack.buffer[0]);
var prev: ?*Upvalue = null;
var next: ?*Upvalue = vm.open_upvalues;
while (next) |upvalue| {
var loc = @ptrToInt(upvalue.location) - @ptrToInt(&vm.stack.buffer[0]);
if (loc / @sizeOf(Upvalue) <= last) break;
prev = next;
next = upvalue.next;
}
if (next != null and next.?.location == local) {
return next.?;
}
var new = try newUpvalue(local);
new.next = next;
if (prev) |upvalue| {
upvalue.next = new;
} else {
vm.open_upvalues = new;
}
return new;
}
fn closeUpvalues(last: usize) !void {
while (vm.open_upvalues) |upvalue| {
var loc = @ptrToInt(upvalue.location) - @ptrToInt(&vm.stack.buffer[0]);
if (loc / @sizeOf(Upvalue) < last) break;
upvalue.closed = upvalue.location.*;
upvalue.location = &upvalue.closed;
vm.open_upvalues = upvalue.next;
}
}
fn run() !void {
const stdout = std.io.getStdOut().writer();
var frame = vm.frames.peek(0);
while (true) {
if (debug.trace_execution) {
const top = (@ptrToInt(&vm.stack.buffer[vm.stack.top]) -
@ptrToInt(&frame.slots[0])) / @sizeOf(Value);
const stack_values = frame.slots[0..top];
try stdout.print(" IP = {x:0>4}", .{frame.ip});
try debug.dumpValueStack(stdout, stack_values);
_ = try debug.disassembleInstruction(stdout, &frame.closure.function.chunk, frame.ip, false);
}
const instruction = @intToEnum(OpCode, readByte(frame));
switch (instruction) {
.return_ => {
const result = vm.stack.pop();
const new_top = (@ptrToInt(frame.slots.ptr) - @ptrToInt(&vm.stack.buffer[0])) / @sizeOf(Value);
try closeUpvalues(new_top);
_ = vm.frames.pop();
if (vm.frames.empty()) {
_ = vm.stack.pop();
return;
}
vm.stack.top = new_top;
vm.stack.push(result);
frame = vm.frames.peek(0);
},
.pop => _ = vm.stack.pop(),
.close_upvalue => {
try closeUpvalues(vm.stack.top - 1);
_ = vm.stack.pop();
},
.print => {
const v = vm.stack.pop();
try stdout.print("{}\n", .{v});
},
.constant => {
const v = readConstant(frame);
vm.stack.push(v);
},
.closure => {
const function = readConstant(frame).cast(*Function).?;
const closure = try newClosure(function);
vm.stack.push(Value{ .obj = &closure.base });
for (closure.upvalues) |*upvalue| {
var is_local = readByte(frame);
var index = readByte(frame);
if (is_local != 0) {
upvalue.* = try captureUpvalue(&frame.slots[index]);
} else {
upvalue.* = frame.closure.upvalues[index];
}
}
},
.define_global => {
const name = readConstant(frame).cast(*String).?;
try vm.globals.put(name, vm.stack.pop());
},
.get_local => {
const slot = readByte(frame);
vm.stack.push(frame.slots[slot]);
},
.get_global => {
const name = readConstant(frame).cast(*String).?;
const value = vm.globals.get(name);
if (value) |v| {
vm.stack.push(v);
} else {
try runtimeError("Undefined variable '{}'", .{name.chars});
return InterpretError.Runtime;
}
},
.set_local => {
const slot = readByte(frame);
frame.slots[slot] = vm.stack.peek(0).*;
},
.set_global => {
const name = readConstant(frame).cast(*String).?;
const entry = vm.globals.getEntry(name);
if (entry) |e| {
e.value = vm.stack.peek(0).*;
} else {
try runtimeError("Undefined variable '{}'", .{name.chars});
return InterpretError.Runtime;
}
},
.get_upvalue => {
var slot = readByte(frame);
vm.stack.push(frame.closure.upvalues[slot].?.location.*);
},
.set_upvalue => {
var slot = readByte(frame);
frame.closure.upvalues[slot].?.location.* = vm.stack.peek(0).*;
},
.call => {
const arg_count = readByte(frame);
try callValue(vm.stack.peek(arg_count).*, arg_count);
frame = vm.frames.peek(0);
},
.negate => {
if (vm.stack.peek(0).* != .number) {
try runtimeError("Operand must be a number", .{});
return InterpretError.Runtime;
}
var operand = vm.stack.pop().number;
var result = Value{ .number = -operand };
vm.stack.push(result);
},
.not => {
var operand = vm.stack.pop();
var result = Value{ .boolean = isFalsey(operand) };
vm.stack.push(result);
},
.false_ => vm.stack.push(Value{ .boolean = false }),
.true_ => vm.stack.push(Value{ .boolean = true }),
.nil => vm.stack.push(Value.nil),
.add => try binaryOp(.{ Op.add, Op.concat }, "+"),
.subtract => try binaryOp(.{Op.subtract}, "-"),
.multiply => try binaryOp(.{Op.multiply}, "*"),
.divide => try binaryOp(.{Op.divide}, "/"),
.equal => {
var b = vm.stack.pop();
var a = vm.stack.pop();
vm.stack.push(Value{ .boolean = vl.equal(a, b) });
},
.not_equal => {
var b = vm.stack.pop();
var a = vm.stack.pop();
vm.stack.push(Value{ .boolean = !vl.equal(a, b) });
},
.greater => try binaryOp(.{Op.greater}, ">"),
.greater_equal => try binaryOp(.{Op.greaterEqual}, ">="),
.less => try binaryOp(.{Op.less}, "<"),
.less_equal => try binaryOp(.{Op.lessEqual}, "<="),
.jump_if_false => {
const offset = readShort(frame);
if (isFalsey(vm.stack.peek(0).*)) {
frame.ip += offset;
}
},
.jump_if_true => {
const offset = readShort(frame);
if (!isFalsey(vm.stack.peek(0).*)) {
frame.ip += offset;
}
},
.jump => {
const offset = readShort(frame);
frame.ip += offset;
},
.loop => {
const offset = readShort(frame);
frame.ip -= offset;
},
}
}
}
fn runtimeError(comptime fmt: []const u8, args: anytype) !void {
const stderr = std.io.getStdErr().writer();
try stderr.print(fmt, args);
try stderr.print("\n", .{});
var i = @intCast(isize, vm.frames.top) - 1;
while (i >= 0) : (i -= 1) {
const frame = vm.frames.peek(@intCast(usize, i));
const func = frame.closure.function;
const line = func.chunk.lines.items[frame.ip];
try stderr.print(
"[line {}] in {}\n",
.{ line, if (func.name != null) func.name.?.chars else "script" },
);
}
vm.stack.reset();
vm.frames.reset();
vm.open_upvalues = null;
}
fn isFalsey(a: Value) bool {
switch (a) {
.nil => return true,
.boolean => |b| return !b,
else => return false,
}
}
fn defineNative(name: []const u8, func: Native.Fn) !void {
vm.stack.push(Value{ .obj = try createString(name) });
var native = try createObj(Native);
native.function = func;
vm.stack.push(Value{ .obj = &native.base });
try vm.globals.put(vm.stack.peek(1).cast(*String).?, vm.stack.peek(0).*);
_ = vm.stack.pop();
_ = vm.stack.pop();
}
fn clockNative(args: []Value) Value {
var ts: std.os.timespec = undefined;
std.os.clock_gettime(std.os.CLOCK_MONOTONIC, &ts) catch |_| {};
var time = @intToFloat(f64, ts.tv_sec);
time += @intToFloat(f64, ts.tv_nsec) * 1e-9;
return Value{ .number = time };
}
const Op = struct {
const Error = error{OutOfMemory};
fn concat(a: []const u8, b: []const u8) Error![]const u8 {
return try std.mem.concat(
vm.allocator,
u8,
&[_][]const u8{ a, b },
);
}
fn add(a: f64, b: f64) Error!f64 {
return a + b;
}
fn subtract(a: f64, b: f64) Error!f64 {
return a - b;
}
fn multiply(a: f64, b: f64) Error!f64 {
return a * b;
}
fn divide(a: f64, b: f64) Error!f64 {
return a / b;
}
fn greater(a: f64, b: f64) Error!bool {
return a > b;
}
fn less(a: f64, b: f64) Error!bool {
return a < b;
}
fn greaterEqual(a: f64, b: f64) Error!bool {
return a >= b;
}
fn lessEqual(a: f64, b: f64) Error!bool {
return a <= b;
}
};
|
src/vm.zig
|
const std = @import("std");
const testing = std.testing;
const allocator = std.heap.page_allocator;
pub const Map = struct {
const OFFSET = 1000;
space: Space,
min: Pos,
max: Pos,
cells: [2]std.AutoHashMap(Pos, Tile),
curr: usize,
next: usize,
pub const Space = enum {
Dim3,
Dim4,
};
pub const Tile = enum {
Active,
Inactive,
};
pub const Pos = struct {
x: usize,
y: usize,
z: usize,
w: usize,
pub fn init(x: usize, y: usize, z: usize, w: usize) Pos {
return Pos{
.x = x,
.y = y,
.z = z,
.w = w,
};
}
};
pub fn init(space: Space) Map {
var self = Map{
.space = space,
.min = Pos.init(OFFSET, OFFSET, OFFSET, OFFSET),
.max = Pos.init(OFFSET, OFFSET, OFFSET, OFFSET),
.cells = undefined,
.curr = 0,
.next = 1,
};
self.cells[0] = std.AutoHashMap(Pos, Tile).init(allocator);
self.cells[1] = std.AutoHashMap(Pos, Tile).init(allocator);
return self;
}
pub fn deinit(self: *Map) void {
self.cells[1].deinit();
self.cells[0].deinit();
}
pub fn add_line(self: *Map, line: []const u8) void {
if (self.max.x == OFFSET) {
self.max.x = OFFSET + line.len;
}
if (self.max.x != OFFSET + line.len) {
@panic("jagged map");
}
var x: usize = 0;
while (x < self.max.x - OFFSET) : (x += 1) {
const tile = switch (line[x]) {
'#' => Tile.Active,
'.' => Tile.Inactive,
else => @panic("TILE"),
};
if (tile == Tile.Inactive) continue;
const pos = Pos.init(OFFSET + x, self.max.y, OFFSET, OFFSET);
_ = self.cells[self.curr].put(pos, tile) catch unreachable;
}
self.max.y += 1;
if (self.max.z == OFFSET) self.max.z += 1;
if (self.max.w == OFFSET) self.max.w += 1;
}
pub fn show(self: Map) void {
std.debug.warn("MAP: {} x {} x {} x {} -- {} active\n", .{ self.max.x - self.min.x, self.max.y - self.min.y, self.max.z - self.min.z, self.max.w - self.min.w, self.count_active() });
var w: usize = self.min.w;
while (w < self.max.w) : (w += 1) {
var z: usize = self.min.z;
while (z < self.max.z) : (z += 1) {
std.debug.warn("z={}, w={}\n", .{ z, w });
var y: usize = self.min.y;
while (y < self.max.y) : (y += 1) {
std.debug.warn("{:4} | ", .{y});
var x: usize = self.min.x;
while (x < self.max.x) : (x += 1) {
var label: u8 = '.';
const pos = Pos.init(x, y, z, w);
const found = self.cells[self.curr].get(pos);
if (found) |t| {
label = switch (t) {
Tile.Active => '#',
Tile.Inactive => '.',
};
}
std.debug.warn("{c}", .{label});
}
std.debug.warn("\n", .{});
}
}
}
}
pub fn count_active(self: Map) usize {
var count: usize = 0;
var w: usize = self.min.w;
while (w < self.max.w) : (w += 1) {
var z: usize = self.min.z;
while (z < self.max.z) : (z += 1) {
var y: usize = self.min.y;
while (y < self.max.y) : (y += 1) {
var x: usize = self.min.x;
while (x < self.max.x) : (x += 1) {
const pos = Pos.init(x, y, z, w);
if (!self.cells[self.curr].contains(pos)) continue;
const tile = self.cells[self.curr].get(pos).?;
if (tile != Tile.Active) continue;
count += 1;
}
}
}
}
return count;
}
pub fn run(self: *Map, cycles: usize) usize {
var c: usize = 0;
while (c < cycles) : (c += 1) {
self.step();
}
return self.count_active();
}
pub fn step(self: *Map) void {
var min: Pos = self.min;
var max: Pos = self.max;
var minw = self.min.w;
var maxw = self.max.w;
if (self.space == .Dim4) {
minw -= 1;
maxw += 1;
}
var w: usize = minw;
while (w < maxw) : (w += 1) {
var z: usize = self.min.z - 1;
while (z < self.max.z + 1) : (z += 1) {
var y: usize = self.min.y - 1;
while (y < self.max.y + 1) : (y += 1) {
var x: usize = self.min.x - 1;
while (x < self.max.x + 1) : (x += 1) {
const pos = Pos.init(x, y, z, w);
if (self.cells[self.next].contains(pos)) {
_ = self.cells[self.next].remove(pos);
}
var old = Tile.Inactive;
if (self.cells[self.curr].contains(pos)) {
old = self.cells[self.curr].get(pos).?;
}
const occupied = self.countAround(pos);
var new = old;
if (old == Tile.Active and (occupied < 2 or occupied > 3)) {
new = Tile.Inactive;
}
if (old == Tile.Inactive and (occupied == 3)) {
new = Tile.Active;
}
// std.debug.warn("AROUND {} = {}, {} => {}\n", .{ pos, occupied, old, new });
if (new == Tile.Inactive) continue;
_ = self.cells[self.next].put(pos, new) catch unreachable;
if (min.x > pos.x) min.x = pos.x;
if (min.y > pos.y) min.y = pos.y;
if (min.z > pos.z) min.z = pos.z;
if (min.w > pos.w) min.w = pos.w;
if (max.x <= pos.x) max.x = pos.x + 1;
if (max.y <= pos.y) max.y = pos.y + 1;
if (max.z <= pos.z) max.z = pos.z + 1;
if (max.w <= pos.w) max.w = pos.w + 1;
}
}
}
}
self.min = min;
self.max = max;
self.curr = 1 - self.curr;
self.next = 1 - self.next;
}
fn countAround(self: *Map, pos: Pos) usize {
var count: usize = 0;
var dw: isize = -1;
while (dw <= 1) : (dw += 1) {
var dz: isize = -1;
while (dz <= 1) : (dz += 1) {
var dy: isize = -1;
while (dy <= 1) : (dy += 1) {
var dx: isize = -1;
while (dx <= 1) : (dx += 1) {
if (dy == 0 and dx == 0 and dz == 0 and dw == 0) continue;
var sx = @intCast(isize, pos.x);
var sy = @intCast(isize, pos.y);
var sz = @intCast(isize, pos.z);
var sw = @intCast(isize, pos.w);
sx += dx;
sy += dy;
sz += dz;
sw += dw;
const nx = @intCast(usize, sx);
const ny = @intCast(usize, sy);
const nz = @intCast(usize, sz);
const nw = @intCast(usize, sw);
const np = Pos.init(nx, ny, nz, nw);
if (!self.cells[self.curr].contains(np)) continue;
const tile = self.cells[self.curr].get(np).?;
if (tile != Tile.Active) continue;
count += 1;
}
}
}
}
return count;
}
};
test "sample part a" {
const data: []const u8 =
\\.#.
\\..#
\\###
;
var map = Map.init(Map.Space.Dim3);
defer map.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
map.add_line(line);
}
// Before any cycles:
//
// z=0
// .#.
// ..#
// ###
//
//
// After 1 cycle:
//
// z=-1
// #..
// ..#
// .#.
//
// z=0
// #.#
// .##
// .#.
//
// z=1
// #..
// ..#
// .#.
//
//
// After 2 cycles:
//
// z=-2
// .....
// .....
// ..#..
// .....
// .....
//
// z=-1
// ..#..
// .#..#
// ....#
// .#...
// .....
//
// z=0
// ##...
// ##...
// #....
// ....#
// .###.
//
// z=1
// ..#..
// .#..#
// ....#
// .#...
// .....
//
// z=2
// .....
// .....
// ..#..
// .....
// .....
//
//
// After 3 cycles:
//
// z=-2
// .......
// .......
// ..##...
// ..###..
// .......
// .......
// .......
//
// z=-1
// ..#....
// ...#...
// #......
// .....##
// .#...#.
// ..#.#..
// ...#...
//
// z=0
// ...#...
// .......
// #......
// .......
// .....##
// .##.#..
// ...#...
//
// z=1
// ..#....
// ...#...
// #......
// .....##
// .#...#.
// ..#.#..
// ...#...
//
// z=2
// .......
// .......
// ..##...
// ..###..
// .......
// .......
// .......
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
const count = map.run(6);
try testing.expect(count == 112);
}
test "sample part b" {
const data: []const u8 =
\\.#.
\\..#
\\###
;
var map = Map.init(Map.Space.Dim4);
defer map.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
map.add_line(line);
}
// Before any cycles:
//
// z=0, w=0
// .#.
// ..#
// ###
//
//
// After 1 cycle:
//
// z=-1, w=-1
// #..
// ..#
// .#.
//
// z=0, w=-1
// #..
// ..#
// .#.
//
// z=1, w=-1
// #..
// ..#
// .#.
//
// z=-1, w=0
// #..
// ..#
// .#.
//
// z=0, w=0
// #.#
// .##
// .#.
//
// z=1, w=0
// #..
// ..#
// .#.
//
// z=-1, w=1
// #..
// ..#
// .#.
//
// z=0, w=1
// #..
// ..#
// .#.
//
// z=1, w=1
// #..
// ..#
// .#.
//
//
// After 2 cycles:
//
// z=-2, w=-2
// .....
// .....
// ..#..
// .....
// .....
//
// z=-1, w=-2
// .....
// .....
// .....
// .....
// .....
//
// z=0, w=-2
// ###..
// ##.##
// #...#
// .#..#
// .###.
//
// z=1, w=-2
// .....
// .....
// .....
// .....
// .....
//
// z=2, w=-2
// .....
// .....
// ..#..
// .....
// .....
//
// z=-2, w=-1
// .....
// .....
// .....
// .....
// .....
//
// z=-1, w=-1
// .....
// .....
// .....
// .....
// .....
//
// z=0, w=-1
// .....
// .....
// .....
// .....
// .....
//
// z=1, w=-1
// .....
// .....
// .....
// .....
// .....
//
// z=2, w=-1
// .....
// .....
// .....
// .....
// .....
//
// z=-2, w=0
// ###..
// ##.##
// #...#
// .#..#
// .###.
//
// z=-1, w=0
// .....
// .....
// .....
// .....
// .....
//
// z=0, w=0
// .....
// .....
// .....
// .....
// .....
//
// z=1, w=0
// .....
// .....
// .....
// .....
// .....
//
// z=2, w=0
// ###..
// ##.##
// #...#
// .#..#
// .###.
//
// z=-2, w=1
// .....
// .....
// .....
// .....
// .....
//
// z=-1, w=1
// .....
// .....
// .....
// .....
// .....
//
// z=0, w=1
// .....
// .....
// .....
// .....
// .....
//
// z=1, w=1
// .....
// .....
// .....
// .....
// .....
//
// z=2, w=1
// .....
// .....
// .....
// .....
// .....
//
// z=-2, w=2
// .....
// .....
// ..#..
// .....
// .....
//
// z=-1, w=2
// .....
// .....
// .....
// .....
// .....
//
// z=0, w=2
// ###..
// ##.##
// #...#
// .#..#
// .###.
//
// z=1, w=2
// .....
// .....
// .....
// .....
// .....
//
// z=2, w=2
// .....
// .....
// ..#..
// .....
// .....
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
// map.step();
// map.show();
const count = map.run(6);
try testing.expect(count == 848);
}
|
2020/p17/map.zig
|
const std = @import("std");
const c = @import("c.zig");
const assert = std.debug.assert;
const panic = std.debug.panic;
const grid_png_data = @embedFile("../assets/grid.png");
const font_bmp_data = @embedFile("../assets/font.bmp");
const player_png_data = @embedFile("../assets/player.png");
pub fn main() anyerror!void {
if (!(c.SDL_SetHintWithPriority(c.SDL_HINT_NO_SIGNAL_HANDLERS, "1", c.SDL_HintPriority.SDL_HINT_OVERRIDE) != c.SDL_bool.SDL_FALSE)) {
panic("failed to disable sdl signal handlers\n", .{});
}
if (c.SDL_Init(c.SDL_INIT_VIDEO) != 0) {
panic("SDL_Init failed: {s}\n", .{c.SDL_GetError()});
}
defer c.SDL_Quit();
const screen = c.SDL_CreateWindow(
"squarez",
c.SDL_WINDOWPOS_UNDEFINED,
c.SDL_WINDOWPOS_UNDEFINED,
400,
400,
0,
) orelse {
panic("SDL_CreateWindow failed: {*}\n", .{c.SDL_GetError()});
};
defer c.SDL_DestroyWindow(screen);
const renderer = c.SDL_CreateRenderer(screen, -1, 0) orelse {
panic("SDL_CreateRenderer failed: {*}\n", .{c.SDL_GetError()});
};
defer c.SDL_DestroyRenderer(renderer);
const grid_texture = createTextureFromData(grid_png_data, renderer);
const font_texture = createTextureFromData(font_bmp_data, renderer);
const player_texture = createTextureFromData(player_png_data, renderer);
var state = Gamestate{
.board = Board.create(),
.position = Point{ .x = 4, .y = 4 },
};
mainLoop: while (true) {
var event: c.SDL_Event = undefined;
while (c.SDL_PollEvent(&event) != 0) {
switch (event.@"type") {
c.SDL_QUIT => return,
c.SDL_KEYDOWN => {
switch (event.key.keysym.sym) {
c.SDLK_LEFT => state.movePosition(.Left),
c.SDLK_RIGHT => state.movePosition(.Right),
c.SDLK_UP => state.movePosition(.Up),
c.SDLK_DOWN => state.movePosition(.Down),
'1'...'9' => state.setValue(@intCast(u8, event.key.keysym.sym - '0')),
'x' => state.setValue(null),
'q' => break :mainLoop,
else => {},
}
},
c.SDL_MOUSEBUTTONDOWN => {
if (event.button.button == c.SDL_BUTTON_LEFT) {
const x = @divFloor((@intCast(u32, event.button.x) - 20), 40);
const y = @divFloor((@intCast(u32, event.button.y) - 20), 40);
if (x >= 0 and x <= 8 and y >= 0 and y <= 8) {
state.position.x = x;
state.position.y = y;
}
}
},
else => {},
}
}
_ = c.SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
c.assertZero(c.SDL_RenderClear(renderer));
drawPlayerPosition(renderer, &state, player_texture);
drawBackground(renderer, grid_texture);
drawNumbers(renderer, &state, font_texture);
c.SDL_RenderPresent(renderer);
c.SDL_Delay(17 - (c.SDL_GetTicks() % 17));
}
}
fn drawPlayerPosition(
renderer: *c.SDL_Renderer,
state: *Gamestate,
texture: *c.SDL_Texture,
) void {
const src = c.SDL_Rect{
.x = 0,
.y = 0,
.w = 40,
.h = 40,
};
const dst = c.SDL_Rect{
.x = @intCast(c_int, 20 + state.position.x * 40),
.y = @intCast(c_int, 20 + state.position.y * 40),
.w = 40,
.h = 40,
};
c.assertZero(c.SDL_RenderCopy(renderer, texture, &src, &dst));
}
fn drawNumbers(renderer: *c.SDL_Renderer, state: *Gamestate, font: *c.SDL_Texture) void {
var x: u32 = 0;
while (x < 9) {
var y: u32 = 0;
while (y < 9) {
var value = state.getValue(x, y);
if (value) |v| {
var idx: i32 = v + 16; // font map starts with space
// 95 characters, ascii sorted
if (idx < 0 or idx > 94)
continue;
const src_rect = c.SDL_Rect{
.x = 18 * idx,
.y = 0,
.w = 18,
.h = 36,
};
const dst_rect = c.SDL_Rect{
.x = 20 + @intCast(i32, x) * 40 + (40 - 18) / 2,
.y = 20 + @intCast(i32, y) * 40 + (40 - 36) / 2,
.w = 18,
.h = 36,
};
c.assertZero(c.SDL_RenderCopy(renderer, font, &src_rect, &dst_rect));
}
y = y + 1;
}
x = x + 1;
}
}
fn drawBackground(renderer: *c.SDL_Renderer, texture: *c.SDL_Texture) void {
const src_rect = c.SDL_Rect{
.x = 0,
.y = 0,
.w = 360,
.h = 360,
};
const dst_rect = c.SDL_Rect{
.x = 20,
.y = 20,
.w = 360,
.h = 360,
};
c.assertZero(c.SDL_RenderCopy(renderer, texture, &src_rect, &dst_rect));
}
fn createTextureFromData(data: anytype, renderer: *c.SDL_Renderer) *c.SDL_Texture {
const rwops = c.SDL_RWFromConstMem(data, data.len).?;
const surface = c.IMG_Load_RW(rwops, 0) orelse panic("unable to load image", .{});
const texture = c.SDL_CreateTextureFromSurface(renderer, surface) orelse panic("unable to create texture", .{});
return texture;
}
const Gamestate = struct {
board: Board,
position: Point,
const Self = @This();
fn movePosition(self: *Self, direction: Direction) void {
switch (direction) {
.Left => {
if (self.position.x > 0) self.position.x -= 1;
},
.Right => {
if (self.position.x < 8) self.position.x += 1;
},
.Up => {
if (self.position.y > 0) self.position.y -= 1;
},
.Down => {
if (self.position.y < 8) self.position.y += 1;
},
}
}
fn setValue(self: *Self, value: ?u8) void {
self.board.setValue(self.position.x, self.position.y, value);
}
fn getValue(self: Self, x: u32, y: u32) ?u8 {
return self.board.getValue(x, y);
}
};
const Board = struct {
values: [81]?u8,
const Self = @This();
pub fn getValue(self: Self, x: u32, y: u32) ?u8 {
return self.values[y * 9 + x];
}
pub fn setValue(self: *Self, x: u32, y: u32, value: ?u8) void {
self.values[y * 9 + x] = value;
}
fn create() Board {
return Board{
.values = [_]?u8{null} ** 81,
};
}
};
const Point = struct {
x: u32,
y: u32,
};
const Direction = enum { Up, Down, Left, Right };
|
src/main.zig
|
// DO NOT MODIFY. This is not actually a source file; it is a textual representation of generated code.
// Use only for debugging purposes.
// Auto-generated constructor
// Access: public
Method <init> : V
(
// (no arguments)
) {
ALOAD 0
// Method descriptor: ()V
INVOKESPECIAL java/lang/Object#<init>
RETURN
}
// Access: public
Method deploy_0 : V
(
arg 1 = Lio/quarkus/runtime/StartupContext;,
arg 2 = [Ljava/lang/Object;
) {
** label1
NEW java/util/HashSet
DUP
// Method descriptor: ()V
INVOKESPECIAL java/util/HashSet#<init>
ASTORE 3
ALOAD 2
LDC (Integer) 1
ALOAD 3
AASTORE
ALOAD 2
LDC (Integer) 1
AALOAD
ASTORE 4
ALOAD 2
LDC (Integer) 2
ALOAD 4
AASTORE
NEW java/util/HashSet
DUP
// Method descriptor: ()V
INVOKESPECIAL java/util/HashSet#<init>
ASTORE 5
ALOAD 2
LDC (Integer) 3
ALOAD 5
AASTORE
ALOAD 2
LDC (Integer) 3
AALOAD
ASTORE 6
ALOAD 2
LDC (Integer) 4
ALOAD 6
AASTORE
NEW io/quarkus/undertow/runtime/UndertowDeploymentRecorder
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#<init>
ASTORE 7
ALOAD 2
LDC (Integer) 0
ALOAD 7
AASTORE
ALOAD 2
LDC (Integer) 2
AALOAD
ASTORE 9
ALOAD 2
LDC (Integer) 4
AALOAD
ASTORE 11
LDC (String) "NORMAL"
// Method descriptor: (Ljava/lang/String;)Lio/quarkus/runtime/LaunchMode;
INVOKESTATIC io/quarkus/runtime/LaunchMode#valueOf
ASTORE 8
ALOAD 1
LDC (String) "io.quarkus.runtime.ShutdownContext"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 10
ALOAD 2
LDC (Integer) 0
AALOAD
ASTORE 14
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
LDC (String) "test"
ALOAD 9
CHECKCAST java/util/Set
ALOAD 11
CHECKCAST java/util/Set
ALOAD 8
ALOAD 10
CHECKCAST io/quarkus/runtime/ShutdownContext
LDC (String) "/"
// Method descriptor: (Ljava/lang/String;Ljava/util/Set;Ljava/util/Set;Lio/quarkus/runtime/LaunchMode;Lio/quarkus/runtime/ShutdownContext;Ljava/lang/String;)Lio/quarkus/runtime/RuntimeValue;
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#createDeployment
ASTORE 12
ALOAD 1
LDC (String) "proxykey51"
ALOAD 12
// Method descriptor: (Ljava/lang/String;Ljava/lang/Object;)V
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#putValue
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 13
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 13
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "resteasy.injector.factory"
LDC (String) "org.jboss.resteasy.cdi.CdiInjectorFactory"
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addContextParam
NEW java/util/LinkedHashMap
DUP
// Method descriptor: ()V
INVOKESPECIAL java/util/LinkedHashMap#<init>
ASTORE 15
ALOAD 2
LDC (Integer) 5
ALOAD 15
AASTORE
ALOAD 2
LDC (Integer) 5
AALOAD
ASTORE 16
ALOAD 2
LDC (Integer) 6
ALOAD 16
AASTORE
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 18
// Method descriptor: ()Ljava/lang/Thread;
INVOKESTATIC java/lang/Thread#currentThread
// Method descriptor: ()Ljava/lang/ClassLoader;
INVOKEVIRTUAL java/lang/Thread#getContextClassLoader
ASTORE 17
LDC (String) "io.quarkus.resteasy.runtime.ResteasyFilter"
LDC (Boolean) true
ALOAD 17
// Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;
INVOKESTATIC java/lang/Class#forName
ASTORE 20
LDC (Boolean) true
// Method descriptor: (Z)Ljava/lang/Boolean;
INVOKESTATIC java/lang/Boolean#valueOf
ASTORE 19
ALOAD 1
LDC (String) "proxykey40"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 21
ALOAD 2
LDC (Integer) 6
AALOAD
ASTORE 22
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 18
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "javax.ws.rs.core.Application"
ALOAD 20
ALOAD 19
CHECKCAST java/lang/Boolean
// Method descriptor: ()Z
INVOKEVIRTUAL java/lang/Boolean#booleanValue
ALOAD 21
CHECKCAST io/quarkus/arc/runtime/BeanContainer
ALOAD 22
CHECKCAST java/util/Map
ACONST_NULL
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/Class;ZLio/quarkus/arc/runtime/BeanContainer;Ljava/util/Map;Lio/undertow/servlet/api/InstanceFactory;)Lio/quarkus/runtime/RuntimeValue;
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#registerFilter
ASTORE 23
ALOAD 1
LDC (String) "proxykey53"
ALOAD 23
// Method descriptor: (Ljava/lang/String;Ljava/lang/Object;)V
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#putValue
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 24
LDC (String) "REQUEST"
// Method descriptor: (Ljava/lang/String;)Ljavax/servlet/DispatcherType;
INVOKESTATIC javax/servlet/DispatcherType#valueOf
ASTORE 25
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 24
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "javax.ws.rs.core.Application"
LDC (String) "default"
ALOAD 25
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/String;Ljavax/servlet/DispatcherType;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addFilterServletNameMapping
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 26
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 26
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "resteasy.injector.factory"
LDC (String) "io.quarkus.resteasy.server.common.runtime.QuarkusInjectorFactory"
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addServletInitParameter
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 27
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 27
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "resteasy.providers"
LDC (String) "io.quarkus.resteasy.runtime.RolesFilterRegistrar"
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addServletInitParameter
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 28
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 28
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "resteasy.scanned.resources"
LDC (String) "com.redhat.demo.robotservice.ProxyTestService,com.redhat.demo.robotservice.LocalRobotProxyService"
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addServletInitParameter
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 29
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 29
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "resteasy.use.builtin.providers"
LDC (String) "true"
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addServletInitParameter
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 30
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 30
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "resteasy.servlet.mapping.prefix"
LDC (String) "/"
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addServletInitParameter
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 31
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 31
CHECKCAST io/quarkus/runtime/RuntimeValue
LDC (String) "resteasy.unwrapped.exceptions"
LDC (String) "io.quarkus.arc.ArcUndeclaredThrowableException"
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/String;Ljava/lang/String;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addServletInitParameter
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 32
ALOAD 1
LDC (String) "proxykey45"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 33
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 32
CHECKCAST io/quarkus/runtime/RuntimeValue
ALOAD 33
CHECKCAST io/undertow/servlet/ServletExtension
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Lio/undertow/servlet/ServletExtension;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#addServletExtension
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 37
// Method descriptor: ()Ljava/lang/Thread;
INVOKESTATIC java/lang/Thread#currentThread
// Method descriptor: ()Ljava/lang/ClassLoader;
INVOKEVIRTUAL java/lang/Thread#getContextClassLoader
ASTORE 34
LDC (String) "io.quarkus.undertow.runtime.HttpSessionContext"
LDC (Boolean) true
ALOAD 34
// Method descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;
INVOKESTATIC java/lang/Class#forName
ASTORE 36
ALOAD 1
LDC (String) "proxykey40"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 35
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 37
CHECKCAST io/quarkus/runtime/RuntimeValue
ALOAD 36
ALOAD 35
CHECKCAST io/quarkus/arc/runtime/BeanContainer
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Ljava/lang/Class;Lio/quarkus/arc/runtime/BeanContainer;)V
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#registerListener
ALOAD 1
LDC (String) "proxykey51"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 39
ALOAD 1
LDC (String) "proxykey40"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 38
LDC (String) "NORMAL"
// Method descriptor: (Ljava/lang/String;)Lio/quarkus/runtime/LaunchMode;
INVOKESTATIC io/quarkus/runtime/LaunchMode#valueOf
ASTORE 41
ALOAD 1
LDC (String) "io.quarkus.runtime.ShutdownContext"
// Method descriptor: (Ljava/lang/String;)Ljava/lang/Object;
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#getValue
ASTORE 40
ALOAD 14
CHECKCAST io/quarkus/undertow/runtime/UndertowDeploymentRecorder
ALOAD 39
CHECKCAST io/quarkus/runtime/RuntimeValue
ALOAD 38
CHECKCAST io/quarkus/arc/runtime/BeanContainer
ALOAD 41
ALOAD 40
CHECKCAST io/quarkus/runtime/ShutdownContext
// Method descriptor: (Lio/quarkus/runtime/RuntimeValue;Lio/quarkus/arc/runtime/BeanContainer;Lio/quarkus/runtime/LaunchMode;Lio/quarkus/runtime/ShutdownContext;)Lio/undertow/servlet/api/DeploymentManager;
INVOKEVIRTUAL io/quarkus/undertow/runtime/UndertowDeploymentRecorder#bootServletContainer
ASTORE 42
ALOAD 1
LDC (String) "proxykey56"
ALOAD 42
// Method descriptor: (Ljava/lang/String;Ljava/lang/Object;)V
INVOKEVIRTUAL io/quarkus/runtime/StartupContext#putValue
RETURN
** label2
}
// Access: public
Method deploy : V
(
arg 1 = Lio/quarkus/runtime/StartupContext;
) {
** label1
LDC (Integer) 7
ANEWARRAY java/lang/Object
ASTORE 2
ALOAD 0
ALOAD 1
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;[Ljava/lang/Object;)V
INVOKEVIRTUAL io/quarkus/deployment/steps/UndertowBuildStep$build23#deploy_0
RETURN
** label2
}
|
localproxyservice/target/generated-sources/gizmo/io/quarkus/deployment/steps/UndertowBuildStep$build23.zig
|
const gdt = @import("gdt.zig");
const isr = @import("isr.zig");
const mem = @import("mem.zig");
const timer = @import("timer.zig");
const tty = @import("tty.zig");
const x86 = @import("x86.zig");
const Process = @import("process.zig").Process;
const Thread = @import("thread.zig").Thread;
const ThreadQueue = @import("thread.zig").ThreadQueue;
pub var current_process: &Process = undefined; // The process that is currently executing.
var ready_queue: ThreadQueue = undefined; // Queue of threads ready for execution.
////
// Schedule to the next thread in the queue.
// Called at each timer tick.
//
fn schedule() void {
if (ready_queue.popFirst()) |next| {
ready_queue.append(next);
const next_thread = next.toData();
contextSwitch(next_thread);
}
}
////
// Set up a context switch to a thread.
//
// Arguments:
// thread: The thread to switch to.
//
fn contextSwitch(thread: &Thread) void {
switchProcess(thread.process);
isr.context = &thread.context;
gdt.setKernelStack(@ptrToInt(isr.context) + @sizeOf(isr.Context));
}
////
// Switch to the address space of a process, if necessary.
//
// Arguments:
// process: The process to switch to.
//
pub fn switchProcess(process: &Process) void {
if (current_process != process) {
x86.writeCR3(process.page_directory);
current_process = process;
}
}
////
// Add a new thread to the scheduling queue.
// Schedule it immediately.
//
// Arguments:
// new_thread: The thread to be added.
//
pub fn new(new_thread: &Thread) void {
ready_queue.append(&new_thread.queue_link);
contextSwitch(new_thread);
}
////
// Enqueue a thread into the scheduling queue.
// Schedule it last.
//
// Arguments:
// thread: The thread to be enqueued.
//
pub fn enqueue(thread: &Thread) void {
// Last element in the queue is the thread currently being executed.
// So put this thread in the second to last position.
if (ready_queue.last) |last| {
ready_queue.insertBefore(last, &thread.queue_link);
} else {
// If the queue is empty, simply insert the thread.
ready_queue.prepend(&thread.queue_link);
}
}
////
// Deschedule the current thread and schedule a new one.
//
// Returns:
// The descheduled thread.
//
pub fn dequeue() ?&Thread {
const thread = ready_queue.pop() ?? return null;
schedule();
return thread.toData();
}
////
// Remove a thread from the scheduling queue.
//
// Arguments:
// thread: The thread to be removed.
//
pub fn remove(thread: &Thread) void {
if (thread == ??current()) {
_ = dequeue();
} else {
ready_queue.remove(&thread.queue_link);
}
}
////
// Return the thread currently being executed.
//
pub inline fn current() ?&Thread {
const last = ready_queue.last ?? return null;
return last.toData();
}
////
// Initialize the scheduler.
//
pub fn initialize() void {
tty.step("Initializing the Scheduler");
ready_queue = ThreadQueue.init();
timer.registerHandler(schedule);
tty.stepOK();
}
|
kernel/scheduler.zig
|
const sf = @import("../sfml.zig");
const SoundBuffer = @This();
// Constructor/destructor
/// Loads music from a file
pub fn createFromFile(path: [:0]const u8) !SoundBuffer {
var sound = sf.c.sfSoundBuffer_createFromFile(path);
if (sound == null)
return sf.Error.resourceLoadingError;
return SoundBuffer{ ._ptr = sound.? };
}
/// Creates a sound buffer from sample data
pub fn createFromSamples(samples: []const i16, channel_count: usize, sample_rate: usize) !SoundBuffer {
var sound = sf.c.sfSoundBuffer_createFromSamples(@ptrCast([*c]const c_short, samples.ptr), samples.len, @intCast(c_uint, channel_count), @intCast(c_uint, sample_rate));
if (sound == null)
return sf.Error.resourceLoadingError;
return SoundBuffer{ ._ptr = sound.? };
}
pub const initFromMemory = @compileError("Function is not implemented yet.");
pub const initFromStream = @compileError("Function is not implemented yet.");
/// Destroys this music object
pub fn destroy(self: *SoundBuffer) void {
sf.c.sfSoundBuffer_destroy(self._ptr);
}
// Getters / Setters
/// Gets the duration of the sound
pub fn getDuration(self: SoundBuffer) sf.system.Time {
return sf.system.Time._fromCSFML(sf.c.sfSoundBuffer_getDuration(self._ptr));
}
/// Gets the sample count of this sound
pub fn getSampleCount(self: SoundBuffer) usize {
return @intCast(usize, sf.c.sfSoundBuffer_getSampleCount(self._ptr));
}
/// Gets the sample rate of this sound (n° of samples per second, often 44100)
pub fn getSampleRate(self: SoundBuffer) usize {
return @intCast(usize, sf.c.sfSoundBuffer_getSampleRate(self._ptr));
}
/// Gets the channel count (2 is stereo for instance)
pub fn getChannelCount(self: SoundBuffer) usize {
return @intCast(usize, sf.c.sfSoundBuffer_getChannelCount(self._ptr));
}
// Misc
/// Save the sound buffer to an audio file
pub fn saveToFile(self: SoundBuffer, path: [:0]const u8) !void {
if (sf.c.sfSoundBuffer_saveToFile(self._ptr, path) != 1)
return sf.Error.savingInFileFailed;
}
/// Pointer to the csfml texture
_ptr: *sf.c.sfSoundBuffer,
test "sound buffer: sane getter and setters" {
const std = @import("std");
const tst = std.testing;
const allocator = std.heap.page_allocator;
var samples = try allocator.alloc(i16, 44100 * 3);
defer allocator.free(samples);
var buffer = try SoundBuffer.createFromSamples(samples, 1, 44100);
defer buffer.destroy();
try tst.expectApproxEqAbs(@as(f32, 3), buffer.getDuration().asSeconds(), 0.001);
try tst.expectEqual(@as(usize, 44100 * 3), buffer.getSampleCount());
try tst.expectEqual(@as(usize, 44100), buffer.getSampleRate());
try tst.expectEqual(@as(usize, 1), buffer.getChannelCount());
}
|
src/sfml/audio/SoundBuffer.zig
|
const lib = @import("lib.zig");
const types = lib.types;
pub const Opcode = enum(u8) {
@"error" = 0,
create_window = 1,
change_window_attributes = 2,
get_window_attributes = 3,
destroy_window = 4,
destroy_subwindows = 5,
change_save_set = 6,
reparent_window = 7,
map_window = 8,
map_subwindows = 9,
unmap_window = 10,
unmap_subwindows = 11,
configure_window = 12,
circulate_window = 13,
get_geometry = 14,
query_tree = 15,
intern_atom = 16,
get_atom_name = 17,
change_property = 18,
delete_property = 19,
get_property = 20,
list_properties = 21,
set_selection_owner = 22,
get_selection_owner = 23,
convert_selection = 24,
send_event = 25,
grab_pointer = 26,
ungrab_pointer = 27,
grab_button = 28,
ungrab_button = 29,
change_active_pointer_grab = 30,
grab_keyboard = 31,
ungrab_keyboard = 32,
grab_key = 33,
ungrab_key = 34,
allow_events = 35,
grab_server = 36,
ungrab_server = 37,
query_pointer = 38,
get_motion_events = 39,
translate_coordinates = 40,
warp_pointer = 41,
set_input_focus = 42,
get_input_focus = 43,
query_keymap = 44,
open_font = 45,
close_font = 46,
query_font = 47,
query_text_extents = 48,
list_fonts = 49,
list_fonts_with_info = 50,
set_font_path = 51,
get_font_path = 52,
create_pixmap = 53,
free_pixmap = 54,
create_gc = 55,
change_gc = 56,
copy_gc = 57,
set_dashes = 58,
set_clip_rectangles = 59,
gree_gc = 60,
clear_area = 61,
copy_area = 62,
copy_plane = 63,
poly_point = 64,
poly_line = 65,
poly_segment = 66,
poly_rectangle = 67,
poly_arc = 68,
fill_poly = 69,
poly_fill_rectangle = 70,
poly_fill_arc = 71,
put_image = 72,
get_image = 73,
poly_text8 = 74,
poly_text16 = 75,
image_text8 = 76,
image_text16 = 77,
create_colormap = 78,
free_Colormap = 79,
copy_Colormap_and_free = 80,
install_colormap = 81,
uninstall_colormap = 82,
list_installed_colormaps = 83,
alloc_color = 84,
alloc_named_color = 85,
alloc_color_cells = 86,
alloc_color_planes = 87,
free_colors = 88,
store_colors = 89,
store_named_colors = 90,
query_colors = 91,
lookup_color = 92,
create_cursor = 93,
create_glyph_cursor = 94,
free_cursor = 95,
recolor_cursor = 96,
query_best_size = 97,
query_extension = 98,
list_extensions = 99,
change_keyboard_mapping = 100,
get_keyboard_mapping = 101,
change_keyboard_control = 102,
get_keyboard_control = 103,
bell = 104,
change_pointer_control = 105,
get_pointer_control = 106,
set_screen_saver = 107,
get_screen_saver = 108,
change_hosts = 109,
list_hosts = 110,
set_access_control = 111,
set_close_down_mode = 112,
kill_client = 113,
rotate_properties = 114,
force_screen_saver = 115,
set_pointer_mapping = 116,
get_pointer_mapping = 117,
set_modifier_mapping = 118,
get_modifier_mapping = 119,
no_operation = 120,
};
pub const Event = enum(u8) {
key_press = 2,
key_release = 3,
button_press = 4,
button_release = 5,
motion_notify = 6,
enter_notify = 7,
leave_notify = 8,
focus_in = 9,
focus_out = 10,
keymap_notify = 11,
expose = 12,
graphics_exposure = 13,
no_exposure = 14,
visibility_notify = 15,
create_notify = 16,
destroy_notify = 17,
unmap_notify = 18,
map_notify = 19,
map_request = 20,
reparent_notify = 21,
configure_notify = 22,
configure_request = 23,
gravity_notify = 24,
resize_request = 25,
circulate_notify = 26,
circulate_request = 27,
property_notify = 28,
selection_clear = 29,
selection_request = 30,
selection_notify = 31,
colormap_notify = 32,
client_message = 33,
mapping_notify = 34,
};
pub const EventMask = packed struct {
key_press: bool = false,
key_releae: bool = false,
button_press: bool = false,
button_release: bool = false,
enter_window: bool = false,
leave_window: bool = false,
pointer_motion: bool = false,
pointer_motion_hint: bool = false,
button1_motion: bool = false,
button2_motion: bool = false,
button3_motion: bool = false,
button4_motion: bool = false,
button5_motion: bool = false,
button_motion: bool = false,
keymap_state: bool = false,
exposure: bool = false,
visibility_change: bool = false,
structure_notify: bool = false,
resize_redirect: bool = false,
substructure_notify: bool = false,
substructure_redirect: bool = false,
focus_change: bool = false,
property_change: bool = false,
colormap_change: bool = false,
owner_grab_button: bool = false,
pad: u7 = 0,
};
pub const Error = extern struct {
opcode: u8 = 0,
code: ErrorCode,
sequence: u16,
bad_value: u32,
minor_opcode: u16,
major_opcode: Opcode,
unused: [21]u8,
pub const ErrorCode = enum(u8) {
request = 1,
value = 2,
window = 3,
pixmap = 4,
atom = 5,
cursor = 6,
font = 7,
match = 8,
drawable = 9,
access = 10,
alloc = 11,
colormap = 12,
g_context = 13,
id_choice = 14,
name = 15,
length = 16,
implementation = 17,
};
};
pub const CreateWindowRequest = extern struct {
opcode: Opcode = .create_window,
depth: u8,
length: u16 = 8,
window: types.Window,
parent: types.Window,
x: i16,
y: i16,
width: u16,
height: u16,
class: u8,
visual: types.VisualId,
value_mask: CreateWindowBitmask = .{},
};
pub const GetWindowAttributesRequest = extern struct {
opcode: Opcode = .get_window_attributes,
unused: u8 = 0,
length: u16 = 2,
window: types.Window,
};
pub const GetWindowAttributesResponse = extern struct {
opcode: u8 = 1,
backing_store: u8,
sequence_number: u8,
length: u32 = 3,
visual: types.VisualId,
bit_gravity: u8,
win_gravity: u8,
backing_planes: u32,
backing_pixel: u32,
save_under: bool,
map_is_installed: bool,
map_state: u8,
override_redirect: bool,
colormap: u32,
all_event_mask: u32,
your_event_mask: u32,
do_not_propagate_mask: u16,
unused: u16,
};
pub const CreateNotify = extern struct {
opcode: Event,
unused: u8 = 0,
sequence: u16,
parent: types.Window,
window: types.Window,
x: i16,
y: i16,
width: u16,
height: u16,
border_width: u16,
override_redirect: bool,
pad: [9]u8 = [_]u8{0} ** 9,
};
pub const DestroyWindow = extern struct {
opcode: Opcode = .destroy_window,
unused: u8 = 0,
length: u16 = 2,
window: types.Window,
};
pub const DestroyNotify = extern struct {
opcode: Event = .destroy_notify,
unused: u8 = 0,
sequence: u16,
event: types.Window,
window: types.Window,
pad: [20]u8 = [_]u8{0} ** 20,
};
pub const MapWindowRequest = extern struct {
opcode: Opcode = .map_window,
unused: u8 = 0,
length: u16 = 2,
window: types.Window,
};
pub const MapNotify = extern struct {
opcode: Event = .map_notify,
unused: u8,
sequence: u16,
event: types.Window,
window: types.Window,
override_redirect: bool,
pad: [19]u8 = [_]u8{0} ** 19,
};
pub const UnmapNotify = extern struct {
opcode: Event = .unmap_notify,
unused: u8,
sequence: u16,
event: types.Window,
window: types.Window,
from_configure: bool,
pad: [19]u8 = [_]u8{0} ** 19,
};
pub const ReparentNotify = extern struct {
opcode: Event = .reparent_notify,
unused: u8,
sequence: u16,
event: types.Window,
window: types.Window,
parent: types.Window,
x: i16,
y: i16,
redirect_override: bool,
pad: [11]u8 = [_]u8{0} ** 11,
};
pub const CreateWindowBitmask = packed struct {
background_pixmap: bool = false,
background_pixel: bool = false,
border_pixmap: bool = false,
border_pixel: bool = false,
bit_gravity: bool = false,
win_gravity: bool = false,
backing_store: bool = false,
backing_planes: bool = false,
backing_pixel: bool = false,
override_redirect: bool = false,
save_under: bool = false,
event_mask: bool = false,
do_not_propagate_mask: bool = false,
colormap: bool = false,
cursor: bool = false,
pad0: u2 = 0,
pad: u16 = 0,
};
pub const ChangeWindowAttributes = extern struct {
opcode: Opcode = .change_window_attributes,
unused: u8 = 0,
length: u16 = 3,
window: types.Window,
value_mask: CreateWindowBitmask,
};
pub const SendEventRequest = extern struct {
opcode: Opcode = .send_event,
propagate: bool,
length: u16 = 11,
window: types.Window,
event_mask: EventMask,
event: [32]u8,
};
|
src/request.zig
|
const builtin = @import("builtin");
const TypeId = builtin.TypeId;
const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;
const matrix = @import("matrix.zig");
const Matrix = matrix.Matrix;
const M44f32 = matrix.M44f32;
const vec = @import("vec.zig");
const V3f32 = vec.V3f32;
const V2f32 = vec.V2f32;
const DBG = false;
pub fn pointToScreenCoord(widthf: f32, heightf: f32, pos_x: f32, pos_y: f32) V2f32 {
// The transformed coord is based on a coordinate system
// where the origin is the center of the screen. Convert
// them to coordindates where x:0, y:0 is the upper left.
var x = (pos_x + 1) * 0.5 * widthf;
var y = (1 - ((pos_y + 1) * 0.5)) * heightf;
if (DBG) warn("pointToScreenCoord: pos_x={.3} pos_y={.3} x={.3} y={.3} widthf={.3} heightf={.3}\n", pos_x, pos_y, x, y, widthf, heightf);
return V2f32.init(x, y);
}
test "screencoord.pointToScreenCoord" {
const x: f32 = 0.1;
const y: f32 = 0.2;
var screen = pointToScreenCoord(640, 480, x, y);
assert(screen.x() == (x + 1) * 0.5 * 640);
assert(screen.y() == (1 - ((y + 1) * 0.5)) * 480);
}
pub fn projectToScreenCoord(widthf: f32, heightf: f32, coord: V3f32, transMat: *const M44f32) V2f32 {
if (DBG) warn("projectToScreenCoord: original coord={} widthf={.3} heightf={.3}\n", &coord, widthf, heightf);
// Transform coord in 3D
var point = coord.transform(transMat);
if (DBG) warn("projectToScreenCoord: transformed point={}\n", &point);
return pointToScreenCoord(widthf, heightf, point.x(), point.y());
}
test "screencoord.projectToScreenCoord" {
var width: f32 = 640;
var height: f32 = 480;
var coord: V3f32 = undefined;
var screen: V2f32 = undefined;
var point: V2f32 = undefined;
const view_matrix = M44f32{ .data = [][4]f32{
[]f32{ 1.00000, 0.00000, 0.00000, 0.00000 },
[]f32{ 0.00000, 1.00000, 0.00000, 0.00000 },
[]f32{ 0.00000, 0.00000, 1.00000, 0.00000 },
[]f32{ 0.00000, 0.00000, 10.00000, 1.00000 },
} };
coord = V3f32.init(0, 0, 0);
screen = projectToScreenCoord(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
assert(screen.x() == 320);
assert(screen.y() == 240);
coord = V3f32.init(0.1, 0.1, 0);
screen = projectToScreenCoord(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
point = pointToScreenCoord(width, height, 0.1, 0.1);
if (DBG) warn("math3d.lookAtLh: point={}\n", &point);
assert(screen.x() == point.x());
assert(screen.y() == point.y());
coord = V3f32.init(-0.1, -0.1, 0);
screen = projectToScreenCoord(width, height, coord, &view_matrix);
if (DBG) warn("math3d.lookAtLh: coord={} screen={}\n", &coord, &screen);
point = pointToScreenCoord(width, height, -0.1, -0.1);
if (DBG) warn("math3d.lookAtLh: point={}\n", &point);
assert(screen.x() == point.x());
assert(screen.y() == point.y());
}
|
screencoord.zig
|
const std = @import("std");
const util = @import("util");
const input = @embedFile("14.txt");
const MaskValueInstr = struct {
addr: u36,
value: u36,
};
const MaskAddrInstr = struct {
addr: u36,
mask: u36,
value: u36,
};
usingnamespace comptime blk: {
@setEvalBranchQuota(input.len * 20);
var bitwise_or: u36 = 0;
var value_mask: u36 = undefined;
var addr_mask: u36 = undefined;
var mask_values_buf: []const MaskValueInstr = &[_]MaskValueInstr{};
var mask_addrs_buf: []const MaskAddrInstr = &[_]MaskAddrInstr{};
for (util.lines(input)) |line| {
if (std.mem.eql(u8, line[0..4], "mem[")) {
var idx_end = 4;
while (line[idx_end] != ']')
idx_end += 1;
const addr = util.parseUint(u36, line[4..idx_end]) catch unreachable;
const value = util.parseUint(u36, line[(idx_end + 4)..]) catch unreachable;
const masked_value = (value & value_mask) | bitwise_or;
const masked_addr = (addr & addr_mask) | bitwise_or;
mask_values_buf = mask_values_buf ++ [_]MaskValueInstr{.{
.addr = addr,
.value = masked_value,
}};
mask_addrs_buf = mask_addrs_buf ++ [_]MaskAddrInstr{.{
.addr = masked_addr,
.mask = value_mask,
.value = value,
}};
} else {
std.debug.assert(line.len == 36 + 7);
const mask_str = line[7..];
bitwise_or = 0;
value_mask = 0;
addr_mask = 0;
for (mask_str) |c, j| {
switch (c) {
'X' => value_mask |= 1 << (35 - j),
'0' => addr_mask |= 1 << (35 - j),
'1' => bitwise_or |= 1 << (35 - j),
else => unreachable,
}
}
}
}
break :blk struct {
pub const mask_values = mask_values_buf[0..mask_values_buf.len].*;
pub const mask_addrs = mask_addrs_buf[0..mask_addrs_buf.len].*;
};
};
pub fn main(n: util.Utils) !void {
var memory = util.map(u36, u36);
try memory.ensureCapacity(n.arena, 1_000_000);
var part_1: u64 = 0;
for (mask_values) |instr|
memory.putAssumeCapacity(instr.addr, instr.value);
for (memory.items()) |entry|
part_1 += entry.value;
var part_2: u64 = 0;
memory.clearRetainingCapacity();
for (mask_addrs) |instr|
permuteAll(&memory, instr);
for (memory.items()) |entry|
part_2 += entry.value;
try n.out.print("{}\n{}\n", .{ part_1, part_2 });
}
fn permuteAll(memory: *util.Map(u36, u36), instr: MaskAddrInstr) void {
if (instr.mask == 0) {
memory.putAssumeCapacity(instr.addr, instr.value);
} else {
const target_bit = @as(u36, 1) << @ctz(u36, instr.mask);
var new_instr = instr;
new_instr.mask &= ~target_bit;
permuteAll(memory, new_instr);
new_instr.addr |= target_bit;
permuteAll(memory, new_instr);
}
}
|
2020/14.zig
|
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const Tile = struct {
num: usize,
lines: [][]u8,
width: usize,
top: u10,
right: u10,
bottom: u10,
left: u10,
alloc: std.mem.Allocator,
pub fn init(alloc: std.mem.Allocator, chunk: []const u8) !*Tile {
var s = try alloc.create(Tile);
s.alloc = alloc;
var lit = std.mem.split(u8, chunk, "\n");
var first = lit.next().?;
s.num = std.fmt.parseUnsigned(usize, first[5..9], 10) catch unreachable;
var ls = std.ArrayList([]u8).init(alloc);
defer ls.deinit();
while (lit.next()) |line| {
var x = try alloc.dupe(u8, line);
try ls.append(x);
}
s.lines = ls.toOwnedSlice();
s.width = s.lines.len;
s.calc_edges();
return s;
}
pub fn deinit(s: *Tile) void {
for (s.lines) |_, i| {
s.alloc.free(s.lines[i]);
}
s.alloc.free(s.lines);
s.alloc.destroy(s);
}
pub fn flip(s: *Tile) void {
aoc.reverseLines(s.lines);
s.calc_edges();
}
pub fn rotate(s: *Tile) void {
aoc.rotateLines(s.lines);
s.calc_edges();
}
pub fn calc_edges(s: *Tile) void {
const end = s.width - 1;
s.top = 0;
s.right = 0;
s.bottom = 0;
s.left = 0;
var i: usize = 0;
while (i < s.width) : (i += 1) {
s.top <<= 1;
s.left <<= 1;
s.bottom <<= 1;
s.right <<= 1;
if (s.lines[0][i] == '#') {
s.top += 1;
}
if (s.lines[end][i] == '#') {
s.bottom += 1;
}
if (s.lines[i][end] == '#') {
s.right += 1;
}
if (s.lines[i][0] == '#') {
s.left += 1;
}
}
}
};
test "tile" {
var t = try Tile.init(aoc.talloc, "Tile 1951:\n.#.\n.##\n#.#");
defer t.deinit();
try aoc.assertEq(@as(usize, 1951), t.num);
try aoc.assertEq(@as(u10, 2), t.top);
try aoc.assertEq(@as(u10, 3), t.right);
try aoc.assertEq(@as(u10, 5), t.bottom);
try aoc.assertEq(@as(u10, 1), t.left);
t.flip();
try aoc.assertEq(@as(u10, 5), t.top);
try aoc.assertEq(@as(u10, 6), t.right);
try aoc.assertEq(@as(u10, 2), t.bottom);
try aoc.assertEq(@as(u10, 4), t.left);
t.flip();
try aoc.assertEq(@as(u10, 2), t.top);
try aoc.assertEq(@as(u10, 3), t.right);
try aoc.assertEq(@as(u10, 5), t.bottom);
try aoc.assertEq(@as(u10, 1), t.left);
t.rotate();
try aoc.assertEq(@as(u10, 4), t.top);
try aoc.assertEq(@as(u10, 2), t.right);
try aoc.assertEq(@as(u10, 6), t.bottom);
try aoc.assertEq(@as(u10, 5), t.left);
t.rotate();
try aoc.assertEq(@as(u10, 5), t.top);
try aoc.assertEq(@as(u10, 4), t.right);
try aoc.assertEq(@as(u10, 2), t.bottom);
try aoc.assertEq(@as(u10, 6), t.left);
}
fn CanonicalEdge(e: u10) u10 {
const r = @bitReverse(u10, e);
if (e < r) {
return e;
} else {
return r;
}
}
test "canonical" {
try aoc.assertEq(@as(u10, 210), CanonicalEdge(@as(u10, 300)));
try aoc.assertEq(@as(u10, 791), CanonicalEdge(@as(u10, 931)));
}
const Water = struct {
tiles: std.AutoHashMap(usize, *Tile),
edges: std.AutoHashMap(usize, std.ArrayList(usize)),
starter: usize,
width: usize,
alloc: std.mem.Allocator,
debug: bool,
pub fn init(alloc: std.mem.Allocator, in: [][]const u8) !*Water {
var s = try alloc.create(Water);
s.alloc = alloc;
s.debug = false;
s.tiles = std.AutoHashMap(usize, *Tile).init(alloc);
s.edges = std.AutoHashMap(usize, std.ArrayList(usize)).init(alloc);
s.starter = 0;
for (in) |chunk| {
var tile = try Tile.init(alloc, chunk);
try s.tiles.put(tile.num, tile);
for ([_]u10{ tile.top, tile.right, tile.bottom, tile.left }) |e| {
const ce = CanonicalEdge(e);
var kv = try s.edges.getOrPutValue(ce, std.ArrayList(usize).init(alloc));
try kv.value_ptr.append(tile.num);
}
}
s.width = isqrt(s.tiles.count());
if (s.debug) {
std.debug.print("width {}\n", .{s.width});
}
return s;
}
pub fn deinit(s: *Water) void {
var it = s.tiles.iterator();
while (it.next()) |e| {
e.value_ptr.*.deinit();
}
s.tiles.deinit();
var eit = s.edges.iterator();
while (eit.next()) |e| {
e.value_ptr.*.deinit();
}
s.edges.deinit();
s.alloc.destroy(s);
}
pub fn EdgeTileCount(s: *Water, e: u10) usize {
const ce = CanonicalEdge(e);
return (s.edges.get(ce) orelse unreachable).items.len;
}
pub fn Part1(s: *Water) usize {
var p: usize = 1;
var it = s.tiles.iterator();
while (it.next()) |kv| {
var tile = kv.value_ptr.*;
var c: usize = 0;
for ([_]u10{ tile.top, tile.right, tile.bottom, tile.left }) |e| {
if (s.EdgeTileCount(e) > 1) {
c += 1;
}
}
if (c == 2) {
if (s.debug) {
std.debug.print("Found corner {}\n", .{tile.num});
}
p *= tile.num;
s.starter = tile.num; // starter corner for part 2
}
}
return p;
}
pub fn EdgeTiles(s: *Water, e: u10) []usize {
const ce = CanonicalEdge(e);
return (s.edges.get(ce) orelse unreachable).items;
}
pub fn FindRightTile(s: *Water, n: usize) usize {
var t = s.tiles.get(n) orelse unreachable;
var edge = t.right;
var matching = s.EdgeTiles(edge);
var match: usize = 0;
for (matching) |tn| {
if (tn != t.num) {
match = tn;
break;
}
}
if (match == 0) {
if (s.debug) {
std.debug.print("no match found\n", .{});
}
return 0;
}
if (s.debug) {
std.debug.print(" found next tile {}\n", .{match});
}
var next = s.tiles.get(match) orelse unreachable;
var i: u8 = 0;
while (i < 8) : (i += 1) {
if (next.left == edge) {
return next.num;
}
if (i == 3) {
next.flip();
} else {
next.rotate();
}
}
std.debug.print("Failed to find next tile orientation\n", .{});
return 0;
}
pub fn FindBottomTile(s: *Water, n: usize) usize {
var t = s.tiles.get(n) orelse unreachable;
var edge = t.bottom;
var matching = s.EdgeTiles(edge);
var match: usize = 0;
for (matching) |tn| {
if (tn != t.num) {
match = tn;
break;
}
}
if (match == 0) {
if (s.debug) {
std.debug.print("no match found\n", .{});
}
return 0;
}
if (s.debug) {
std.debug.print(" found next tile {}\n", .{match});
}
var next = s.tiles.get(match) orelse unreachable;
var i: u8 = 0;
while (i < 8) : (i += 1) {
if (next.top == edge) {
return next.num;
}
if (i == 3) {
next.flip();
} else {
next.rotate();
}
}
std.debug.print(" Failed to find next tile orientation\n", .{});
return 0;
}
fn isqrt(x: usize) usize {
const ix = @intCast(isize, x);
var q: isize = 1;
while (q <= ix) {
q <<= 2;
}
var z = ix;
var r: isize = 0;
while (q > 1) {
q >>= 2;
var t = z - r - q;
r >>= 1;
if (t >= 0) {
z = t;
r += q;
}
}
return @intCast(usize, r);
}
pub fn Image(s: *Water) [][]const u8 {
var layout = s.alloc.alloc(usize, s.tiles.count()) catch unreachable;
defer s.alloc.free(layout);
if (s.starter == 0) {
_ = s.Part1();
}
if (s.debug) {
std.debug.print("Starting with corner {}\n", .{s.starter});
}
var t = s.tiles.get(s.starter) orelse unreachable;
while (s.EdgeTileCount(t.right) != 2 or s.EdgeTileCount(t.bottom) != 2) {
t.rotate();
}
layout[0] = t.num;
var i: usize = 1;
while (i < s.width * s.width) : (i += 1) {
var tn: usize = undefined;
if ((i % s.width) == 0) {
tn = s.FindBottomTile(layout[i - s.width]);
} else {
tn = s.FindRightTile(layout[i - 1]);
}
if (tn == 0) {
std.debug.print("failed to find next tile\n", .{});
unreachable;
}
if (s.debug) {
std.debug.print("Found #{}: {}\n", .{ i, tn });
}
layout[i] = tn;
}
var tl = t.width - 2;
var nl = s.width * tl;
var res = s.alloc.alloc([]u8, nl) catch unreachable;
var irow: usize = 0;
while (irow < s.width) : (irow += 1) {
var trow: usize = 0;
while (trow < t.width - 2) : (trow += 1) {
res[irow * tl + trow] = s.alloc.alloc(u8, nl) catch unreachable;
var icol: usize = 0;
while (icol < s.width) : (icol += 1) {
var tt = s.tiles.get(layout[irow * s.width + icol]) orelse unreachable;
var tcol: usize = 0;
while (tcol < t.width - 2) : (tcol += 1) {
res[irow * tl + trow][icol * tl + tcol] = tt.lines[trow + 1][tcol + 1];
}
}
}
}
return res;
}
pub fn Part2(s: *Water) usize {
var image = s.Image();
defer {
for (image) |_, j| {
s.alloc.free(image[j]);
}
s.alloc.free(image);
}
if (s.debug) {
for (image) |l| {
std.debug.print("{s}\n", .{l});
}
std.debug.print("\n", .{});
}
const monster = aoc.readLines(s.alloc, @embedFile("monster.txt"));
defer s.alloc.free(monster);
const mh = monster.len;
const mw = monster[0].len;
var monsterSize: usize = aoc.countCharsInLines(monster, '#');
const ih = image.len;
const iw = image[0].len;
if (s.debug) {
std.debug.print("image {} x {}\n", .{ iw, ih });
std.debug.print("monster {} x {} #={}\n", .{ mw, mh, monsterSize });
}
var i: usize = 0;
var mchars: usize = 0;
while (i < 8) : (i += 1) {
var r: usize = 0;
while (r < (ih - mh)) : (r += 1) {
var c: usize = 0;
while (c < (iw - mw)) : (c += 1) {
var match: bool = true;
var mr: usize = 0;
while (mr < mh and match) : (mr += 1) {
var mc: usize = 0;
while (mc < mw and match) : (mc += 1) {
if (monster[mr][mc] != '#') {
continue;
}
if (image[r + mr][c + mc] != '#') {
match = false;
}
}
}
if (match) {
if (s.debug) {
std.debug.print("found monster at {},{}\n", .{ c, r });
}
mchars += monsterSize;
}
}
}
if (i == 3) {
aoc.reverseLines(image);
} else {
var old = image;
defer {
for (old) |_, j| {
s.alloc.free(old[j]);
}
s.alloc.free(old);
}
image = aoc.rotateLinesNonSymmetric(s.alloc, image);
}
}
var c: usize = aoc.countCharsInLines(image, '#');
return c - mchars;
}
};
test "part1" {
const test1 = aoc.readChunks(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readChunks(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var wt = try Water.init(aoc.talloc, test1);
defer wt.deinit();
try aoc.assertEq(@as(usize, 20899048083289), wt.Part1());
var w = try Water.init(aoc.talloc, inp);
defer w.deinit();
try aoc.assertEq(@as(usize, 17712468069479), w.Part1());
}
test "part2" {
const test1 = aoc.readChunks(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const inp = aoc.readChunks(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var wt = try Water.init(aoc.talloc, test1);
defer wt.deinit();
try aoc.assertEq(@as(usize, 273), wt.Part2());
var w = try Water.init(aoc.talloc, inp);
defer w.deinit();
try aoc.assertEq(@as(usize, 2173), w.Part2());
}
fn day20(inp: []const u8, bench: bool) anyerror!void {
const chunks = aoc.readChunks(aoc.halloc, inp);
defer aoc.halloc.free(chunks);
var w = try Water.init(aoc.halloc, chunks);
defer w.deinit();
var p1 = w.Part1();
var p2 = w.Part2();
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day20);
}
|
2020/20/aoc.zig
|
const std = @import("std");
const process = std.process;
const os = std.os;
const fs = std.fs;
pub const log_level: std.log.Level = .debug;
pub const scope_levels = [_]std.log.ScopeLevel{
.{ .scope = .crfl, .level = .debug },
.{ .scope = .config, .level = .info },
.{ .scope = .verbose, .level = .info },
.{ .scope = .sout, .level = .err },
};
const thisLog = std.log.scoped(.crlf);
const configLog = std.log.scoped(.config);
const verboseLog = std.log.scoped(.verbose);
const soutLog = std.log.scoped(.sout);
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const scope_prefix = "(" ++ @tagName(scope) ++ "): ";
const prefix = "[" ++ level.asText() ++ "] " ++ scope_prefix;
// Print the message to stderr, silently ignoring any errors
std.debug.getStderrMutex().lock();
std.debug.getStderrMutex().unlock();
const stderr = std.io.getStdErr().writer();
nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return;
}
const temp_file_name = "asdf.tmp";
var flags = struct {
mk_backup: bool = false,
verbose: bool = false,
const Self = @This();
pub fn status(self: Self, comptime logger: anytype) void {
const fields = @typeInfo(Self).Struct.fields;
inline for (fields) |field| {
if ( field.field_type != bool )
@compileError(@typeName(Self) ++ "has a non-bool field.");
if ( @field(self, field.name) ) {
logger.info("flag: " ++ field.name ++ "", .{});
}
}
}
}{};
const Action = enum { noop, toCRLF, toLF,
pub fn format(
self: @This(),
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype
) !void {
_ = fmt; _ = options;
try std.fmt.format(out_stream, "{s}", .{ @tagName(self) });
}
};
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer thisLog.debug("leaked: {}", .{ gpa.deinit() });
const malloc = gpa.allocator();
const argv = try getArgv(malloc);
defer malloc.free(argv);
if ( argv.len <= 1 ) {
thisLog.warn("no arguments", .{});
os.exit(0);
}
var input_file_name: []const u8 = undefined;
var action: Action = .toCRLF;
var help: bool = false;
for ( argv ) |arg, i| {
// TODO: better argument parsing
if ( i == 0 ) continue
else if ( std.mem.eql(u8, arg, "--help")
or std.mem.eql(u8, arg, "--help") )
help = true
else if ( i == 1 )
input_file_name = arg
else if ( std.mem.eql(u8, arg, "--noop") )
action = .noop
else if ( std.mem.eql(u8, arg, "--to-crlf") )
action = .toCRLF
else if ( std.mem.eql(u8, arg, "--to-lf") )
action = .toLF
else if ( std.mem.eql(u8, arg, "--backup") )
flags.mk_backup = true
else if ( std.mem.eql(u8, arg, "--verbose") )
flags.verbose = true
else thisLog.warn("unused argument [{d}]: {s}", .{ i, arg });
}
if ( help ) {
print_help(argv[0]);
os.exit(0);
}
if ( flags.verbose ) {
configLog.info("target-file: {s}", .{ input_file_name });
configLog.info("action: {s}", .{ action });
flags.status(configLog);
}
const cwd = std.fs.cwd();
var dir = cwd.openDir(input_file_name, .{
.access_sub_paths = true, .iterate = true,
}) catch |err| switch (err) {
error.NotDir => {
try doAction(action, cwd, input_file_name, malloc);
os.exit(0);
},
else => {
thisLog.err("unhandled error: {s}", .{ err });
return;
},
};
defer dir.close();
try traverse(dir, action, malloc);
os.exit(0);
}
fn traverse(dir: fs.Dir, action: Action,
alloc: std.mem.Allocator) anyerror!void {
if ( flags.verbose )
verboseLog.info("Traversing a directory", .{});
var iter = dir.iterate();
while ( try iter.next() ) |entry| {
const name = entry.name;
if ( std.mem.eql(u8, temp_file_name, name) ) continue;
switch ( entry.kind ) {
.Directory => {
var new_dir = try dir.openDir(name, .{
.access_sub_paths = true, .iterate = true,
});
defer new_dir.close();
try traverse(new_dir, action, alloc);
},
.File => try doAction(action, dir, name, alloc),
else => {},
}
}
if ( flags.verbose )
verboseLog.info("Directory finished", .{});
}
fn doAction(action: Action, dir: fs.Dir,
input_file_name: []const u8,
alloc: std.mem.Allocator) !void {
if ( flags.verbose )
verboseLog.info("Doing {} on file: {s}", .{ action, input_file_name });
try actOnTemp(action, dir, input_file_name, alloc);
if ( flags.mk_backup ) {
const backup_name = try alloc.alloc(u8, input_file_name.len + 1);
defer alloc.free(backup_name);
for ( input_file_name ) |c, i| {
backup_name[i] = c;
}
backup_name[input_file_name.len] = '~';
try dir.rename(input_file_name, backup_name);
}
try dir.rename(temp_file_name, input_file_name);
}
fn actOnTemp(action: Action, dir: fs.Dir,
input_file_name: []const u8,
alloc: std.mem.Allocator) !void {
const fin = dir.openFile(input_file_name, .{ .read = true }) catch
|err| {
thisLog.err("Couldn't open file {s}: {s}",
.{ input_file_name, err });
os.exit(1);
};
defer fin.close();
const ftmp = dir.createFile(
temp_file_name, .{ .exclusive = true, }
) catch |err| switch (err) {
error.PathAlreadyExists => {
const realpath = try dir.realpathAlloc(alloc, temp_file_name);
defer alloc.free(realpath);
thisLog.warn("{s}: already exists.\n" ++
"If you are sure that nobody is using this file. " ++
"Consider deleating `{s}` and try again.",
.{ realpath, temp_file_name });
return;
},
else => return err,
};
defer ftmp.close();
try copyWithAction(action, fin, ftmp, alloc);
}
fn copyWithAction(action: Action, fin: fs.File, fout: fs.File,
alloc: std.mem.Allocator) !void {
const fit_in_memory = fin.readToEndAlloc(alloc, 0xFF_FF_FF_FF) catch
|err| switch (err) {
error.FileTooBig => null,
else => return err,
};
if ( fit_in_memory ) |input| {
try actOnFullBuffer(action, input, fout);
alloc.free(input);
} else { // use small buffer
try fin.seekFromEnd(0);
var bytesLeft: usize = try fin.getPos();
try fin.seekTo(0);
var buffer: [0xFF_FF]u8 = undefined;
var lastc: ?u8 = null;
while ( bytesLeft > 0 ) {
const read = try fin.read(&buffer);
bytesLeft -= read;
try actOnBuffer(action, lastc, bytesLeft == 0,
buffer[0..read], fout);
lastc = buffer[read-1];
}
}
}
fn actOnFullBuffer(action: Action, buffer: []const u8, fout: fs.File) !void {
return actOnBuffer(action, null, true, buffer, fout);
}
fn actOnBuffer(action: Action, lastc: ?u8, isLastBuffer: bool,
buffer: []const u8, fout: fs.File) !void {
const debugging = false;
if ( action == .noop ) return;
var c: ?u8 = lastc;
var last_i: usize = 0;
var i: usize = 0;
const limit = if (isLastBuffer) buffer.len else buffer.len - 1;
if ( debugging )
thisLog.debug("DEBUG: limit={d} len={d}\n\n", .{ limit, buffer.len });
while ( last_i < limit ) : ( i += 1 ) {
var stop = false;
while ( i < buffer.len and !stop ) : ( i += 1 ) {
stop = switch ( action ) {
.noop => unreachable,
.toCRLF => buffer[i] == '\n'
and ( c == null or c.? != '\r' ),
.toLF => buffer[i] == '\r',
};
if ( debugging )
thisLog.debug(">>> i={d} c=({x:0>2})" ++
"buffer[i]=({x:0>2}) write=\"{s}\"\n",
.{ i, c, buffer[i], buffer[last_i..i] });
c = buffer[i];
}
if ( stop ) i -= 1;
if ( debugging ) {
thisLog.debug("\nDEBUG: last_i={d} i={d}\n", .{ last_i, i });
thisLog.debug("....write=\"{s}\" buffer[i]={c}({d})\n", .{
buffer[last_i..i],
if (stop) buffer[i] else '1',
if (stop) buffer[i] else '1',
});
}
try fout.writeAll(buffer[last_i..i]);
switch ( action ) {
.noop => unreachable,
.toCRLF => {
if ( stop ) try fout.writeAll("\r");
last_i = i;
},
.toLF =>
last_i = if ( stop ) i + 1 else i,
}
if ( debugging ) thisLog.debug("----------\n", .{});
}
}
fn getArgc(alloc: std.mem.Allocator) usize {
var argIter = process.args();
var argc: usize = 0;
while ( nextArg(&argIter, alloc) ) |_| {
argc += 1;
}
return argc;
}
fn getArgv(alloc: std.mem.Allocator) ![][]const u8 {
var argIter = process.args();
const argc = getArgc(alloc);
const argv = try alloc.alloc([]const u8, argc);
var i: u8 = 0;
while ( nextArg(&argIter, alloc) ) |arg| {
argv[i] = arg;
i += 1;
}
return argv;
}
fn nextArg(argIter: *process.ArgIterator,
alloc: std.mem.Allocator) ?[]u8 {
return argIter.next(alloc) catch |err| blk: {
thisLog.err("Found err: {}", .{ err });
break :blk null;
};
}
fn print_help(prog: []const u8) void {
sout("usage: {s} <target-file> [--noop|--to-crlf|--to-lf] [--backup]\n",
.{ prog });
sout("Converts file or directory subtree"
++ " from linux to windows text file format"
++ " or the other way around\n", .{});
sout("\n Options:\n", .{});
sout(" --noop\n", .{});
sout(" reads the file, but does nothing\n", .{});
sout(" --to-crlf (default)\n", .{});
sout(" adds '\\r' before '\\n' (when missing)\n", .{});
sout(" --to-lf\n", .{});
sout(" removes '\\r' before '\\n'\n", .{});
sout(" --backup\n", .{});
sout(" backups the old file to <target-file>~\n", .{});
sout(" --verbose\n", .{});
sout(" logs to stderr what the program is doing\n", .{});
sout(" --help\n", .{});
sout(" prints this message\n", .{});
}
fn sout(comptime format: []const u8, args: anytype) void {
const stdout = std.io.getStdOut().writer();
stdout.print(format, args) catch |err|
soutLog.err("sout: {}", .{ err });
}
|
src/main.zig
|
const std = @import("std");
const c_args = [_][]const u8{
"-Wunreachable-code",
"-Wall",
"-Wpedantic",
"-fPIC",
};
pub fn build(b: *std.build.Builder) void {
const is_android = b.option(bool, "android", "building for the quest 2") orelse false;
const android_ndk = b.option([]const u8, "android-ndk", "building for the quest 2") orelse if (is_android) @panic("need android ndk") else null;
const luajit_path = b.option([]const u8, "luajit", "path to luajit target binary (required if cross compiling to quest 2)") orelse if (is_android) @panic("need luajit path") else null;
var target: std.zig.CrossTarget = undefined;
if (is_android) {
// snapdragon xr2 is based on kryo
// see https://en.wikipedia.org/wiki/List_of_Qualcomm_Snapdragon_processors#Snapdragon_XR1_and_XR2
target = b.standardTargetOptions(.{
.default_target = .{
.cpu_arch = .aarch64,
.cpu_model = .{ .explicit = &std.Target.aarch64.cpu.kryo },
.os_tag = .linux,
.abi = .android,
},
});
} else {
target = b.standardTargetOptions(.{});
}
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const lib = b.addSharedLibrary("rtsp", "src/main.zig", b.version(0, 0, 1));
lib.setTarget(target);
lib.setBuildMode(mode);
lib.install();
lib.addCSourceFile("src/funny.c", &c_args);
if (!is_android) {
lib.linkLibC();
lib.addIncludeDir("/usr/include/lua5.1");
lib.linkSystemLibrary("lua5.1");
lib.linkSystemLibrary("avformat");
lib.linkSystemLibrary("avutil");
lib.linkSystemLibrary("avcodec");
lib.linkSystemLibrary("swresample");
lib.linkSystemLibrary("swscale");
} else {
lib.force_pic = true;
lib.link_function_sections = true;
lib.bundle_compiler_rt = true;
std.log.info("got ndk '{s}'", .{android_ndk});
const sysroot =
std.fs.path.join(b.allocator, &[_][]const u8{ android_ndk.?, "/toolchains/llvm/prebuilt/linux-x86_64/sysroot" }) catch unreachable;
const include_generic =
std.fs.path.join(b.allocator, &[_][]const u8{ sysroot, "/usr/include" }) catch unreachable;
const include_arch_dependent =
std.fs.path.join(b.allocator, &[_][]const u8{ sysroot, "/usr/include/aarch64-linux-android" }) catch unreachable;
const libgcc_lib_path =
std.fs.path.join(b.allocator, &[_][]const u8{ android_ndk.?, "/toolchains/llvm/prebuilt/linux-x86_64/lib/gcc/aarch64-linux-android/4.9.x" }) catch unreachable;
std.log.info("sysroot '{s}'", .{sysroot});
std.log.info("include_generic '{s}'", .{include_generic});
std.log.info("include_arch_dependent '{s}'", .{include_arch_dependent});
lib.defineCMacro("ANDROID", null);
b.sysroot = sysroot;
lib.setLibCFile(std.build.FileSource{ .path = "./android_libc.txt" });
lib.addIncludeDir(include_generic);
lib.addIncludeDir(include_arch_dependent);
lib.linkLibC();
lib.addIncludeDir("/usr/include/lua5.1");
lib.addIncludeDir("./q2_include");
lib.linkSystemLibrary("c");
lib.linkSystemLibrary("./q2_lib/libavcodec.so");
lib.linkSystemLibrary("./q2_lib/libavformat.so");
lib.linkSystemLibrary("./q2_lib/libavutil.so");
lib.linkSystemLibrary("./q2_lib/libswresample.so");
lib.linkSystemLibrary("./q2_lib/libswscale.so");
lib.addLibPath(std.fs.path.dirname(luajit_path.?).?);
lib.linkSystemLibrary("luajit");
lib.addLibPath(libgcc_lib_path);
lib.linkSystemLibrary("gcc");
}
const main_tests = b.addTest("src/main.zig");
main_tests.setBuildMode(mode);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
}
|
build.zig
|
const std = @import("std");
const testing = std.testing;
pub const Uuid = struct {
bytes: [16]u8,
pub const zero = Uuid{ .bytes = std.mem.zeroes([16]u8) };
pub fn v3(ns: []const u8, name: []const u8) Uuid {
return hashInit(std.crypto.hash.Md5, 3, ns, name);
}
pub fn v4() Uuid {
var v: [16]u8 = undefined;
std.crypto.random.bytes(&v);
return init(4, v);
}
pub fn v5(ns: []const u8, name: []const u8) Uuid {
return hashInit(std.crypto.hash.Sha1, 5, ns, name);
}
const ParseError = error{ InvalidCharacter, InvalidLength };
pub fn fromString(str: []const u8) ParseError!Uuid {
var v: [16]u8 = undefined;
var i: u64 = 0;
for (v) |*b| {
const high = try nextHexDig(str, &i);
const low = try nextHexDig(str, &i);
b.* = (high << 4) | low;
}
if (i != str.len) {
return error.InvalidLength;
}
return Uuid{ .bytes = v };
}
fn nextHexDig(str: []const u8, i: *u64) ParseError!u8 {
while (i.* < str.len) {
if (str[i.*] == '-') {
i.* += 1;
} else {
const c = try std.fmt.charToDigit(str[i.*], 16);
i.* += 1;
return c;
}
}
return error.InvalidLength;
}
pub fn toString(self: Uuid) [36]u8 {
var buf: [36]u8 = undefined;
const slice = std.fmt.bufPrint(&buf, "{}-{}-{}-{}-{}", .{
std.fmt.fmtSliceHexLower(self.bytes[0..4]),
std.fmt.fmtSliceHexLower(self.bytes[4..6]),
std.fmt.fmtSliceHexLower(self.bytes[6..8]),
std.fmt.fmtSliceHexLower(self.bytes[8..10]),
std.fmt.fmtSliceHexLower(self.bytes[10..16]),
}) catch unreachable;
std.debug.assert(slice.len == buf.len);
return buf;
}
pub fn fromInt(n: u128) Uuid {
var v: [16]u8 = undefined;
std.mem.writeIntBig(u128, &v, n);
return Uuid{ .bytes = v };
}
pub fn toInt(self: Uuid) u128 {
return std.mem.readIntBig(u128, &self.bytes);
}
fn init(comptime version: u4, bytes: [16]u8) Uuid {
var v: [16]u8 = bytes;
v[8] = (v[8] & 0x3f) | 0x80; // Set variant
v[6] = (v[6] & 0x0f) | (@as(u8, version) << 4); // Set version
return .{ .bytes = v };
}
fn hashInit(comptime Hash: type, comptime version: u4, ns: []const u8, name: []const u8) Uuid {
var hasher = Hash.init(.{});
hasher.update(ns);
hasher.update(name);
var hashed: [Hash.digest_length]u8 = undefined;
hasher.final(&hashed);
return init(version, hashed[0..16].*);
}
pub fn format(self: Uuid, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "s")) {
return std.fmt.formatBuf(&self.toString(), options, writer);
} else {
return std.fmt.formatIntValue(self.toInt(), fmt, options, writer);
}
}
};
test "UUID v3 generation" {
const a = Uuid.v3(&Uuid.zero.bytes, "foo bar");
const b = Uuid.v3(&Uuid.zero.bytes, "foo bar");
const c = Uuid.v3(&Uuid.zero.bytes, "bar baz");
const d = Uuid.v3("helloooo", "foo bar");
try testing.expectEqualSlices(
u8,
&(Uuid.fromString("5d686fd9-3ac1-33e2-9493-c2d436bbaee3") catch unreachable).bytes,
&a.bytes,
);
try testing.expectEqualSlices(u8, &a.bytes, &b.bytes);
try testNotEqual(a, c);
try testNotEqual(a, d);
}
test "UUID v4 generation" {
const a = Uuid.v4();
const b = Uuid.v4();
try testNotEqual(a, b);
}
test "UUID v5 generation" {
const a = Uuid.v5(&Uuid.zero.bytes, "foo bar");
const b = Uuid.v5(&Uuid.zero.bytes, "foo bar");
const c = Uuid.v5(&Uuid.zero.bytes, "bar baz");
const d = Uuid.v3(&Uuid.zero.bytes, "foo bar");
const e = Uuid.v5("hellooooo", "foo bar");
try testing.expectEqualSlices(
u8,
&(Uuid.fromString("963bee72-17fa-5f11-a921-ac4d98f53b5e") catch unreachable).bytes,
&a.bytes,
);
try testing.expectEqualSlices(u8, &a.bytes, &b.bytes);
try testNotEqual(a, c);
try testNotEqual(a, d);
try testNotEqual(a, e);
}
const test_uuid = blk: {
var buf: [16]u8 = undefined;
_ = std.fmt.hexToBytes(&buf, "00112233445566778899aabbccddeeff") catch unreachable;
break :blk Uuid{
.bytes = buf,
};
};
test "fromString" {
const id = try Uuid.fromString("00112233445566778899aabbccddeeff");
try testing.expectEqualSlices(u8, &test_uuid.bytes, &id.bytes);
const id2 = try Uuid.fromString("00112233-4455-6677-8899-aabbccddeeff");
try testing.expectEqualSlices(u8, &test_uuid.bytes, &id2.bytes);
try testing.expectError(error.InvalidCharacter, Uuid.fromString("00112233+4455-6677-8899-aabbccddeeff"));
try testing.expectError(error.InvalidLength, Uuid.fromString("00112233-4455-6677-8899-aabbccddeeff0"));
try testing.expectError(error.InvalidLength, Uuid.fromString("00112233-4455-6677-8899-aabbccddeef"));
}
test "toString" {
try testing.expectEqualStrings(
"00112233-4455-6677-8899-aabbccddeeff",
&test_uuid.toString(),
);
}
test "fromInt" {
const id = Uuid.fromInt(0x00112233445566778899aabbccddeeff);
try testing.expectEqualSlices(u8, &test_uuid.bytes, &id.bytes);
}
test "toInt" {
const i: u128 = 0x00112233445566778899aabbccddeeff;
try testing.expectEqual(i, test_uuid.toInt());
}
test "format" {
try testing.expectFmt("00112233-4455-6677-8899-aabbccddeeff", "{}", .{test_uuid});
try testing.expectFmt("00112233-4455-6677-8899-aabbccddeeff", "{s}", .{test_uuid});
try testing.expectFmt("00112233-4455-6677-8899-aabbccddeeff", "{any}", .{test_uuid});
try testing.expectFmt("00112233445566778899aabbccddeeff", "{x:0>32}", .{test_uuid});
}
fn testNotEqual(a: Uuid, b: Uuid) !void {
var eql = true;
for (a.bytes) |ab, i| {
if (ab != b.bytes[i]) {
eql = false;
break;
}
}
try testing.expect(!eql);
}
|
uuid.zig
|
const std = @import("std");
const os = std.os;
const assert = std.debug.assert;
const sockaddr = std.c.sockaddr;
const Address = std.net.Address;
const Allocator = std.mem.Allocator;
// What a router should do:
// 1. Poll and wait for a file descriptor to be ready
// 2. Read the available data to buffer
// 3. Interpret the IP packet header
// 4. Assert the correct destination of the arriving packet
// 5. Pass it to the transport that will take care of sending it
// 6. Repeat.
// Misc. Allow insertion and deletion of clients from the loop
pub const Error = error{ Interrupted, HandlerRead, Resources, NoHandler };
/// The definition for the router function that finds the destination
/// socket from a given Address structure.
pub const GetSock = fn (Address) Error!i32;
/// A representation of a Router peer.
pub const Peer = struct {
socket: i32,
address: Address,
handleFn: fn (self: *Self, map: *AddressMap) Error!void,
const Self = @This();
pub fn handle(self: *Self, map: *AddressMap) Error!void {
return self.handleFn(self, map);
}
};
pub const AddressMap = struct {
map: MapType,
lock: std.Mutex,
const Self = @This();
const MapType = std.AutoHashMapUnmanaged(sockaddr, i32);
pub fn init(allocator: *Allocator) AddressMap {
return .{
.map = MapType.init(allocator),
.lock = .{},
};
}
pub fn deinit(self: *Self, allocator: *Allocator) void {
self.map.deinit(allocator);
}
};
/// Implements the packet handling mechanism.
pub const Router = struct {
epoll_fd: i32,
epoll_timeout: i32,
max_concurrent: u32,
allocator: *Allocator,
peers_lock: std.Mutex,
peers: PeerMap,
addresses: AddressMap,
const Self = @This();
const PeerMap = std.AutoHashMapUnmanaged(i32, *Peer);
/// Starts processing the incoming packets and writing them. Will exit after a configured timeout,
/// so it must be continously run in a loop with quick successions with optional status checking before etc.
pub fn run(self: *Self) Error!void {
const events = self.allocator.alloc(os.epoll_event, self.max_concurrent) catch return error.Resources;
defer self.allocator.free(events);
try self.epollProc(events);
}
/// Register a handler so that it could start participating in the routing process.
/// First, we insert the handler into the map, only later activating it via epoll.
///
/// It accepts a handler and epoll flags that will influence the behaviour of signalling.
/// Leaving flags to zero will result in a correct default behaviour. Polling for write
/// availability is disallowed and will crash.
pub fn register(self: *Self, peer: *Peer, flags: u32) !void {
// We do not want to poll for write availability.
assert(flags & os.EPOLLOUT == 0);
if (self.peers_lock.tryAcquire()) |lock| {
self.peers.put(self.allocator, peer.socket, peer) catch |err| {
lock.release();
switch (err) {
error.OutOfMemory => return error.Resources,
else => return err,
}
};
lock.release();
}
if (self.addresses.lock.tryAcquire()) |lock| {
self.addresses.map.put(self.allocator, peer.address.any, peer.socket) catch |err| {
lock.release();
switch (err) {
error.OutOfMemory => return error.Resources,
else => return err,
}
};
lock.release();
}
var ee = os.linux.epoll_event{
.events = flags | os.EPOLLIN,
.data = .{ .fd = peer.socket },
};
try os.epoll_ctl(self.epoll_fd, os.EPOLL_CTL_ADD, peer.socket, &ee);
}
/// Removes the handler from routing. It's first disabled via epoll, to prevent
/// the routing process from trying to access it. Only then it is removed from the map.
pub fn unregister(self: *Self, peer: *Peer) void {
os.epoll_ctl(self.epoll_fd, os.EPOLL_CTL_DEL, peer.socket, null) catch {};
if (self.addresses.lock.tryAcquire()) |lock| {
_ = self.addresses.map.remove(peer.address.any);
lock.release();
}
if (self.peers_lock.tryAcquire()) |lock| {
_ = self.peers.remove(peer.socket);
lock.release();
}
}
pub fn init(allocator: *Allocator, max_concurrent: u32, epoll_timeout: i32) !Self {
return Self{
.epoll_fd = try os.epoll_create1(0),
.epoll_timeout = epoll_timeout,
.max_concurrent = max_concurrent,
.allocator = allocator,
.peers = PeerMap.init(allocator),
.peers_lock = std.Mutex{},
.addresses = AddressMap.init(allocator),
};
}
pub fn deinit(self: *Self) void {
os.close(self.epoll_fd);
self.addresses.deinit(self.allocator);
self.peers.deinit(self.allocator);
}
fn epollProc(self: *Self, e: []os.epoll_event) Error!void {
var ret: usize = 0;
var first: bool = true;
while (ret > 0 or first) : (ret = os.epoll_wait(self.epoll_fd, e, self.epoll_timeout)) {
for (e[0..ret]) |event| {
try self.execHandler(event);
}
first = false;
}
}
fn execHandler(self: *Self, event: os.epoll_event) Error!void {
var peerEntry: ?*Peer = undefined;
if (self.peers_lock.tryAcquire()) |lock| {
peerEntry = self.peers.get(event.data.fd);
lock.release();
}
if (peerEntry) |peer| {
peer.handle(&self.addresses) catch |err| {
switch (err) {
error.HandlerRead => self.unregister(peer),
error.Interrupted => unreachable,
error.Resources => unreachable,
error.NoHandler => unreachable,
}
};
} else {
return error.NoHandler;
}
}
};
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
const expectEqualStrings = testing.expectEqualStrings;
const expectError = testing.expectError;
const FailingAllocator = testing.FailingAllocator;
const MockPeer = struct {
ret_error: bool,
handle_count: i32,
last_byte_count: usize,
last_content: [128:0]u8,
peer: Peer,
const Self = @This();
pub fn init(socket: i32, addr: Address, ret_error: bool) Self {
return .{
.ret_error = ret_error,
.handle_count = 0,
.last_byte_count = 0,
.last_content = [_:0]u8{0} ** 128,
.peer = .{
.address = addr,
.socket = socket,
.handleFn = handle,
},
};
}
fn handle(peer: *Peer, map: *AddressMap) Error!void {
const self = @fieldParentPtr(Self, "peer", peer);
self.handle_count += 1;
if (self.ret_error) {
return error.HandlerRead;
}
self.last_byte_count = os.read(peer.socket, self.last_content[0..]) catch |err| return error.HandlerRead;
}
};
test "epoll" {
var router = try Router.init(std.heap.page_allocator, 1, 100);
defer router.deinit();
const pipes = try os.pipe();
defer os.close(pipes[0]);
defer os.close(pipes[1]);
const address = try Address.parseIp4("172.16.31.10", 0);
var mock = MockPeer.init(pipes[0], address, false);
try router.register(&mock.peer, 0);
const written = try os.write(pipes[1], "hello world!");
expectEqual(@intCast(usize, 12), written);
try router.run();
expectEqual(@intCast(i32, 1), mock.handle_count);
expectEqual(@intCast(usize, 12), mock.last_byte_count);
expectEqualStrings("hello world!", mock.last_content[0..12 :0]);
}
test "self unregister on failed read" {
var router = try Router.init(std.heap.page_allocator, 1, 100);
defer router.deinit();
const pipes = try os.pipe();
defer os.close(pipes[0]);
defer os.close(pipes[1]);
const address = try Address.parseIp4("172.16.31.10", 0);
var mock = MockPeer.init(pipes[0], address, true);
try router.register(&mock.peer, 0);
var written = try os.write(pipes[1], "hello world!");
expectEqual(@intCast(usize, 12), written);
try router.run();
expectEqual(@intCast(i32, 1), mock.handle_count);
expectEqual(@intCast(usize, 0), mock.last_byte_count);
// Verify that the handler had unregistered itself.
written = try os.write(pipes[1], "hello world!");
expectEqual(@intCast(usize, 12), written);
try router.run();
// Expect unchanged values after self unregister.
expectEqual(@intCast(i32, 1), mock.handle_count);
expectEqual(@intCast(usize, 0), mock.last_byte_count);
}
test "no resources Router register" {
var allocator = FailingAllocator.init(std.heap.page_allocator, 0);
var router = try Router.init(&allocator.allocator, 1, 100);
defer router.deinit();
const address = try Address.parseIp4("172.16.31.10", 0);
var mock = MockPeer.init(0, address, true);
expectError(error.Resources, router.register(&mock.peer, 0));
}
test "no resources Router run" {
var allocator = FailingAllocator.init(std.heap.page_allocator, 2);
var router = try Router.init(&allocator.allocator, 1, 100);
defer router.deinit();
const pipes = try os.pipe();
defer os.close(pipes[0]);
defer os.close(pipes[1]);
const address = try Address.parseIp4("172.16.31.10", 0);
var mock = MockPeer.init(pipes[0], address, true);
try router.register(&mock.peer, 0);
expectError(error.Resources, router.run());
}
|
src/router.zig
|
//--------------------------------------------------------------------------------
// Section: Types (4)
//--------------------------------------------------------------------------------
pub const JOB_OBJECT_LIMIT = enum(u32) {
LIMIT_WORKINGSET = 1,
LIMIT_PROCESS_TIME = 2,
LIMIT_JOB_TIME = 4,
LIMIT_ACTIVE_PROCESS = 8,
LIMIT_AFFINITY = 16,
LIMIT_PRIORITY_CLASS = 32,
LIMIT_PRESERVE_JOB_TIME = 64,
LIMIT_SCHEDULING_CLASS = 128,
LIMIT_PROCESS_MEMORY = 256,
LIMIT_JOB_MEMORY = 512,
// LIMIT_JOB_MEMORY_HIGH = 512, this enum value conflicts with LIMIT_JOB_MEMORY
LIMIT_DIE_ON_UNHANDLED_EXCEPTION = 1024,
LIMIT_BREAKAWAY_OK = 2048,
LIMIT_SILENT_BREAKAWAY_OK = 4096,
LIMIT_KILL_ON_JOB_CLOSE = 8192,
LIMIT_SUBSET_AFFINITY = 16384,
LIMIT_JOB_MEMORY_LOW = 32768,
LIMIT_JOB_READ_BYTES = 65536,
LIMIT_JOB_WRITE_BYTES = 131072,
LIMIT_RATE_CONTROL = 262144,
// LIMIT_CPU_RATE_CONTROL = 262144, this enum value conflicts with LIMIT_RATE_CONTROL
LIMIT_IO_RATE_CONTROL = 524288,
LIMIT_NET_RATE_CONTROL = 1048576,
LIMIT_VALID_FLAGS = 524287,
BASIC_LIMIT_VALID_FLAGS = 255,
EXTENDED_LIMIT_VALID_FLAGS = 32767,
NOTIFICATION_LIMIT_VALID_FLAGS = 2064900,
_,
pub fn initFlags(o: struct {
LIMIT_WORKINGSET: u1 = 0,
LIMIT_PROCESS_TIME: u1 = 0,
LIMIT_JOB_TIME: u1 = 0,
LIMIT_ACTIVE_PROCESS: u1 = 0,
LIMIT_AFFINITY: u1 = 0,
LIMIT_PRIORITY_CLASS: u1 = 0,
LIMIT_PRESERVE_JOB_TIME: u1 = 0,
LIMIT_SCHEDULING_CLASS: u1 = 0,
LIMIT_PROCESS_MEMORY: u1 = 0,
LIMIT_JOB_MEMORY: u1 = 0,
LIMIT_DIE_ON_UNHANDLED_EXCEPTION: u1 = 0,
LIMIT_BREAKAWAY_OK: u1 = 0,
LIMIT_SILENT_BREAKAWAY_OK: u1 = 0,
LIMIT_KILL_ON_JOB_CLOSE: u1 = 0,
LIMIT_SUBSET_AFFINITY: u1 = 0,
LIMIT_JOB_MEMORY_LOW: u1 = 0,
LIMIT_JOB_READ_BYTES: u1 = 0,
LIMIT_JOB_WRITE_BYTES: u1 = 0,
LIMIT_RATE_CONTROL: u1 = 0,
LIMIT_IO_RATE_CONTROL: u1 = 0,
LIMIT_NET_RATE_CONTROL: u1 = 0,
LIMIT_VALID_FLAGS: u1 = 0,
BASIC_LIMIT_VALID_FLAGS: u1 = 0,
EXTENDED_LIMIT_VALID_FLAGS: u1 = 0,
NOTIFICATION_LIMIT_VALID_FLAGS: u1 = 0,
}) JOB_OBJECT_LIMIT {
return @intToEnum(JOB_OBJECT_LIMIT,
(if (o.LIMIT_WORKINGSET == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_WORKINGSET) else 0)
| (if (o.LIMIT_PROCESS_TIME == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_PROCESS_TIME) else 0)
| (if (o.LIMIT_JOB_TIME == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_JOB_TIME) else 0)
| (if (o.LIMIT_ACTIVE_PROCESS == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_ACTIVE_PROCESS) else 0)
| (if (o.LIMIT_AFFINITY == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_AFFINITY) else 0)
| (if (o.LIMIT_PRIORITY_CLASS == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_PRIORITY_CLASS) else 0)
| (if (o.LIMIT_PRESERVE_JOB_TIME == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_PRESERVE_JOB_TIME) else 0)
| (if (o.LIMIT_SCHEDULING_CLASS == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_SCHEDULING_CLASS) else 0)
| (if (o.LIMIT_PROCESS_MEMORY == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_PROCESS_MEMORY) else 0)
| (if (o.LIMIT_JOB_MEMORY == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_JOB_MEMORY) else 0)
| (if (o.LIMIT_DIE_ON_UNHANDLED_EXCEPTION == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_DIE_ON_UNHANDLED_EXCEPTION) else 0)
| (if (o.LIMIT_BREAKAWAY_OK == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_BREAKAWAY_OK) else 0)
| (if (o.LIMIT_SILENT_BREAKAWAY_OK == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_SILENT_BREAKAWAY_OK) else 0)
| (if (o.LIMIT_KILL_ON_JOB_CLOSE == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_KILL_ON_JOB_CLOSE) else 0)
| (if (o.LIMIT_SUBSET_AFFINITY == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_SUBSET_AFFINITY) else 0)
| (if (o.LIMIT_JOB_MEMORY_LOW == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_JOB_MEMORY_LOW) else 0)
| (if (o.LIMIT_JOB_READ_BYTES == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_JOB_READ_BYTES) else 0)
| (if (o.LIMIT_JOB_WRITE_BYTES == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_JOB_WRITE_BYTES) else 0)
| (if (o.LIMIT_RATE_CONTROL == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_RATE_CONTROL) else 0)
| (if (o.LIMIT_IO_RATE_CONTROL == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_IO_RATE_CONTROL) else 0)
| (if (o.LIMIT_NET_RATE_CONTROL == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_NET_RATE_CONTROL) else 0)
| (if (o.LIMIT_VALID_FLAGS == 1) @enumToInt(JOB_OBJECT_LIMIT.LIMIT_VALID_FLAGS) else 0)
| (if (o.BASIC_LIMIT_VALID_FLAGS == 1) @enumToInt(JOB_OBJECT_LIMIT.BASIC_LIMIT_VALID_FLAGS) else 0)
| (if (o.EXTENDED_LIMIT_VALID_FLAGS == 1) @enumToInt(JOB_OBJECT_LIMIT.EXTENDED_LIMIT_VALID_FLAGS) else 0)
| (if (o.NOTIFICATION_LIMIT_VALID_FLAGS == 1) @enumToInt(JOB_OBJECT_LIMIT.NOTIFICATION_LIMIT_VALID_FLAGS) else 0)
);
}
};
pub const JOB_OBJECT_LIMIT_WORKINGSET = JOB_OBJECT_LIMIT.LIMIT_WORKINGSET;
pub const JOB_OBJECT_LIMIT_PROCESS_TIME = JOB_OBJECT_LIMIT.LIMIT_PROCESS_TIME;
pub const JOB_OBJECT_LIMIT_JOB_TIME = JOB_OBJECT_LIMIT.LIMIT_JOB_TIME;
pub const JOB_OBJECT_LIMIT_ACTIVE_PROCESS = JOB_OBJECT_LIMIT.LIMIT_ACTIVE_PROCESS;
pub const JOB_OBJECT_LIMIT_AFFINITY = JOB_OBJECT_LIMIT.LIMIT_AFFINITY;
pub const JOB_OBJECT_LIMIT_PRIORITY_CLASS = JOB_OBJECT_LIMIT.LIMIT_PRIORITY_CLASS;
pub const JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME = JOB_OBJECT_LIMIT.LIMIT_PRESERVE_JOB_TIME;
pub const JOB_OBJECT_LIMIT_SCHEDULING_CLASS = JOB_OBJECT_LIMIT.LIMIT_SCHEDULING_CLASS;
pub const JOB_OBJECT_LIMIT_PROCESS_MEMORY = JOB_OBJECT_LIMIT.LIMIT_PROCESS_MEMORY;
pub const JOB_OBJECT_LIMIT_JOB_MEMORY = JOB_OBJECT_LIMIT.LIMIT_JOB_MEMORY;
pub const JOB_OBJECT_LIMIT_JOB_MEMORY_HIGH = JOB_OBJECT_LIMIT.LIMIT_JOB_MEMORY;
pub const JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION = JOB_OBJECT_LIMIT.LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
pub const JOB_OBJECT_LIMIT_BREAKAWAY_OK = JOB_OBJECT_LIMIT.LIMIT_BREAKAWAY_OK;
pub const JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK = JOB_OBJECT_LIMIT.LIMIT_SILENT_BREAKAWAY_OK;
pub const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = JOB_OBJECT_LIMIT.LIMIT_KILL_ON_JOB_CLOSE;
pub const JOB_OBJECT_LIMIT_SUBSET_AFFINITY = JOB_OBJECT_LIMIT.LIMIT_SUBSET_AFFINITY;
pub const JOB_OBJECT_LIMIT_JOB_MEMORY_LOW = JOB_OBJECT_LIMIT.LIMIT_JOB_MEMORY_LOW;
pub const JOB_OBJECT_LIMIT_JOB_READ_BYTES = JOB_OBJECT_LIMIT.LIMIT_JOB_READ_BYTES;
pub const JOB_OBJECT_LIMIT_JOB_WRITE_BYTES = JOB_OBJECT_LIMIT.LIMIT_JOB_WRITE_BYTES;
pub const JOB_OBJECT_LIMIT_RATE_CONTROL = JOB_OBJECT_LIMIT.LIMIT_RATE_CONTROL;
pub const JOB_OBJECT_LIMIT_CPU_RATE_CONTROL = JOB_OBJECT_LIMIT.LIMIT_RATE_CONTROL;
pub const JOB_OBJECT_LIMIT_IO_RATE_CONTROL = JOB_OBJECT_LIMIT.LIMIT_IO_RATE_CONTROL;
pub const JOB_OBJECT_LIMIT_NET_RATE_CONTROL = JOB_OBJECT_LIMIT.LIMIT_NET_RATE_CONTROL;
pub const JOB_OBJECT_LIMIT_VALID_FLAGS = JOB_OBJECT_LIMIT.LIMIT_VALID_FLAGS;
pub const JOB_OBJECT_BASIC_LIMIT_VALID_FLAGS = JOB_OBJECT_LIMIT.BASIC_LIMIT_VALID_FLAGS;
pub const JOB_OBJECT_EXTENDED_LIMIT_VALID_FLAGS = JOB_OBJECT_LIMIT.EXTENDED_LIMIT_VALID_FLAGS;
pub const JOB_OBJECT_NOTIFICATION_LIMIT_VALID_FLAGS = JOB_OBJECT_LIMIT.NOTIFICATION_LIMIT_VALID_FLAGS;
pub const JOB_OBJECT_UILIMIT = enum(u32) {
NONE = 0,
HANDLES = 1,
READCLIPBOARD = 2,
WRITECLIPBOARD = 4,
SYSTEMPARAMETERS = 8,
DISPLAYSETTINGS = 16,
GLOBALATOMS = 32,
DESKTOP = 64,
EXITWINDOWS = 128,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
HANDLES: u1 = 0,
READCLIPBOARD: u1 = 0,
WRITECLIPBOARD: u1 = 0,
SYSTEMPARAMETERS: u1 = 0,
DISPLAYSETTINGS: u1 = 0,
GLOBALATOMS: u1 = 0,
DESKTOP: u1 = 0,
EXITWINDOWS: u1 = 0,
}) JOB_OBJECT_UILIMIT {
return @intToEnum(JOB_OBJECT_UILIMIT,
(if (o.NONE == 1) @enumToInt(JOB_OBJECT_UILIMIT.NONE) else 0)
| (if (o.HANDLES == 1) @enumToInt(JOB_OBJECT_UILIMIT.HANDLES) else 0)
| (if (o.READCLIPBOARD == 1) @enumToInt(JOB_OBJECT_UILIMIT.READCLIPBOARD) else 0)
| (if (o.WRITECLIPBOARD == 1) @enumToInt(JOB_OBJECT_UILIMIT.WRITECLIPBOARD) else 0)
| (if (o.SYSTEMPARAMETERS == 1) @enumToInt(JOB_OBJECT_UILIMIT.SYSTEMPARAMETERS) else 0)
| (if (o.DISPLAYSETTINGS == 1) @enumToInt(JOB_OBJECT_UILIMIT.DISPLAYSETTINGS) else 0)
| (if (o.GLOBALATOMS == 1) @enumToInt(JOB_OBJECT_UILIMIT.GLOBALATOMS) else 0)
| (if (o.DESKTOP == 1) @enumToInt(JOB_OBJECT_UILIMIT.DESKTOP) else 0)
| (if (o.EXITWINDOWS == 1) @enumToInt(JOB_OBJECT_UILIMIT.EXITWINDOWS) else 0)
);
}
};
pub const JOB_OBJECT_UILIMIT_NONE = JOB_OBJECT_UILIMIT.NONE;
pub const JOB_OBJECT_UILIMIT_HANDLES = JOB_OBJECT_UILIMIT.HANDLES;
pub const JOB_OBJECT_UILIMIT_READCLIPBOARD = JOB_OBJECT_UILIMIT.READCLIPBOARD;
pub const JOB_OBJECT_UILIMIT_WRITECLIPBOARD = JOB_OBJECT_UILIMIT.WRITECLIPBOARD;
pub const JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS = JOB_OBJECT_UILIMIT.SYSTEMPARAMETERS;
pub const JOB_OBJECT_UILIMIT_DISPLAYSETTINGS = JOB_OBJECT_UILIMIT.DISPLAYSETTINGS;
pub const JOB_OBJECT_UILIMIT_GLOBALATOMS = JOB_OBJECT_UILIMIT.GLOBALATOMS;
pub const JOB_OBJECT_UILIMIT_DESKTOP = JOB_OBJECT_UILIMIT.DESKTOP;
pub const JOB_OBJECT_UILIMIT_EXITWINDOWS = JOB_OBJECT_UILIMIT.EXITWINDOWS;
pub const JOB_OBJECT_SECURITY = enum(u32) {
NO_ADMIN = 1,
RESTRICTED_TOKEN = 2,
ONLY_TOKEN = 4,
FILTER_TOKENS = 8,
VALID_FLAGS = 15,
_,
pub fn initFlags(o: struct {
NO_ADMIN: u1 = 0,
RESTRICTED_TOKEN: u1 = 0,
ONLY_TOKEN: u1 = 0,
FILTER_TOKENS: u1 = 0,
VALID_FLAGS: u1 = 0,
}) JOB_OBJECT_SECURITY {
return @intToEnum(JOB_OBJECT_SECURITY,
(if (o.NO_ADMIN == 1) @enumToInt(JOB_OBJECT_SECURITY.NO_ADMIN) else 0)
| (if (o.RESTRICTED_TOKEN == 1) @enumToInt(JOB_OBJECT_SECURITY.RESTRICTED_TOKEN) else 0)
| (if (o.ONLY_TOKEN == 1) @enumToInt(JOB_OBJECT_SECURITY.ONLY_TOKEN) else 0)
| (if (o.FILTER_TOKENS == 1) @enumToInt(JOB_OBJECT_SECURITY.FILTER_TOKENS) else 0)
| (if (o.VALID_FLAGS == 1) @enumToInt(JOB_OBJECT_SECURITY.VALID_FLAGS) else 0)
);
}
};
pub const JOB_OBJECT_SECURITY_NO_ADMIN = JOB_OBJECT_SECURITY.NO_ADMIN;
pub const JOB_OBJECT_SECURITY_RESTRICTED_TOKEN = JOB_OBJECT_SECURITY.RESTRICTED_TOKEN;
pub const JOB_OBJECT_SECURITY_ONLY_TOKEN = JOB_OBJECT_SECURITY.ONLY_TOKEN;
pub const JOB_OBJECT_SECURITY_FILTER_TOKENS = JOB_OBJECT_SECURITY.FILTER_TOKENS;
pub const JOB_OBJECT_SECURITY_VALID_FLAGS = JOB_OBJECT_SECURITY.VALID_FLAGS;
pub const JOBOBJECT_IO_RATE_CONTROL_INFORMATION = extern struct {
MaxIops: i64,
MaxBandwidth: i64,
ReservationIops: i64,
VolumeName: ?[*:0]const u16,
BaseIoSize: u32,
ControlFlags: JOB_OBJECT_IO_RATE_CONTROL_FLAGS,
};
//--------------------------------------------------------------------------------
// Section: Functions (13)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn IsProcessInJob(
ProcessHandle: ?HANDLE,
JobHandle: ?HANDLE,
Result: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateJobObjectW(
lpJobAttributes: ?*SECURITY_ATTRIBUTES,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "KERNEL32" fn FreeMemoryJobObject(
Buffer: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenJobObjectW(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn AssignProcessToJobObject(
hJob: ?HANDLE,
hProcess: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn TerminateJobObject(
hJob: ?HANDLE,
uExitCode: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetInformationJobObject(
hJob: ?HANDLE,
JobObjectInformationClass: JOBOBJECTINFOCLASS,
// TODO: what to do with BytesParamIndex 3?
lpJobObjectInformation: ?*c_void,
cbJobObjectInformationLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "KERNEL32" fn SetIoRateControlInformationJobObject(
hJob: ?HANDLE,
IoRateControlInfo: ?*JOBOBJECT_IO_RATE_CONTROL_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn QueryInformationJobObject(
hJob: ?HANDLE,
JobObjectInformationClass: JOBOBJECTINFOCLASS,
// TODO: what to do with BytesParamIndex 3?
lpJobObjectInformation: ?*c_void,
cbJobObjectInformationLength: u32,
lpReturnLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "KERNEL32" fn QueryIoRateControlInformationJobObject(
hJob: ?HANDLE,
VolumeName: ?[*:0]const u16,
InfoBlocks: ?*?*JOBOBJECT_IO_RATE_CONTROL_INFORMATION,
InfoBlockCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "USER32" fn UserHandleGrantAccess(
hUserHandle: ?HANDLE,
hJob: ?HANDLE,
bGrant: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateJobObjectA(
lpJobAttributes: ?*SECURITY_ATTRIBUTES,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenJobObjectA(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (2)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const CreateJobObject = thismodule.CreateJobObjectA;
pub const OpenJobObject = thismodule.OpenJobObjectA;
},
.wide => struct {
pub const CreateJobObject = thismodule.CreateJobObjectW;
pub const OpenJobObject = thismodule.OpenJobObjectW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const CreateJobObject = *opaque{};
pub const OpenJobObject = *opaque{};
} else struct {
pub const CreateJobObject = @compileError("'CreateJobObject' requires that UNICODE be set to true or false in the root module");
pub const OpenJobObject = @compileError("'OpenJobObject' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (7)
//--------------------------------------------------------------------------------
const BOOL = @import("../foundation.zig").BOOL;
const HANDLE = @import("../foundation.zig").HANDLE;
const JOB_OBJECT_IO_RATE_CONTROL_FLAGS = @import("../system/system_services.zig").JOB_OBJECT_IO_RATE_CONTROL_FLAGS;
const JOBOBJECTINFOCLASS = @import("../system/system_services.zig").JOBOBJECTINFOCLASS;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const SECURITY_ATTRIBUTES = @import("../security.zig").SECURITY_ATTRIBUTES;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
deps/zigwin32/win32/system/job_objects.zig
|
const std = @import("std");
const prot = @import("protocols.zig");
const Context = @import("client.zig").Context;
const Object = @import("client.zig").Object;
const fw_control_impl = @import("implementations/fw_control.zig");
const wl_compositor_impl = @import("implementations/wl_compositor.zig");
const wl_data_device_manager_impl = @import("implementations/wl_data_device_manager.zig");
const wl_display_impl = @import("implementations/wl_display.zig");
const wl_pointer_impl = @import("implementations/wl_pointer.zig");
const wl_registry_impl = @import("implementations/wl_registry.zig");
const wl_region_impl = @import("implementations/wl_region.zig");
const wl_seat_impl = @import("implementations/wl_seat.zig");
const wl_shm_pool_impl = @import("implementations/wl_shm_pool.zig");
const wl_buffer_impl = @import("implementations/wl_buffer.zig");
const wl_subcompositor_impl = @import("implementations/wl_subcompositor.zig");
const wl_subsurface_impl = @import("implementations/wl_subsurface.zig");
const wl_surface_impl = @import("implementations/wl_surface.zig");
const xdg_base_impl = @import("implementations/xdg_base.zig");
const xdg_popup_impl = @import("implementations/xdg_popup.zig");
const xdg_positioner_impl = @import("implementations/xdg_positioner.zig");
const xdg_surface_impl = @import("implementations/xdg_surface.zig");
const xdg_toplevel_impl = @import("implementations/xdg_toplevel.zig");
const zwp_linux_buffer_params_impl = @import("implementations/zwp_linux_buffer_params.zig");
const zwp_linux_dmabuf_impl = @import("implementations/zwp_linux_dmabuf.zig");
pub fn init() void {
fw_control_impl.init();
wl_compositor_impl.init();
wl_data_device_manager_impl.init();
wl_display_impl.init();
wl_pointer_impl.init();
wl_region_impl.init();
wl_registry_impl.init();
wl_seat_impl.init();
wl_shm_pool_impl.init();
wl_buffer_impl.init();
wl_subcompositor_impl.init();
wl_subsurface_impl.init();
wl_surface_impl.init();
xdg_base_impl.init();
xdg_popup_impl.init();
xdg_positioner_impl.init();
xdg_surface_impl.init();
xdg_toplevel_impl.init();
zwp_linux_buffer_params_impl.init();
zwp_linux_dmabuf_impl.init();
}
|
src/implementations.zig
|
const std = @import("std");
// TODO: maybe imvec4 is not worth it creating a dependency here
const upaya = @import("upaya");
usingnamespace upaya.imgui;
/// We aim at the following Markdown dialect:
///
/// Normal text.
/// Some **bold** text and some _italic_ text.
/// The combination is **_bold italic_** text or _**bold italic**_.
/// - a bulleted item
/// Some ~~underlined~~ text.
///
/// Colors <#rrggbbaa>this is colored</>
///
/// ~~**_underlined bold italic text_**~~.
///
pub const StyleFlags = struct {
pub const none = 0;
pub const bold = 1;
pub const italic = 2;
pub const underline = 4;
pub const line_bulleted = 8;
pub const colored = 16;
pub const zig = 32;
};
pub const MdTextSpan = struct {
startpos: usize = 0,
endpos: usize = 0,
styleflags: u8 = 0,
color_override: ?ImVec4 = null,
text: ?[]const u8 = null,
};
pub const MdParsingError = error{color};
fn parseColorLiteral(colorstr: []const u8) !ImVec4 {
var ret = ImVec4{};
if (colorstr[0] != '#') {
return MdParsingError.color;
}
var temp: ImVec4 = undefined;
var coloru32 = std.fmt.parseInt(c_uint, colorstr[1..9], 16) catch |err| {
return MdParsingError.color;
};
igColorConvertU32ToFloat4(&temp, coloru32);
ret.x = temp.w;
ret.y = temp.z;
ret.z = temp.y;
ret.w = temp.x;
return ret;
}
pub const MdLineParser = struct {
allocator: *std.mem.Allocator = undefined,
currentSpan: MdTextSpan = .{},
result_spans: ?std.ArrayList(MdTextSpan) = null,
pub fn init(self: *MdLineParser, allocator: *std.mem.Allocator) void {
if (self.result_spans) |spans| {
self.result_spans.?.shrinkRetainingCapacity(0);
} else {
self.result_spans = std.ArrayList(MdTextSpan).init(allocator);
}
self.allocator = allocator;
self.currentSpan = .{};
}
fn makeCstr(self: *MdLineParser, t: []const u8) ![]const u8 {
return try std.fmt.allocPrint(self.allocator, "{s}", .{t});
}
// bold, italic, underline starts must be preceded by one of " _*~"
// bold, italic, underline ends must not be preceded by a space.
pub fn parseLine(self: *MdLineParser, line: []const u8) !void {
var pos: usize = 0;
if (std.mem.startsWith(u8, std.mem.trimLeft(u8, line, " \t"), "-")) {
self.currentSpan.styleflags |= StyleFlags.line_bulleted;
}
while (pos < line.len) {
switch (line[pos]) {
'*' => {
if (self.currentSpan.styleflags & StyleFlags.bold > 0) {
// try to terminate bold
if (peekAhead(line, pos, 1)) |ahead| {
if (ahead == '*') {
// make sure we weren't preceded by a space
if (peekBack(line, pos, 1)) |prev| {
if (prev != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// clear bold
self.currentSpan.styleflags &= 0xff - StyleFlags.bold;
self.currentSpan.startpos = pos + 2;
self.currentSpan.endpos = 0;
pos += 1; // skip the 2nd terminator
}
}
}
}
} else {
// try to start bold:
// must be followed by 2nd *
// must eventually be followed by ** in the future
// those ** must not be preceded by a space
// if started: switch on bold flag
if (peekAhead(line, pos, 1)) |next| {
if (next == '*') {
if (std.mem.indexOf(u8, line[pos + 1 ..], "**")) |term_pos_relative| {
// here, we have to deal with double symbols, hence no >= 1 down there:
if (term_pos_relative > 1) {
// check if terminator is preceded by space
if (peekBack(line, pos + 1 + term_pos_relative, 1)) |nospace| {
if (nospace != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// change style of new span
self.currentSpan.styleflags |= StyleFlags.bold;
self.currentSpan.startpos = pos + 2;
self.currentSpan.endpos = 0;
pos += 1;
}
}
}
}
}
}
}
},
'~' => {
if (self.currentSpan.styleflags & StyleFlags.underline > 0) {
// try to terminate underline
if (peekAhead(line, pos, 1)) |ahead| {
if (ahead == '~') {
// make sure we weren't preceded by a space
if (peekBack(line, pos, 1)) |prev| {
if (prev != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// clear underline
self.currentSpan.styleflags &= 0xff - StyleFlags.underline;
self.currentSpan.startpos = pos + 2;
self.currentSpan.endpos = 0;
pos += 1; // skip the 2nd terminator
}
}
}
}
} else {
// try to start underline:
if (peekAhead(line, pos, 1)) |next| {
if (next == '~') {
if (std.mem.indexOf(u8, line[pos + 1 ..], "~~")) |term_pos_relative| {
// here, we have to deal with double symbols, hence no >= 1 down there:
if (term_pos_relative > 1) {
// check if terminator is preceded by space
if (peekBack(line, pos + 1 + term_pos_relative, 1)) |nospace| {
if (nospace != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// change style of new span
self.currentSpan.styleflags |= StyleFlags.underline;
self.currentSpan.startpos = pos + 2;
self.currentSpan.endpos = 0;
pos += 1;
}
}
}
}
}
}
}
},
'_' => {
if (self.currentSpan.styleflags & StyleFlags.italic > 0) {
// try to terminate italic
// make sure we weren't preceded by a space
if (peekBack(line, pos, 1)) |prev| {
if (prev != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// clear italic
self.currentSpan.styleflags &= 0xff - StyleFlags.italic;
self.currentSpan.startpos = pos + 1;
self.currentSpan.endpos = 0;
}
}
} else {
// try to start italic:
if (std.mem.indexOf(u8, line[pos + 1 ..], "_")) |term_pos_relative| {
// how many chars after the character (pos+1) after the initial _ (pos)
if (term_pos_relative >= 1) {
// check if terminator is preceded by space
if (peekBack(line, pos + 1 + term_pos_relative, 1)) |nospace| {
if (nospace != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// change style of new span
self.currentSpan.styleflags |= StyleFlags.italic;
self.currentSpan.startpos = pos + 1;
self.currentSpan.endpos = 0;
}
}
}
}
}
},
'!' => {
if (self.currentSpan.styleflags & StyleFlags.zig > 0) {
// try to terminate zig
// make sure we weren't preceded by a space
if (peekBack(line, pos, 1)) |prev| {
if (prev != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// clear zig
self.currentSpan.styleflags &= 0xff - StyleFlags.zig;
self.currentSpan.startpos = pos + 1;
self.currentSpan.endpos = 0;
}
}
} else {
// try to start italic:
if (std.mem.indexOf(u8, line[pos + 1 ..], "!")) |term_pos_relative| {
// how many chars after the character (pos+1) after the initial ! (pos)
if (term_pos_relative >= 1) {
// check if terminator is preceded by space
if (peekBack(line, pos + 1 + term_pos_relative, 1)) |nospace| {
if (nospace != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// change style of new span
self.currentSpan.styleflags |= StyleFlags.zig;
self.currentSpan.startpos = pos + 1;
self.currentSpan.endpos = 0;
}
}
}
}
}
},
'<' => {
if (self.currentSpan.styleflags & StyleFlags.colored > 0) {
// try to terminate color
if (std.mem.startsWith(u8, line[pos..], "</>")) {
// make sure we weren't preceded by a space
if (peekBack(line, pos, 1)) |prev| {
if (prev != ' ') {
// emit current span
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// clear color
self.currentSpan.styleflags &= 0xff - StyleFlags.colored;
self.currentSpan.startpos = pos + 3;
self.currentSpan.endpos = 0;
self.currentSpan.color_override = null;
pos += 2;
}
}
}
} else {
// try to start color:
if (peekAhead(line, pos, 1)) |next| {
if (next == '#') {
const color_opt: ?ImVec4 = parseColorLiteral(line[pos + 1 ..]) catch null;
if (color_opt) |color| {
if (std.mem.indexOf(u8, line[pos + 1 ..], "</>")) |term_pos_relative| {
// check if terminator is preceded by space
if (peekBack(line, pos + 1 + term_pos_relative, 1)) |nospace| {
if (nospace != ' ') {
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
// change style of new span
self.currentSpan.styleflags |= StyleFlags.colored;
self.currentSpan.color_override = color;
self.currentSpan.startpos = pos + 11;
self.currentSpan.endpos = 0;
pos += 10;
}
}
}
} else {
std.log.warn("no color `{s}`", .{line[pos + 1 ..]});
}
}
}
}
},
else => {},
}
pos += 1;
}
self.currentSpan.endpos = pos;
try self.emitCurrentSpan(line);
return;
}
fn emitCurrentSpan(self: *MdLineParser, line: []const u8) !void {
if (self.currentSpan.endpos == 0 or self.currentSpan.startpos >= line.len or self.currentSpan.endpos - self.currentSpan.startpos < 1) {
return;
}
const span = line[self.currentSpan.startpos..self.currentSpan.endpos];
self.currentSpan.text = try self.makeCstr(span);
if (self.result_spans) |spans| {
try self.result_spans.?.append(self.currentSpan);
} else {
self.result_spans = std.ArrayList(MdTextSpan).init(self.allocator);
try self.result_spans.?.append(self.currentSpan);
}
}
pub fn logSpans(self: *MdLineParser) void {
if (self.result_spans.?.items.len == 0) {
return;
}
for (self.result_spans.?.items) |span| {
var bold: []const u8 = "(not bold)";
if (span.styleflags & StyleFlags.bold > 0) {
bold = "bold";
}
var italic: []const u8 = "(not italic)";
if (span.styleflags & StyleFlags.italic > 0) {
italic = "italic";
}
var underline: []const u8 = "(not underlined)";
if (span.styleflags & StyleFlags.underline > 0) {
underline = "underlined";
}
var line_bulleted: []const u8 = "(not bulleted)";
if (span.styleflags & StyleFlags.line_bulleted > 0) {
line_bulleted = "bulleted";
}
var zig: []const u8 = "(not zig)";
if (span.styleflags & StyleFlags.zig > 0) {
zig = "zig";
}
var colored: []const u8 = "";
if (span.styleflags & StyleFlags.colored > 0) {
colored = std.fmt.allocPrint(self.allocator, "color: {}", .{span.color_override}) catch "color";
}
std.log.debug("[{}:{}] `{s}` : {s} {s} {s} {s} {s} {s}", .{ span.startpos, span.endpos, span.text, bold, italic, underline, zig, line_bulleted, colored });
}
}
};
fn peekAhead(line: []const u8, pos: usize, howmany: usize) ?u8 {
if (pos + howmany >= line.len) {
return null;
}
return line[pos + howmany];
}
fn peekBack(line: []const u8, pos: usize, howmany: usize) ?u8 {
if (howmany > pos) {
return null;
}
return line[pos - howmany];
}
|
src/markdownlineparser.zig
|
const std = @import("std");
pub const pkg = std.build.Pkg{
.name = "lyon",
.source = .{ .path = srcPath() ++ "/lyon.zig" },
};
pub const dummy_pkg = std.build.Pkg{
.name = "lyon",
.source = .{ .path = srcPath() ++ "/lyon_dummy.zig" },
};
pub fn addPackage(step: *std.build.LibExeObjStep, link_lyon: bool) void {
step.addIncludeDir(srcPath());
if (link_lyon) {
step.addPackage(pkg);
} else {
step.addPackage(dummy_pkg);
}
}
pub const BuildStep = struct {
const Self = @This();
step: std.build.Step,
builder: *std.build.Builder,
target: std.zig.CrossTarget,
pub fn create(builder: *std.build.Builder, target: std.zig.CrossTarget) *Self {
const new = builder.allocator.create(Self) catch unreachable;
new.* = .{
.step = std.build.Step.init(.custom, builder.fmt("lyon", .{}), builder.allocator, make),
.builder = builder,
.target = target,
};
return new;
}
fn make(step: *std.build.Step) anyerror!void {
const self = @fieldParentPtr(Self, "step", step);
const toml_path = srcPath() ++ "/Cargo.toml";
if (self.target.getOsTag() == .linux and self.target.getCpuArch() == .x86_64) {
_ = try self.builder.exec(&.{ "cargo", "build", "--release", "--manifest-path", toml_path });
const out_file = srcPath() ++ "/target/release/libclyon.a";
const to_path = srcPath() ++ "/../extras/prebuilt/linux64/libclyon.a";
_ = try self.builder.exec(&.{ "cp", out_file, to_path });
_ = try self.builder.exec(&.{ "strip", "--strip-debug", to_path });
} else if (self.target.getOsTag() == .windows and self.target.getCpuArch() == .x86_64 and self.target.getAbi() == .gnu) {
var env_map = try self.builder.allocator.create(std.process.EnvMap);
env_map.* = try std.process.getEnvMap(self.builder.allocator);
// Attempted to use zig cc like: https://github.com/ziglang/zig/issues/10336
// But ran into issues linking with -lgcc_eh
// try env_map.put("RUSTFLAGS", "-C linker=/Users/fubar/dev/cosmic/zig-cc");
try env_map.put("RUSTFLAGS", "-C linker=/usr/local/Cellar/mingw-w64/9.0.0_2/bin/x86_64-w64-mingw32-gcc");
try self.builder.spawnChildEnvMap(null, env_map, &.{
"cargo", "build", "--target=x86_64-pc-windows-gnu", "--release", "--manifest-path", toml_path,
});
const out_file = srcPath() ++ "/target/x86_64-pc-windows-gnu/release/libclyon.a";
const to_path = srcPath() ++ "/../extras/prebuilt/win64/clyon.lib";
_ = try self.builder.exec(&.{ "cp", out_file, to_path });
} else if (self.target.getOsTag() == .macos and self.target.getCpuArch() == .x86_64) {
_ = try self.builder.exec(&.{ "cargo", "build", "--target=x86_64-apple-darwin", "--release", "--manifest-path", toml_path });
const out_file = srcPath() ++ "/target/x86_64-apple-darwin/release/libclyon.a";
const to_path = srcPath() ++ "/../extras/prebuilt/mac64/libclyon.a";
_ = try self.builder.exec(&.{ "cp", out_file, to_path });
// This actually corrupts the lib and zig will fail to parse it after linking.
// _ = try self.builder.exec(&[_][]const u8{ "strip", "-S", to_path });
} else if (self.target.getOsTag() == .macos and self.target.getCpuArch() == .aarch64) {
_ = try self.builder.exec(&.{ "cargo", "build", "--target=aarch64-apple-darwin", "--release", "--manifest-path", toml_path });
const out_file = srcPath() ++ "/target/aarch64-apple-darwin/release/libclyon.a";
const to_path = srcPath() ++ "/../extras/prebuilt/mac-arm64/libclyon.a";
_ = try self.builder.exec(&.{ "cp", out_file, to_path });
}
}
};
/// Static link prebuilt clyon.
pub fn link(step: *std.build.LibExeObjStep) void {
const target = step.target;
if (target.getOsTag() == .linux and target.getCpuArch() == .x86_64) {
step.addAssemblyFile(srcPath() ++ "/../extras/prebuilt/linux64/libclyon.a");
// Currently clyon needs unwind.
step.linkSystemLibrary("unwind");
} else if (target.getOsTag() == .macos and target.getCpuArch() == .x86_64) {
step.addAssemblyFile(srcPath() ++ "/../extras/prebuilt/mac64/libclyon.a");
} else if (target.getOsTag() == .macos and target.getCpuArch() == .aarch64) {
step.addAssemblyFile(srcPath() ++ "/../extras/prebuilt/mac-arm64/libclyon.a");
} else if (target.getOsTag() == .windows and target.getCpuArch() == .x86_64) {
step.addAssemblyFile(srcPath() ++ "/../extras/prebuilt/win64/clyon.lib");
step.linkSystemLibrary("bcrypt");
step.linkSystemLibrary("userenv");
} else {
step.addLibPath(srcPath() ++ "target/release");
step.linkSystemLibrary("clyon");
}
}
fn srcPath() []const u8 {
return std.fs.path.dirname(@src().file) orelse unreachable;
}
|
lib/clyon/lib.zig
|
const std = @import("std.zig");
const builtin = @import("builtin");
const debug = std.debug;
const mem = std.mem;
const math = std.math;
const testing = std.testing;
pub const trait = @import("meta/trait.zig");
const TypeId = builtin.TypeId;
const TypeInfo = builtin.TypeInfo;
pub fn tagName(v: var) []const u8 {
const T = @TypeOf(v);
switch (@typeInfo(T)) {
TypeId.ErrorSet => return @errorName(v),
else => return @tagName(v),
}
}
test "std.meta.tagName" {
const E1 = enum {
A,
B,
};
const E2 = enum(u8) {
C = 33,
D,
};
const U1 = union(enum) {
G: u8,
H: u16,
};
const U2 = union(E2) {
C: u8,
D: u16,
};
var u1g = U1{ .G = 0 };
var u1h = U1{ .H = 0 };
var u2a = U2{ .C = 0 };
var u2b = U2{ .D = 0 };
testing.expect(mem.eql(u8, tagName(E1.A), "A"));
testing.expect(mem.eql(u8, tagName(E1.B), "B"));
testing.expect(mem.eql(u8, tagName(E2.C), "C"));
testing.expect(mem.eql(u8, tagName(E2.D), "D"));
testing.expect(mem.eql(u8, tagName(error.E), "E"));
testing.expect(mem.eql(u8, tagName(error.F), "F"));
testing.expect(mem.eql(u8, tagName(u1g), "G"));
testing.expect(mem.eql(u8, tagName(u1h), "H"));
testing.expect(mem.eql(u8, tagName(u2a), "C"));
testing.expect(mem.eql(u8, tagName(u2b), "D"));
}
pub fn stringToEnum(comptime T: type, str: []const u8) ?T {
inline for (@typeInfo(T).Enum.fields) |enumField| {
if (std.mem.eql(u8, str, enumField.name)) {
return @field(T, enumField.name);
}
}
return null;
}
test "std.meta.stringToEnum" {
const E1 = enum {
A,
B,
};
testing.expect(E1.A == stringToEnum(E1, "A").?);
testing.expect(E1.B == stringToEnum(E1, "B").?);
testing.expect(null == stringToEnum(E1, "C"));
}
pub fn bitCount(comptime T: type) comptime_int {
return switch (@typeInfo(T)) {
TypeId.Bool => 1,
TypeId.Int => |info| info.bits,
TypeId.Float => |info| info.bits,
else => @compileError("Expected bool, int or float type, found '" ++ @typeName(T) ++ "'"),
};
}
test "std.meta.bitCount" {
testing.expect(bitCount(u8) == 8);
testing.expect(bitCount(f32) == 32);
}
pub fn alignment(comptime T: type) comptime_int {
//@alignOf works on non-pointer types
const P = if (comptime trait.is(TypeId.Pointer)(T)) T else *T;
return @typeInfo(P).Pointer.alignment;
}
test "std.meta.alignment" {
testing.expect(alignment(u8) == 1);
testing.expect(alignment(*align(1) u8) == 1);
testing.expect(alignment(*align(2) u8) == 2);
testing.expect(alignment([]align(1) u8) == 1);
testing.expect(alignment([]align(2) u8) == 2);
}
pub fn Child(comptime T: type) type {
return switch (@typeInfo(T)) {
TypeId.Array => |info| info.child,
TypeId.Pointer => |info| info.child,
TypeId.Optional => |info| info.child,
else => @compileError("Expected pointer, optional, or array type, " ++ "found '" ++ @typeName(T) ++ "'"),
};
}
test "std.meta.Child" {
testing.expect(Child([1]u8) == u8);
testing.expect(Child(*u8) == u8);
testing.expect(Child([]u8) == u8);
testing.expect(Child(?u8) == u8);
}
pub fn containerLayout(comptime T: type) TypeInfo.ContainerLayout {
return switch (@typeInfo(T)) {
TypeId.Struct => |info| info.layout,
TypeId.Enum => |info| info.layout,
TypeId.Union => |info| info.layout,
else => @compileError("Expected struct, enum or union type, found '" ++ @typeName(T) ++ "'"),
};
}
test "std.meta.containerLayout" {
const E1 = enum {
A,
};
const E2 = packed enum {
A,
};
const E3 = extern enum {
A,
};
const S1 = struct {};
const S2 = packed struct {};
const S3 = extern struct {};
const U1 = union {
a: u8,
};
const U2 = packed union {
a: u8,
};
const U3 = extern union {
a: u8,
};
testing.expect(containerLayout(E1) == TypeInfo.ContainerLayout.Auto);
testing.expect(containerLayout(E2) == TypeInfo.ContainerLayout.Packed);
testing.expect(containerLayout(E3) == TypeInfo.ContainerLayout.Extern);
testing.expect(containerLayout(S1) == TypeInfo.ContainerLayout.Auto);
testing.expect(containerLayout(S2) == TypeInfo.ContainerLayout.Packed);
testing.expect(containerLayout(S3) == TypeInfo.ContainerLayout.Extern);
testing.expect(containerLayout(U1) == TypeInfo.ContainerLayout.Auto);
testing.expect(containerLayout(U2) == TypeInfo.ContainerLayout.Packed);
testing.expect(containerLayout(U3) == TypeInfo.ContainerLayout.Extern);
}
pub fn declarations(comptime T: type) []TypeInfo.Declaration {
return switch (@typeInfo(T)) {
TypeId.Struct => |info| info.decls,
TypeId.Enum => |info| info.decls,
TypeId.Union => |info| info.decls,
else => @compileError("Expected struct, enum or union type, found '" ++ @typeName(T) ++ "'"),
};
}
test "std.meta.declarations" {
const E1 = enum {
A,
fn a() void {}
};
const S1 = struct {
fn a() void {}
};
const U1 = union {
a: u8,
fn a() void {}
};
const decls = comptime [_][]TypeInfo.Declaration{
declarations(E1),
declarations(S1),
declarations(U1),
};
inline for (decls) |decl| {
testing.expect(decl.len == 1);
testing.expect(comptime mem.eql(u8, decl[0].name, "a"));
}
}
pub fn declarationInfo(comptime T: type, comptime decl_name: []const u8) TypeInfo.Declaration {
inline for (comptime declarations(T)) |decl| {
if (comptime mem.eql(u8, decl.name, decl_name))
return decl;
}
@compileError("'" ++ @typeName(T) ++ "' has no declaration '" ++ decl_name ++ "'");
}
test "std.meta.declarationInfo" {
const E1 = enum {
A,
fn a() void {}
};
const S1 = struct {
fn a() void {}
};
const U1 = union {
a: u8,
fn a() void {}
};
const infos = comptime [_]TypeInfo.Declaration{
declarationInfo(E1, "a"),
declarationInfo(S1, "a"),
declarationInfo(U1, "a"),
};
inline for (infos) |info| {
testing.expect(comptime mem.eql(u8, info.name, "a"));
testing.expect(!info.is_pub);
}
}
pub fn fields(comptime T: type) switch (@typeInfo(T)) {
TypeId.Struct => []TypeInfo.StructField,
TypeId.Union => []TypeInfo.UnionField,
TypeId.ErrorSet => []TypeInfo.Error,
TypeId.Enum => []TypeInfo.EnumField,
else => @compileError("Expected struct, union, error set or enum type, found '" ++ @typeName(T) ++ "'"),
} {
return switch (@typeInfo(T)) {
TypeId.Struct => |info| info.fields,
TypeId.Union => |info| info.fields,
TypeId.Enum => |info| info.fields,
TypeId.ErrorSet => |errors| errors.?, // must be non global error set
else => @compileError("Expected struct, union, error set or enum type, found '" ++ @typeName(T) ++ "'"),
};
}
test "std.meta.fields" {
const E1 = enum {
A,
};
const E2 = error{A};
const S1 = struct {
a: u8,
};
const U1 = union {
a: u8,
};
const e1f = comptime fields(E1);
const e2f = comptime fields(E2);
const sf = comptime fields(S1);
const uf = comptime fields(U1);
testing.expect(e1f.len == 1);
testing.expect(e2f.len == 1);
testing.expect(sf.len == 1);
testing.expect(uf.len == 1);
testing.expect(mem.eql(u8, e1f[0].name, "A"));
testing.expect(mem.eql(u8, e2f[0].name, "A"));
testing.expect(mem.eql(u8, sf[0].name, "a"));
testing.expect(mem.eql(u8, uf[0].name, "a"));
testing.expect(comptime sf[0].field_type == u8);
testing.expect(comptime uf[0].field_type == u8);
}
pub fn fieldInfo(comptime T: type, comptime field_name: []const u8) switch (@typeInfo(T)) {
TypeId.Struct => TypeInfo.StructField,
TypeId.Union => TypeInfo.UnionField,
TypeId.ErrorSet => TypeInfo.Error,
TypeId.Enum => TypeInfo.EnumField,
else => @compileError("Expected struct, union, error set or enum type, found '" ++ @typeName(T) ++ "'"),
} {
inline for (comptime fields(T)) |field| {
if (comptime mem.eql(u8, field.name, field_name))
return field;
}
@compileError("'" ++ @typeName(T) ++ "' has no field '" ++ field_name ++ "'");
}
test "std.meta.fieldInfo" {
const E1 = enum {
A,
};
const E2 = error{A};
const S1 = struct {
a: u8,
};
const U1 = union {
a: u8,
};
const e1f = comptime fieldInfo(E1, "A");
const e2f = comptime fieldInfo(E2, "A");
const sf = comptime fieldInfo(S1, "a");
const uf = comptime fieldInfo(U1, "a");
testing.expect(mem.eql(u8, e1f.name, "A"));
testing.expect(mem.eql(u8, e2f.name, "A"));
testing.expect(mem.eql(u8, sf.name, "a"));
testing.expect(mem.eql(u8, uf.name, "a"));
testing.expect(comptime sf.field_type == u8);
testing.expect(comptime uf.field_type == u8);
}
pub fn TagType(comptime T: type) type {
return switch (@typeInfo(T)) {
TypeId.Enum => |info| info.tag_type,
TypeId.Union => |info| if (info.tag_type) |Tag| Tag else null,
else => @compileError("expected enum or union type, found '" ++ @typeName(T) ++ "'"),
};
}
test "std.meta.TagType" {
const E = enum(u8) {
C = 33,
D,
};
const U = union(E) {
C: u8,
D: u16,
};
testing.expect(TagType(E) == u8);
testing.expect(TagType(U) == E);
}
///Returns the active tag of a tagged union
pub fn activeTag(u: var) @TagType(@TypeOf(u)) {
const T = @TypeOf(u);
return @as(@TagType(T), u);
}
test "std.meta.activeTag" {
const UE = enum {
Int,
Float,
};
const U = union(UE) {
Int: u32,
Float: f32,
};
var u = U{ .Int = 32 };
testing.expect(activeTag(u) == UE.Int);
u = U{ .Float = 112.9876 };
testing.expect(activeTag(u) == UE.Float);
}
///Given a tagged union type, and an enum, return the type of the union
/// field corresponding to the enum tag.
pub fn TagPayloadType(comptime U: type, tag: var) type {
const Tag = @TypeOf(tag);
testing.expect(trait.is(builtin.TypeId.Union)(U));
testing.expect(trait.is(builtin.TypeId.Enum)(Tag));
const info = @typeInfo(U).Union;
inline for (info.fields) |field_info| {
if (field_info.enum_field.?.value == @enumToInt(tag)) return field_info.field_type;
}
unreachable;
}
test "std.meta.TagPayloadType" {
const Event = union(enum) {
Moved: struct {
from: i32,
to: i32,
},
};
const MovedEvent = TagPayloadType(Event, Event.Moved);
var e: Event = undefined;
testing.expect(MovedEvent == @TypeOf(e.Moved));
}
///Compares two of any type for equality. Containers are compared on a field-by-field basis,
/// where possible. Pointers are not followed.
pub fn eql(a: var, b: @TypeOf(a)) bool {
const T = @TypeOf(a);
switch (@typeId(T)) {
builtin.TypeId.Struct => {
const info = @typeInfo(T).Struct;
inline for (info.fields) |field_info| {
if (!eql(@field(a, field_info.name), @field(b, field_info.name))) return false;
}
return true;
},
builtin.TypeId.ErrorUnion => {
if (a) |a_p| {
if (b) |b_p| return eql(a_p, b_p) else |_| return false;
} else |a_e| {
if (b) |_| return false else |b_e| return a_e == b_e;
}
},
builtin.TypeId.Union => {
const info = @typeInfo(T).Union;
if (info.tag_type) |_| {
const tag_a = activeTag(a);
const tag_b = activeTag(b);
if (tag_a != tag_b) return false;
inline for (info.fields) |field_info| {
const enum_field = field_info.enum_field.?;
if (enum_field.value == @enumToInt(tag_a)) {
return eql(@field(a, enum_field.name), @field(b, enum_field.name));
}
}
return false;
}
@compileError("cannot compare untagged union type " ++ @typeName(T));
},
builtin.TypeId.Array => {
if (a.len != b.len) return false;
for (a) |e, i|
if (!eql(e, b[i])) return false;
return true;
},
builtin.TypeId.Pointer => {
const info = @typeInfo(T).Pointer;
switch (info.size) {
builtin.TypeInfo.Pointer.Size.One,
builtin.TypeInfo.Pointer.Size.Many,
builtin.TypeInfo.Pointer.Size.C,
=> return a == b,
builtin.TypeInfo.Pointer.Size.Slice => return a.ptr == b.ptr and a.len == b.len,
}
},
builtin.TypeId.Optional => {
if (a == null and b == null) return true;
if (a == null or b == null) return false;
return eql(a.?, b.?);
},
else => return a == b,
}
}
test "std.meta.eql" {
const S = struct {
a: u32,
b: f64,
c: [5]u8,
};
const U = union(enum) {
s: S,
f: ?f32,
};
const s_1 = S{
.a = 134,
.b = 123.3,
.c = "12345".*,
};
const s_2 = S{
.a = 1,
.b = 123.3,
.c = "54321".*,
};
const s_3 = S{
.a = 134,
.b = 123.3,
.c = "12345".*,
};
const u_1 = U{ .f = 24 };
const u_2 = U{ .s = s_1 };
const u_3 = U{ .f = 24 };
testing.expect(eql(s_1, s_3));
testing.expect(eql(&s_1, &s_1));
testing.expect(!eql(&s_1, &s_3));
testing.expect(eql(u_1, u_3));
testing.expect(!eql(u_1, u_2));
var a1 = "abcdef".*;
var a2 = "abcdef".*;
var a3 = "ghijkl".*;
testing.expect(eql(a1, a2));
testing.expect(!eql(a1, a3));
testing.expect(!eql(a1[0..], a2[0..]));
const EU = struct {
fn tst(err: bool) !u8 {
if (err) return error.Error;
return @as(u8, 5);
}
};
testing.expect(eql(EU.tst(true), EU.tst(true)));
testing.expect(eql(EU.tst(false), EU.tst(false)));
testing.expect(!eql(EU.tst(false), EU.tst(true)));
}
test "intToEnum with error return" {
const E1 = enum {
A,
};
const E2 = enum {
A,
B,
};
var zero: u8 = 0;
var one: u16 = 1;
testing.expect(intToEnum(E1, zero) catch unreachable == E1.A);
testing.expect(intToEnum(E2, one) catch unreachable == E2.B);
testing.expectError(error.InvalidEnumTag, intToEnum(E1, one));
}
pub const IntToEnumError = error{InvalidEnumTag};
pub fn intToEnum(comptime Tag: type, tag_int: var) IntToEnumError!Tag {
comptime var i = 0;
inline while (i != @memberCount(Tag)) : (i += 1) {
const this_tag_value = @field(Tag, @memberName(Tag, i));
if (tag_int == @enumToInt(this_tag_value)) {
return this_tag_value;
}
}
return error.InvalidEnumTag;
}
/// Given a type and a name, return the field index according to source order.
/// Returns `null` if the field is not found.
pub fn fieldIndex(comptime T: type, comptime name: []const u8) ?comptime_int {
inline for (fields(T)) |field, i| {
if (mem.eql(u8, field.name, name))
return i;
}
return null;
}
/// Given a type, reference all the declarations inside, so that the semantic analyzer sees them.
pub fn refAllDecls(comptime T: type) void {
if (!builtin.is_test) return;
_ = declarations(T);
}
|
lib/std/meta.zig
|
const std = @import("../std.zig");
const fmt = std.fmt;
const math = std.math;
const mem = std.mem;
const testing = std.testing;
const Vector = std.meta.Vector;
const ChunkIterator = struct {
slice: []u8,
chunk_len: usize,
fn init(slice: []u8, chunk_len: usize) ChunkIterator {
return ChunkIterator{
.slice = slice,
.chunk_len = chunk_len,
};
}
fn next(self: *ChunkIterator) ?[]u8 {
const next_chunk = self.slice[0..math.min(self.chunk_len, self.slice.len)];
self.slice = self.slice[next_chunk.len..];
return if (next_chunk.len > 0) next_chunk else null;
}
};
const OUT_LEN: usize = 32;
const KEY_LEN: usize = 32;
const BLOCK_LEN: usize = 64;
const CHUNK_LEN: usize = 1024;
const IV = [8]u32{
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
};
const MSG_SCHEDULE = [7][16]u8{
[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
[_]u8{ 2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8 },
[_]u8{ 3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1 },
[_]u8{ 10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6 },
[_]u8{ 12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4 },
[_]u8{ 9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7 },
[_]u8{ 11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13 },
};
// These are the internal flags that we use to domain separate root/non-root,
// chunk/parent, and chunk beginning/middle/end. These get set at the high end
// of the block flags word in the compression function, so their values start
// high and go down.
const CHUNK_START: u8 = 1 << 0;
const CHUNK_END: u8 = 1 << 1;
const PARENT: u8 = 1 << 2;
const ROOT: u8 = 1 << 3;
const KEYED_HASH: u8 = 1 << 4;
const DERIVE_KEY_CONTEXT: u8 = 1 << 5;
const DERIVE_KEY_MATERIAL: u8 = 1 << 6;
const CompressVectorized = struct {
const Lane = Vector(4, u32);
const Rows = [4]Lane;
inline fn rot(x: Lane, comptime n: u5) Lane {
return (x >> @splat(4, @as(u5, n))) | (x << @splat(4, @as(u5, 1 +% ~n)));
}
inline fn g(comptime even: bool, rows: *Rows, m: Lane) void {
rows[0] +%= rows[1] +% m;
rows[3] ^= rows[0];
rows[3] = rot(rows[3], if (even) 8 else 16);
rows[2] +%= rows[3];
rows[1] ^= rows[2];
rows[1] = rot(rows[1], if (even) 7 else 12);
}
inline fn diagonalize(rows: *Rows) void {
rows[0] = @shuffle(u32, rows[0], undefined, [_]i32{ 3, 0, 1, 2 });
rows[3] = @shuffle(u32, rows[3], undefined, [_]i32{ 2, 3, 0, 1 });
rows[2] = @shuffle(u32, rows[2], undefined, [_]i32{ 1, 2, 3, 0 });
}
inline fn undiagonalize(rows: *Rows) void {
rows[0] = @shuffle(u32, rows[0], undefined, [_]i32{ 1, 2, 3, 0 });
rows[3] = @shuffle(u32, rows[3], undefined, [_]i32{ 2, 3, 0, 1 });
rows[2] = @shuffle(u32, rows[2], undefined, [_]i32{ 3, 0, 1, 2 });
}
fn compress(
chaining_value: [8]u32,
block_words: [16]u32,
block_len: u32,
counter: u64,
flags: u8,
) [16]u32 {
const md = Lane{ @truncate(u32, counter), @truncate(u32, counter >> 32), block_len, @as(u32, flags) };
var rows = Rows{ chaining_value[0..4].*, chaining_value[4..8].*, IV[0..4].*, md };
var m = Rows{ block_words[0..4].*, block_words[4..8].*, block_words[8..12].*, block_words[12..16].* };
var t0 = @shuffle(u32, m[0], m[1], [_]i32{ 0, 2, (-1 - 0), (-1 - 2) });
g(false, &rows, t0);
var t1 = @shuffle(u32, m[0], m[1], [_]i32{ 1, 3, (-1 - 1), (-1 - 3) });
g(true, &rows, t1);
diagonalize(&rows);
var t2 = @shuffle(u32, m[2], m[3], [_]i32{ 0, 2, (-1 - 0), (-1 - 2) });
t2 = @shuffle(u32, t2, undefined, [_]i32{ 3, 0, 1, 2 });
g(false, &rows, t2);
var t3 = @shuffle(u32, m[2], m[3], [_]i32{ 1, 3, (-1 - 1), (-1 - 3) });
t3 = @shuffle(u32, t3, undefined, [_]i32{ 3, 0, 1, 2 });
g(true, &rows, t3);
undiagonalize(&rows);
m = Rows{ t0, t1, t2, t3 };
var i: usize = 0;
while (i < 6) : (i += 1) {
t0 = @shuffle(u32, m[0], m[1], [_]i32{ 2, 1, (-1 - 1), (-1 - 3) });
t0 = @shuffle(u32, t0, undefined, [_]i32{ 1, 2, 3, 0 });
g(false, &rows, t0);
t1 = @shuffle(u32, m[2], m[3], [_]i32{ 2, 2, (-1 - 3), (-1 - 3) });
var tt = @shuffle(u32, m[0], undefined, [_]i32{ 3, 3, 0, 0 });
t1 = @shuffle(u32, tt, t1, [_]i32{ 0, (-1 - 1), 2, (-1 - 3) });
g(true, &rows, t1);
diagonalize(&rows);
t2 = @shuffle(u32, m[3], m[1], [_]i32{ 0, 1, (-1 - 0), (-1 - 1) });
tt = @shuffle(u32, t2, m[2], [_]i32{ 0, 1, 2, (-1 - 3) });
t2 = @shuffle(u32, tt, undefined, [_]i32{ 0, 2, 3, 1 });
g(false, &rows, t2);
t3 = @shuffle(u32, m[1], m[3], [_]i32{ 2, (-1 - 2), 3, (-1 - 3) });
tt = @shuffle(u32, m[2], t3, [_]i32{ 0, (-1 - 0), 1, (-1 - 1) });
t3 = @shuffle(u32, tt, undefined, [_]i32{ 2, 3, 1, 0 });
g(true, &rows, t3);
undiagonalize(&rows);
m = Rows{ t0, t1, t2, t3 };
}
rows[0] ^= rows[2];
rows[1] ^= rows[3];
rows[2] ^= Vector(4, u32){ chaining_value[0], chaining_value[1], chaining_value[2], chaining_value[3] };
rows[3] ^= Vector(4, u32){ chaining_value[4], chaining_value[5], chaining_value[6], chaining_value[7] };
return @bitCast([16]u32, rows);
}
};
const CompressGeneric = struct {
fn g(state: *[16]u32, comptime a: usize, comptime b: usize, comptime c: usize, comptime d: usize, mx: u32, my: u32) void {
state[a] +%= state[b] +% mx;
state[d] = math.rotr(u32, state[d] ^ state[a], 16);
state[c] +%= state[d];
state[b] = math.rotr(u32, state[b] ^ state[c], 12);
state[a] +%= state[b] +% my;
state[d] = math.rotr(u32, state[d] ^ state[a], 8);
state[c] +%= state[d];
state[b] = math.rotr(u32, state[b] ^ state[c], 7);
}
fn round(state: *[16]u32, msg: [16]u32, schedule: [16]u8) void {
// Mix the columns.
g(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]);
g(state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]);
g(state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]);
g(state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]);
// Mix the diagonals.
g(state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]);
g(state, 1, 6, 11, 12, msg[schedule[10]], msg[schedule[11]]);
g(state, 2, 7, 8, 13, msg[schedule[12]], msg[schedule[13]]);
g(state, 3, 4, 9, 14, msg[schedule[14]], msg[schedule[15]]);
}
fn compress(
chaining_value: [8]u32,
block_words: [16]u32,
block_len: u32,
counter: u64,
flags: u8,
) [16]u32 {
var state = [16]u32{
chaining_value[0],
chaining_value[1],
chaining_value[2],
chaining_value[3],
chaining_value[4],
chaining_value[5],
chaining_value[6],
chaining_value[7],
IV[0],
IV[1],
IV[2],
IV[3],
@truncate(u32, counter),
@truncate(u32, counter >> 32),
block_len,
flags,
};
for (MSG_SCHEDULE) |schedule| {
round(&state, block_words, schedule);
}
for (chaining_value) |_, i| {
state[i] ^= state[i + 8];
state[i + 8] ^= chaining_value[i];
}
return state;
}
};
const compress = if (std.Target.current.cpu.arch == .x86_64) CompressVectorized.compress else CompressGeneric.compress;
fn first8Words(words: [16]u32) [8]u32 {
return @ptrCast(*const [8]u32, &words).*;
}
fn wordsFromLittleEndianBytes(comptime count: usize, bytes: [count * 4]u8) [count]u32 {
var words: [count]u32 = undefined;
for (words) |*word, i| {
word.* = mem.readIntSliceLittle(u32, bytes[4 * i ..]);
}
return words;
}
// Each chunk or parent node can produce either an 8-word chaining value or, by
// setting the ROOT flag, any number of final output bytes. The Output struct
// captures the state just prior to choosing between those two possibilities.
const Output = struct {
input_chaining_value: [8]u32 align(16),
block_words: [16]u32 align(16),
block_len: u32,
counter: u64,
flags: u8,
fn chainingValue(self: *const Output) [8]u32 {
return first8Words(compress(
self.input_chaining_value,
self.block_words,
self.block_len,
self.counter,
self.flags,
));
}
fn rootOutputBytes(self: *const Output, output: []u8) void {
var out_block_it = ChunkIterator.init(output, 2 * OUT_LEN);
var output_block_counter: usize = 0;
while (out_block_it.next()) |out_block| {
var words = compress(
self.input_chaining_value,
self.block_words,
self.block_len,
output_block_counter,
self.flags | ROOT,
);
var out_word_it = ChunkIterator.init(out_block, 4);
var word_counter: usize = 0;
while (out_word_it.next()) |out_word| {
var word_bytes: [4]u8 = undefined;
mem.writeIntLittle(u32, &word_bytes, words[word_counter]);
mem.copy(u8, out_word, word_bytes[0..out_word.len]);
word_counter += 1;
}
output_block_counter += 1;
}
}
};
const ChunkState = struct {
chaining_value: [8]u32 align(16),
chunk_counter: u64,
block: [BLOCK_LEN]u8 align(16) = [_]u8{0} ** BLOCK_LEN,
block_len: u8 = 0,
blocks_compressed: u8 = 0,
flags: u8,
fn init(key: [8]u32, chunk_counter: u64, flags: u8) ChunkState {
return ChunkState{
.chaining_value = key,
.chunk_counter = chunk_counter,
.flags = flags,
};
}
fn len(self: *const ChunkState) usize {
return BLOCK_LEN * @as(usize, self.blocks_compressed) + @as(usize, self.block_len);
}
fn fillBlockBuf(self: *ChunkState, input: []const u8) []const u8 {
const want = BLOCK_LEN - self.block_len;
const take = math.min(want, input.len);
mem.copy(u8, self.block[self.block_len..][0..take], input[0..take]);
self.block_len += @truncate(u8, take);
return input[take..];
}
fn startFlag(self: *const ChunkState) u8 {
return if (self.blocks_compressed == 0) CHUNK_START else 0;
}
fn update(self: *ChunkState, input_slice: []const u8) void {
var input = input_slice;
while (input.len > 0) {
// If the block buffer is full, compress it and clear it. More
// input is coming, so this compression is not CHUNK_END.
if (self.block_len == BLOCK_LEN) {
const block_words = wordsFromLittleEndianBytes(16, self.block);
self.chaining_value = first8Words(compress(
self.chaining_value,
block_words,
BLOCK_LEN,
self.chunk_counter,
self.flags | self.startFlag(),
));
self.blocks_compressed += 1;
self.block = [_]u8{0} ** BLOCK_LEN;
self.block_len = 0;
}
// Copy input bytes into the block buffer.
input = self.fillBlockBuf(input);
}
}
fn output(self: *const ChunkState) Output {
const block_words = wordsFromLittleEndianBytes(16, self.block);
return Output{
.input_chaining_value = self.chaining_value,
.block_words = block_words,
.block_len = self.block_len,
.counter = self.chunk_counter,
.flags = self.flags | self.startFlag() | CHUNK_END,
};
}
};
fn parentOutput(
left_child_cv: [8]u32,
right_child_cv: [8]u32,
key: [8]u32,
flags: u8,
) Output {
var block_words: [16]u32 align(16) = undefined;
mem.copy(u32, block_words[0..8], left_child_cv[0..]);
mem.copy(u32, block_words[8..], right_child_cv[0..]);
return Output{
.input_chaining_value = key,
.block_words = block_words,
.block_len = BLOCK_LEN, // Always BLOCK_LEN (64) for parent nodes.
.counter = 0, // Always 0 for parent nodes.
.flags = PARENT | flags,
};
}
fn parentCv(
left_child_cv: [8]u32,
right_child_cv: [8]u32,
key: [8]u32,
flags: u8,
) [8]u32 {
return parentOutput(left_child_cv, right_child_cv, key, flags).chainingValue();
}
/// An incremental hasher that can accept any number of writes.
pub const Blake3 = struct {
pub const Options = struct { key: ?[digest_length]u8 = null };
pub const KdfOptions = struct {};
chunk_state: ChunkState,
key: [8]u32,
cv_stack: [54][8]u32 = undefined, // Space for 54 subtree chaining values:
cv_stack_len: u8 = 0, // 2^54 * CHUNK_LEN = 2^64
flags: u8,
pub const block_length = BLOCK_LEN;
pub const digest_length = OUT_LEN;
pub const key_length = KEY_LEN;
fn init_internal(key: [8]u32, flags: u8) Blake3 {
return Blake3{
.chunk_state = ChunkState.init(key, 0, flags),
.key = key,
.flags = flags,
};
}
/// Construct a new `Blake3` for the hash function, with an optional key
pub fn init(options: Options) Blake3 {
if (options.key) |key| {
const key_words = wordsFromLittleEndianBytes(8, key);
return Blake3.init_internal(key_words, KEYED_HASH);
} else {
return Blake3.init_internal(IV, 0);
}
}
/// Construct a new `Blake3` for the key derivation function. The context
/// string should be hardcoded, globally unique, and application-specific.
pub fn initKdf(context: []const u8, options: KdfOptions) Blake3 {
var context_hasher = Blake3.init_internal(IV, DERIVE_KEY_CONTEXT);
context_hasher.update(context);
var context_key: [KEY_LEN]u8 = undefined;
context_hasher.final(context_key[0..]);
const context_key_words = wordsFromLittleEndianBytes(8, context_key);
return Blake3.init_internal(context_key_words, DERIVE_KEY_MATERIAL);
}
pub fn hash(in: []const u8, out: []u8, options: Options) void {
var hasher = Blake3.init(options);
hasher.update(in);
hasher.final(out);
}
fn pushCv(self: *Blake3, cv: [8]u32) void {
self.cv_stack[self.cv_stack_len] = cv;
self.cv_stack_len += 1;
}
fn popCv(self: *Blake3) [8]u32 {
self.cv_stack_len -= 1;
return self.cv_stack[self.cv_stack_len];
}
// Section 5.1.2 of the BLAKE3 spec explains this algorithm in more detail.
fn addChunkChainingValue(self: *Blake3, first_cv: [8]u32, total_chunks: u64) void {
// This chunk might complete some subtrees. For each completed subtree,
// its left child will be the current top entry in the CV stack, and
// its right child will be the current value of `new_cv`. Pop each left
// child off the stack, merge it with `new_cv`, and overwrite `new_cv`
// with the result. After all these merges, push the final value of
// `new_cv` onto the stack. The number of completed subtrees is given
// by the number of trailing 0-bits in the new total number of chunks.
var new_cv = first_cv;
var chunk_counter = total_chunks;
while (chunk_counter & 1 == 0) {
new_cv = parentCv(self.popCv(), new_cv, self.key, self.flags);
chunk_counter >>= 1;
}
self.pushCv(new_cv);
}
/// Add input to the hash state. This can be called any number of times.
pub fn update(self: *Blake3, input_slice: []const u8) void {
var input = input_slice;
while (input.len > 0) {
// If the current chunk is complete, finalize it and reset the
// chunk state. More input is coming, so this chunk is not ROOT.
if (self.chunk_state.len() == CHUNK_LEN) {
const chunk_cv = self.chunk_state.output().chainingValue();
const total_chunks = self.chunk_state.chunk_counter + 1;
self.addChunkChainingValue(chunk_cv, total_chunks);
self.chunk_state = ChunkState.init(self.key, total_chunks, self.flags);
}
// Compress input bytes into the current chunk state.
const want = CHUNK_LEN - self.chunk_state.len();
const take = math.min(want, input.len);
self.chunk_state.update(input[0..take]);
input = input[take..];
}
}
/// Finalize the hash and write any number of output bytes.
pub fn final(self: *const Blake3, out_slice: []u8) void {
// Starting with the Output from the current chunk, compute all the
// parent chaining values along the right edge of the tree, until we
// have the root Output.
var output = self.chunk_state.output();
var parent_nodes_remaining: usize = self.cv_stack_len;
while (parent_nodes_remaining > 0) {
parent_nodes_remaining -= 1;
output = parentOutput(
self.cv_stack[parent_nodes_remaining],
output.chainingValue(),
self.key,
self.flags,
);
}
output.rootOutputBytes(out_slice);
}
};
// Use named type declarations to workaround crash with anonymous structs (issue #4373).
const ReferenceTest = struct {
key: *const [KEY_LEN]u8,
context_string: []const u8,
cases: []const ReferenceTestCase,
};
const ReferenceTestCase = struct {
input_len: usize,
hash: *const [262]u8,
keyed_hash: *const [262]u8,
derive_key: *const [262]u8,
};
// Each test is an input length and three outputs, one for each of the `hash`, `keyed_hash`, and
// `derive_key` modes. The input in each case is filled with a 251-byte-long repeating pattern:
// 0, 1, 2, ..., 249, 250, 0, 1, ... The key used with `keyed_hash` is the 32-byte ASCII string
// given in the `key` field below. For `derive_key`, the test input is used as the input key, and
// the context string is 'BLAKE3 2019-12-27 16:29:52 test vectors context'. (As good practice for
// following the security requirements of `derive_key`, test runners should make that context
// string a hardcoded constant, and we do not provided it in machine-readable form.) Outputs are
// encoded as hexadecimal. Each case is an extended output, and implementations should also check
// that the first 32 bytes match their default-length output.
//
// Source: https://github.com/BLAKE3-team/BLAKE3/blob/92d421dea1a89e2f079f4dbd93b0dab41234b279/test_vectors/test_vectors.json
const reference_test = ReferenceTest{
.key = "whats the Elvish word for friend",
.context_string = "BLAKE3 2019-12-27 16:29:52 test vectors context",
.cases = &[_]ReferenceTestCase{
.{
.input_len = 0,
.hash = "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262e00f03e7b69af26b7faaf09fcd333050338ddfe085b8cc869ca98b206c08243a26f5487789e8f660afe6c99ef9e0c52b92e7393024a80459cf91f476f9ffdbda7001c22e159b402631f277ca96f2defdf1078282314e763699a31c5363165421cce14d",
.keyed_hash = "92b2b75604ed3c761f9d6f62392c8a9227ad0ea3f09573e783f1498a4ed60d26b18171a2f22a4b94822c701f107153dba24918c4bae4d2945c20ece13387627d3b73cbf97b797d5e59948c7ef788f54372df45e45e4293c7dc18c1d41144a9758be58960856be1eabbe22c2653190de560ca3b2ac4aa692a9210694254c371e851bc8f",
.derive_key = "<KEY>",
},
.{
.input_len = 1,
.hash = "2d3adedff11b61f14c886e35afa036736dcd87a74d27b5c1510225d0f592e213c3a6cb8bf623e20cdb535f8d1a5ffb86342d9c0b64aca3bce1d31f60adfa137b358ad4d79f97b47c3d5e79f179df87a3b9776ef8325f8329886ba42f07fb138bb502f4081cbcec3195c5871e6c23e2cc97d3c69a613eba131e5f1351f3f1da786545e5",
.keyed_hash = "6d7878dfff2f485635d39013278ae14f1454b8c0a3a2d34bc1ab38228a80c95b6568c0490609413006fbd428eb3fd14e7756d90f73a4725fad147f7bf70fd61c4e0cf7074885e92b0e3f125978b4154986d4fb202a3f331a3fb6cf349a3a70e49990f98fe4289761c8602c4e6ab1138d31d3b62218078b2f3ba9a88e1d08d0dd4cea11",
.derive_key = "b3e2e340a117a499c6cf2398a19ee0d29cca2bb7404c73063382693bf66cb06c5827b91bf889b6b97c5477f535361caefca0b5d8c4746441c57617111933158950670f9aa8a05d791daae10ac683cbef8faf897c84e6114a59d2173c3f417023a35d6983f2c7dfa57e7fc559ad751dbfb9ffab39c2ef8c4aafebc9ae973a64f0c76551",
},
.{
.input_len = 1023,
.hash = "10108970eeda3eb932baac1428c7a2163b0e924c9a9e25b35bba72b28f70bd11a182d27a591b05592b15607500e1e8dd56bc6c7fc063715b7a1d737df5bad3339c56778957d870eb9717b57ea3d9fb68d1b55127bba6a906a4a24bbd5acb2d123a37b28f9e9a81bbaae360d58f85e5fc9d75f7c370a0cc09b6522d9c8d822f2f28f485",
.keyed_hash = "c951ecdf03288d0fcc96ee3413563d8a6d3589547f2c2fb36d9786470f1b9d6e890316d2e6d8b8c25b0a5b2180f94fb1a158ef508c3cde45e2966bd796a696d3e13efd86259d756387d9becf5c8bf1ce2192b87025152907b6d8cc33d17826d8b7b9bc97e38c3c85108ef09f013e01c229c20a83d9e8efac5b37470da28575fd755a10",
.derive_key = "74a16c1c3d44368a86e1ca6df64be6a2f64cce8f09220787450722d85725dea59c413264404661e9e4d955409dfe4ad3aa487871bcd454ed12abfe2c2b1eb7757588cf6cb18d2eccad49e018c0d0fec323bec82bf1644c6325717d13ea712e6840d3e6e730d35553f59eff5377a9c350bcc1556694b924b858f329c44ee64b884ef00d",
},
.{
.input_len = 1024,
.hash = "42214739f095a406f3fc83deb889744ac00df831c10daa55189b5d121c855af71cf8107265ecdaf8505b95d8fcec83a98a6a96ea5109d2c179c47a387ffbb404756f6eeae7883b446b70ebb144527c2075ab8ab204c0086bb22b7c93d465efc57f8d917f0b385c6df265e77003b85102967486ed57db5c5ca170ba441427ed9afa684e",
.keyed_hash = "75c46f6f3d9eb4f55ecaaee480db732e6c2105546f1e675003687c31719c7ba4a78bc838c72852d4f49c864acb7adafe2478e824afe51c8919d06168414c265f298a8094b1ad813a9b8614acabac321f24ce61c5a5346eb519520d38ecc43e89b5000236df0597243e4d2493fd626730e2ba17ac4d8824d09d1a4a8f57b8227778e2de",
.derive_key = "7356cd7720d5b66b6d0697eb3177d9f8d73a4a5c5e968896eb6a6896843027066c23b601d3ddfb391e90d5c8eccdef4ae2a264bce9e612ba15e2bc9d654af1481b2e75dbabe615974f1070bba84d56853265a34330b4766f8e75edd1f4a1650476c10802f22b64bd3919d246ba20a17558bc51c199efdec67e80a227251808d8ce5bad",
},
.{
.input_len = 1025,
.hash = "d00278ae47eb27b34faecf67b4fe263f82d5412916c1ffd97c8cb7fb814b8444f4c4a22b4b399155358a994e52bf255de60035742ec71bd08ac275a1b51cc6bfe332b0ef84b409108cda080e6269ed4b3e2c3f7d722aa4cdc98d16deb554e5627be8f955c98e1d5f9565a9194cad0c4285f93700062d9595adb992ae68ff12800ab67a",
.keyed_hash = "357dc55de0c7e382c900fd6e320acc04146be01db6a8ce7210b7189bd664ea69362396b77fdc0d2634a552970843722066c3c15902ae5097e00ff53f1e116f1cd5352720113a837ab2452cafbde4d54085d9cf5d21ca613071551b25d52e69d6c81123872b6f19cd3bc1333edf0c52b94de23ba772cf82636cff4542540a7738d5b930",
.derive_key = "effaa245f065fbf82ac186839a249707c3bddf6d3fdda22d1b95a3c970379bcb5d31013a167509e9066273ab6e2123bc835b408b067d88f96addb550d96b6852dad38e320b9d940f86db74d398c770f462118b35d2724efa13da97194491d96dd37c3c09cbef665953f2ee85ec83d88b88d11547a6f911c8217cca46defa2751e7f3ad",
},
.{
.input_len = 2048,
.hash = "e776b6028c7cd22a4d0ba182a8bf62205d2ef576467e838ed6f2529b85fba24a9a60bf80001410ec9eea6698cd537939fad4749edd484cb541aced55cd9bf54764d063f23f6f1e32e12958ba5cfeb1bf618ad094266d4fc3c968c2088f677454c288c67ba0dba337b9d91c7e1ba586dc9a5bc2d5e90c14f53a8863ac75655461cea8f9",
.keyed_hash = "879cf1fa2ea0e79126cb1063617a05b6ad9d0b696d0d757cf053439f60a99dd10173b961cd574288194b23ece278c330fbb8585485e74967f31352a8183aa782b2b22f26cdcadb61eed1a5bc144b8198fbb0c13abbf8e3192c145d0a5c21633b0ef86054f42809df823389ee40811a5910dcbd1018af31c3b43aa55201ed4edaac74fe",
.derive_key = "7b2945cb4fef70885cc5d78a87bf6f6207dd901ff239201351ffac04e1088a23e2c11a1ebffcea4d80447867b61badb1383d842d4e79645d48dd82ccba290769caa7af8eaa1bd78a2a5e6e94fbdab78d9c7b74e894879f6a515257ccf6f95056f4e25390f24f6b35ffbb74b766202569b1d797f2d4bd9d17524c720107f985f4ddc583",
},
.{
.input_len = 2049,
.hash = "5f4d72f40d7a5f82b15ca2b2e44b1de3c2ef86c426c95c1af0b687952256303096de31d71d74103403822a2e0bc1eb193e7aecc9643a76b7bbc0c9f9c52e8783aae98764ca468962b5c2ec92f0c74eb5448d519713e09413719431c802f948dd5d90425a4ecdadece9eb178d80f26efccae630734dff63340285adec2aed3b51073ad3",
.keyed_hash = "9f29700902f7c86e514ddc4df1e3049f258b2472b6dd5267f61bf13983b78dd5f9a88abfefdfa1e00b418971f2b39c64ca621e8eb37fceac57fd0c8fc8e117d43b81447be22d5d8186f8f5919ba6bcc6846bd7d50726c06d245672c2ad4f61702c646499ee1173daa061ffe15bf45a631e2946d616a4c345822f1151284712f76b2b0e",
.derive_key = "2ea477c5515cc3dd606512ee72bb3e0e758cfae7232826f35fb98ca1bcbdf27316d8e9e79081a80b046b60f6a263616f33ca464bd78d79fa18200d06c7fc9bffd808cc4755277a7d5e09da0f29ed150f6537ea9bed946227ff184cc66a72a5f8c1e4bd8b04e81cf40fe6dc4427ad5678311a61f4ffc39d195589bdbc670f63ae70f4b6",
},
.{
.input_len = 3072,
.hash = "b98cb0ff3623be03326b373de6b9095218513e64f1ee2edd2525c7ad1e5cffd29a3f6b0b978d6608335c09dc94ccf682f9951cdfc501bfe47b9c9189a6fc7b404d120258506341a6d802857322fbd20d3e5dae05b95c88793fa83db1cb08e7d8008d1599b6209d78336e24839724c191b2a52a80448306e0daa84a3fdb566661a37e11",
.keyed_hash = "044a0e7b172a312dc02a4c9a818c036ffa2776368d7f528268d2e6b5df19177022f302d0529e4174cc507c463671217975e81dab02b8fdeb0d7ccc7568dd22574c783a76be215441b32e91b9a904be8ea81f7a0afd14bad8ee7c8efc305ace5d3dd61b996febe8da4f56ca0919359a7533216e2999fc87ff7d8f176fbecb3d6f34278b",
.derive_key = "050df97f8c2ead654d9bb3ab8c9178edcd902a32f8495949feadcc1e0480c46b3604131bbd6e3ba573b6dd682fa0a63e5b165d39fc43a625d00207607a2bfeb65ff1d29292152e26b298868e3b87be95d6458f6f2ce6118437b632415abe6ad522874bcd79e4030a5e7bad2efa90a7a7c67e93f0a18fb28369d0a9329ab5c24134ccb0",
},
.{
.input_len = 3073,
.hash = "7124b49501012f81cc7f11ca069ec9226cecb8a2c850cfe644e327d22d3e1cd39a27ae3b79d68d89da9bf25bc27139ae65a324918a5f9b7828181e52cf373c84f35b639b7fccbb985b6f2fa56aea0c18f531203497b8bbd3a07ceb5926f1cab74d14bd66486d9a91eba99059a98bd1cd25876b2af5a76c3e9eed554ed72ea952b603bf",
.keyed_hash = "68dede9bef00ba89e43f31a6825f4cf433389fedae75c04ee9f0cf16a427c95a96d6da3fe985054d3478865be9a092250839a697bbda74e279e8a9e69f0025e4cfddd6cfb434b1cd9543aaf97c635d1b451a4386041e4bb100f5e45407cbbc24fa53ea2de3536ccb329e4eb9466ec37093a42cf62b82903c696a93a50b702c80f3c3c5",
.derive_key = "72613c9ec9ff7e40f8f5c173784c532ad852e827dba2bf85b2ab4b76f7079081576288e552647a9d86481c2cae75c2dd4e7c5195fb9ada1ef50e9c5098c249d743929191441301c69e1f48505a4305ec1778450ee48b8e69dc23a25960fe33070ea549119599760a8a2d28aeca06b8c5e9ba58bc19e11fe57b6ee98aa44b2a8e6b14a5",
},
.{
.input_len = 4096,
.hash = "015094013f57a5277b59d8475c0501042c0b642e531b0a1c8f58d2163229e9690289e9409ddb1b99768eafe1623da896faf7e1114bebeadc1be30829b6f8af707d85c298f4f0ff4d9438aef948335612ae921e76d411c3a9111df62d27eaf871959ae0062b5492a0feb98ef3ed4af277f5395172dbe5c311918ea0074ce0036454f620",
.keyed_hash = "befc660aea2f1718884cd8deb9902811d332f4fc4a38cf7c7300d597a081bfc0bbb64a36edb564e01e4b4aaf3b060092a6b838bea44afebd2deb8298fa562b7b597c757b9df4c911c3ca462e2ac89e9a787357aaf74c3b56d5c07bc93ce899568a3eb17d9250c20f6c5f6c1e792ec9a2dcb715398d5a6ec6d5c54f586a00403a1af1de",
.derive_key = "<KEY>",
},
.{
.input_len = 4097,
.hash = "9b4052b38f1c5fc8b1f9ff7ac7b27cd242487b3d890d15c96a1c25b8aa0fb99505f91b0b5600a11251652eacfa9497b31cd3c409ce2e45cfe6c0a016967316c426bd26f619eab5d70af9a418b845c608840390f361630bd497b1ab44019316357c61dbe091ce72fc16dc340ac3d6e009e050b3adac4b5b2c92e722cffdc46501531956",
.keyed_hash = "00df940cd36bb9fa7cbbc3556744e0dbc8191401afe70520ba292ee3ca80abbc606db4976cfdd266ae0abf667d9481831ff12e0caa268e7d3e57260c0824115a54ce595ccc897786d9dcbf495599cfd90157186a46ec800a6763f1c59e36197e9939e900809f7077c102f888caaf864b253bc41eea812656d46742e4ea42769f89b83f",
.derive_key = "aca51029626b55fda7117b42a7c211f8c6e9ba4fe5b7a8ca922f34299500ead8a897f66a400fed9198fd61dd2d58d382458e64e100128075fc54b860934e8de2e84170734b06e1d212a117100820dbc48292d148afa50567b8b84b1ec336ae10d40c8c975a624996e12de31abbe135d9d159375739c333798a80c64ae895e51e22f3ad",
},
.{
.input_len = 5120,
.hash = "9cadc15fed8b5d854562b26a9536d9707cadeda9b143978f319ab34230535833acc61c8fdc114a2010ce8038c853e121e1544985133fccdd0a2d507e8e615e611e9a0ba4f47915f49e53d721816a9198e8b30f12d20ec3689989175f1bf7a300eee0d9321fad8da232ece6efb8e9fd81b42ad161f6b9550a069e66b11b40487a5f5059",
.keyed_hash = "2c493e48e9b9bf31e0553a22b23503c0a3388f035cece68eb438d22fa1943e209b4dc9209cd80ce7c1f7c9a744658e7e288465717ae6e56d5463d4f80cdb2ef56495f6a4f5487f69749af0c34c2cdfa857f3056bf8d807336a14d7b89bf62bef2fb54f9af6a546f818dc1e98b9e07f8a5834da50fa28fb5874af91bf06020d1bf0120e",
.derive_key = "7a7acac8a02adcf3038d74cdd1d34527de8a0fcc0ee3399d1262397ce5817f6055d0cefd84d9d57fe792d65a278fd20384ac6c30fdb340092f1a74a92ace99c482b28f0fc0ef3b923e56ade20c6dba47e49227166251337d80a037e987ad3a7f728b5ab6dfafd6e2ab1bd583a95d9c895ba9c2422c24ea0f62961f0dca45cad47bfa0d",
},
.{
.input_len = 5121,
.hash = "628bd2cb2004694adaab7bbd778a25df25c47b9d4155a55f8fbd79f2fe154cff96adaab0613a6146cdaabe498c3a94e529d3fc1da2bd08edf54ed64d40dcd6777647eac51d8277d70219a9694334a68bc8f0f23e20b0ff70ada6f844542dfa32cd4204ca1846ef76d811cdb296f65e260227f477aa7aa008bac878f72257484f2b6c95",
.keyed_hash = "6ccf1c34753e7a044db80798ecd0782a8f76f33563accaddbfbb2e0ea4b2d0240d07e63f13667a8d1490e5e04f13eb617aea16a8c8a5aaed1ef6fbde1b0515e3c81050b361af6ead126032998290b563e3caddeaebfab592e155f2e161fb7cba939092133f23f9e65245e58ec23457b78a2e8a125588aad6e07d7f11a85b88d375b72d",
.derive_key = "b07f01e518e702f7ccb44a267e9e112d403a7b3f4883a47ffbed4b48339b3c341a0add0ac032ab5aaea1e4e5b004707ec5681ae0fcbe3796974c0b1cf31a194740c14519273eedaabec832e8a784b6e7cfc2c5952677e6c3f2c3914454082d7eb1ce1766ac7d75a4d3001fc89544dd46b5147382240d689bbbaefc359fb6ae30263165",
},
.{
.input_len = 6144,
.hash = "3e2e5b74e048f3add6d21faab3f83aa44d3b2278afb83b80b3c35164ebeca2054d742022da6fdda444ebc384b04a54c3ac5839b49da7d39f6d8a9db03deab32aade156c1c0311e9b3435cde0ddba0dce7b26a376cad121294b689193508dd63151603c6ddb866ad16c2ee41585d1633a2cea093bea714f4c5d6b903522045b20395c83",
.keyed_hash = "3d6b6d21281d0ade5b2b016ae4034c5dec10ca7e475f90f76eac7138e9bc8f1dc35754060091dc5caf3efabe0603c60f45e415bb3407db67e6beb3d11cf8e4f7907561f05dace0c15807f4b5f389c841eb114d81a82c02a00b57206b1d11fa6e803486b048a5ce87105a686dee041207e095323dfe172df73deb8c9532066d88f9da7e",
.derive_key = "2a95beae63ddce523762355cf4b9c1d8f131465780a391286a5d01abb5683a1597099e3c6488aab6c48f3c15dbe1942d21dbcdc12115d19a8b8465fb54e9053323a9178e4275647f1a9927f6439e52b7031a0b465c861a3fc531527f7758b2b888cf2f20582e9e2c593709c0a44f9c6e0f8b963994882ea4168827823eef1f64169fef",
},
.{
.input_len = 6145,
.hash = "f1323a8631446cc50536a9f705ee5cb619424d46887f3c376c695b70e0f0507f18a2cfdd73c6e39dd75ce7c1c6e3ef238fd54465f053b25d21044ccb2093beb015015532b108313b5829c3621ce324b8e14229091b7c93f32db2e4e63126a377d2a63a3597997d4f1cba59309cb4af240ba70cebff9a23d5e3ff0cdae2cfd54e070022",
.keyed_hash = "9ac301e9e39e45e3250a7e3b3df701aa0fb6889fbd80eeecf28dbc6300fbc539f3c184ca2f59780e27a576c1d1fb9772e99fd17881d02ac7dfd39675aca918453283ed8c3169085ef4a466b91c1649cc341dfdee60e32231fc34c9c4e0b9a2ba87ca8f372589c744c15fd6f985eec15e98136f25beeb4b13c4e43dc84abcc79cd4646c",
.derive_key = "379bcc61d0051dd489f686c13de00d5b14c505245103dc040d9e4dd1facab8e5114493d029bdbd295aaa744a59e31f35c7f52dba9c3642f773dd0b4262a9980a2aef811697e1305d37ba9d8b6d850ef07fe41108993180cf779aeece363704c76483458603bbeeb693cffbbe5588d1f3535dcad888893e53d977424bb707201569a8d2",
},
.{
.input_len = 7168,
.hash = "61da957ec2499a95d6b8023e2b0e604ec7f6b50e80a9678b89d2628e99ada77a5707c321c83361793b9af62a40f43b523df1c8633cecb4cd14d00bdc79c78fca5165b863893f6d38b02ff7236c5a9a8ad2dba87d24c547cab046c29fc5bc1ed142e1de4763613bb162a5a538e6ef05ed05199d751f9eb58d332791b8d73fb74e4fce95",
.keyed_hash = "b42835e40e9d4a7f42ad8cc04f85a963a76e18198377ed84adddeaecacc6f3fca2f01d5277d69bb681c70fa8d36094f73ec06e452c80d2ff2257ed82e7ba348400989a65ee8daa7094ae0933e3d2210ac6395c4af24f91c2b590ef87d7788d7066ea3eaebca4c08a4f14b9a27644f99084c3543711b64a070b94f2c9d1d8a90d035d52",
.derive_key = "11c37a112765370c94a51415d0d651190c288566e295d505defdad895dae223730d5a5175a38841693020669c7638f40b9bc1f9f39cf98bda7a5b54ae24218a800a2116b34665aa95d846d97ea988bfcb53dd9c055d588fa21ba78996776ea6c40bc428b53c62b5f3ccf200f647a5aae8067f0ea1976391fcc72af1945100e2a6dcb88",
},
.{
.input_len = 7169,
.hash = "a003fc7a51754a9b3c7fae0367ab3d782dccf28855a03d435f8cfe74605e781798a8b20534be1ca9eb2ae2df3fae2ea60e48c6fb0b850b1385b5de0fe460dbe9d9f9b0d8db4435da75c601156df9d047f4ede008732eb17adc05d96180f8a73548522840779e6062d643b79478a6e8dbce68927f36ebf676ffa7d72d5f68f050b119c8",
.keyed_hash = "ed9b1a922c046fdb3d423ae34e143b05ca1bf28b710432857bf738bcedbfa5113c9e28d72fcbfc020814ce3f5d4fc867f01c8f5b6caf305b3ea8a8ba2da3ab69fabcb438f19ff11f5378ad4484d75c478de425fb8e6ee809b54eec9bdb184315dc856617c09f5340451bf42fd3270a7b0b6566169f242e533777604c118a6358250f54",
.derive_key = "<KEY>",
},
.{
.input_len = 8192,
.hash = "aae792484c8efe4f19e2ca7d371d8c467ffb10748d8a5a1ae579948f718a2a635fe51a27db045a567c1ad51be5aa34c01c6651c4d9b5b5ac5d0fd58cf18dd61a47778566b797a8c67df7b1d60b97b19288d2d877bb2df417ace009dcb0241ca1257d62712b6a4043b4ff33f690d849da91ea3bf711ed583cb7b7a7da2839ba71309bbf",
.keyed_hash = "dc9637c8845a770b4cbf76b8daec0eebf7dc2eac11498517f08d44c8fc00d58a4834464159dcbc12a0ba0c6d6eb41bac0ed6585cabfe0aca36a375e6c5480c22afdc40785c170f5a6b8a1107dbee282318d00d915ac9ed1143ad40765ec120042ee121cd2baa36250c618adaf9e27260fda2f94dea8fb6f08c04f8f10c78292aa46102",
.derive_key = "ad01d7ae4ad059b0d33baa3c01319dcf8088094d0359e5fd45d6aeaa8b2d0c3d4c9e58958553513b67f84f8eac653aeeb02ae1d5672dcecf91cd9985a0e67f4501910ecba25555395427ccc7241d70dc21c190e2aadee875e5aae6bf1912837e53411dabf7a56cbf8e4fb780432b0d7fe6cec45024a0788cf5874616407757e9e6bef7",
},
.{
.input_len = 8193,
.hash = "bab6c09cb8ce8cf459261398d2e7aef35700bf488116ceb94a36d0f5f1b7bc3bb2282aa69be089359ea1154b9a9286c4a56af4de975a9aa4a5c497654914d279bea60bb6d2cf7225a2fa0ff5ef56bbe4b149f3ed15860f78b4e2ad04e158e375c1e0c0b551cd7dfc82f1b155c11b6b3ed51ec9edb30d133653bb5709d1dbd55f4e1ff6",
.keyed_hash = "954a2a75420c8d6547e3ba5b98d963e6fa6491addc8c023189cc519821b4a1f5f03228648fd983aef045c2fa8290934b0866b615f585149587dda2299039965328835a2b18f1d63b7e300fc76ff260b571839fe44876a4eae66cbac8c67694411ed7e09df51068a22c6e67d6d3dd2cca8ff12e3275384006c80f4db68023f24eebba57",
.derive_key = "af1e0346e389b17c23200270a64aa4e1ead98c61695d917de7d5b00491c9b0f12f20a01d6d622edf3de026a4db4e4526225debb93c1237934d71c7340bb5916158cbdafe9ac3225476b6ab57a12357db3abbad7a26c6e66290e44034fb08a20a8d0ec264f309994d2810c49cfba6989d7abb095897459f5425adb48aba07c5fb3c83c0",
},
.{
.input_len = 16384,
.hash = "f875d6646de28985646f34ee13be9a576fd515f76b5b0a26bb324735041ddde49d764c270176e53e97bdffa58d549073f2c660be0e81293767ed4e4929f9ad34bbb39a529334c57c4a381ffd2a6d4bfdbf1482651b172aa883cc13408fa67758a3e47503f93f87720a3177325f7823251b85275f64636a8f1d599c2e49722f42e93893",
.keyed_hash = "9e9fc4eb7cf081ea7c47d1807790ed211bfec56aa25bb7037784c13c4b707b0df9e601b101e4cf63a404dfe50f2e1865bb12edc8fca166579ce0c70dba5a5c0fc960ad6f3772183416a00bd29d4c6e651ea7620bb100c9449858bf14e1ddc9ecd35725581ca5b9160de04060045993d972571c3e8f71e9d0496bfa744656861b169d65",
.derive_key = "<KEY>",
},
.{
.input_len = 31744,
.hash = "62b6960e1a44bcc1eb1a611a8d6235b6b4b78f32e7abc4fb4c6cdcce94895c47860cc51f2b0c28a7b77304bd55fe73af663c02d3f52ea053ba43431ca5bab7bfea2f5e9d7121770d88f70ae9649ea713087d1914f7f312147e247f87eb2d4ffef0ac978bf7b6579d57d533355aa20b8b77b13fd09748728a5cc327a8ec470f4013226f",
.keyed_hash = "efa53b389ab67c593dba624d898d0f7353ab99e4ac9d42302ee64cbf9939a4193a7258db2d9cd32a7a3ecfce46144114b15c2fcb68a618a976bd74515d47be08b628be420b5e830fade7c080e351a076fbc38641ad80c736c8a18fe3c66ce12f95c61c2462a9770d60d0f77115bbcd3782b593016a4e728d4c06cee4505cb0c08a42ec",
.derive_key = "39772aef80e0ebe60596361e45b061e8f417429d529171b6764468c22928e28e9759adeb797a3fbf771b1bcea30150a020e317982bf0d6e7d14dd9f064bc11025c25f31e81bd78a921db0174f03dd481d30e93fd8e90f8b2fee209f849f2d2a52f31719a490fb0ba7aea1e09814ee912eba111a9fde9d5c274185f7bae8ba85d300a2b",
},
.{
.input_len = 102400,
.hash = "bc3e3d41a1146b069abffad3c0d44860cf664390afce4d9661f7902e7943e085e01c59dab908c04c3342b816941a26d69c2605ebee5ec5291cc55e15b76146e6745f0601156c3596cb75065a9c57f35585a52e1ac70f69131c23d611ce11ee4ab1ec2c009012d236648e77be9295dd0426f29b764d65de58eb7d01dd42248204f45f8e",
.keyed_hash = "1c35d1a5811083fd7119f5d5d1ba027b4d01c0c6c49fb6ff2cf75393ea5db4a7f9dbdd3e1d81dcbca3ba241bb18760f207710b751846faaeb9dff8262710999a59b2aa1aca298a032d94eacfadf1aa192418eb54808db23b56e34213266aa08499a16b354f018fc4967d05f8b9d2ad87a7278337be9693fc638a3bfdbe314574ee6fc4",
.derive_key = "4652cff7a3f385a6103b5c260fc1593e13c778dbe608efb092fe7ee69df6e9c6d83a3e041bc3a48df2879f4a0a3ed40e7c961c73eff740f3117a0504c2dff4786d44fb17f1549eb0ba585e40ec29bf7732f0b7e286ff8acddc4cb1e23b87ff5d824a986458dcc6a04ac83969b80637562953df51ed1a7e90a7926924d2763778be8560",
},
},
};
fn testBlake3(hasher: *Blake3, input_len: usize, expected_hex: [262]u8) void {
// Save initial state
const initial_state = hasher.*;
// Setup input pattern
var input_pattern: [251]u8 = undefined;
for (input_pattern) |*e, i| e.* = @truncate(u8, i);
// Write repeating input pattern to hasher
var input_counter = input_len;
while (input_counter > 0) {
const update_len = math.min(input_counter, input_pattern.len);
hasher.update(input_pattern[0..update_len]);
input_counter -= update_len;
}
// Read final hash value
var actual_bytes: [expected_hex.len / 2]u8 = undefined;
hasher.final(actual_bytes[0..]);
// Compare to expected value
var expected_bytes: [expected_hex.len / 2]u8 = undefined;
fmt.hexToBytes(expected_bytes[0..], expected_hex[0..]) catch unreachable;
testing.expectEqual(actual_bytes, expected_bytes);
// Restore initial state
hasher.* = initial_state;
}
test "BLAKE3 reference test cases" {
var hash = &Blake3.init(.{});
var keyed_hash = &Blake3.init(.{ .key = reference_test.key.* });
var derive_key = &Blake3.initKdf(reference_test.context_string, .{});
for (reference_test.cases) |t| {
testBlake3(hash, t.input_len, t.hash.*);
testBlake3(keyed_hash, t.input_len, t.keyed_hash.*);
testBlake3(derive_key, t.input_len, t.derive_key.*);
}
}
|
lib/std/crypto/blake3.zig
|
const freetype2 = @import("freetype2.zig");
const std = @import("std");
pub const FontRasterizer = struct {
pub var library: freetype2.FT_Library = null;
pub var fonts = [_]freetype2.FT_Face{null} ** 16;
pub var fonts_count: u8 = 0;
pub fn init(self: *@This()) void {
// var library: freetype2.FT_Library;
var freetype_init_error = freetype2.FT_Init_FreeType(&library);
if (freetype_init_error != 0) {
@panic("freetype could not be initialized! While this shouldn't be a panic, I don't see why this should be able to fail ... and therefore am clueless as to how to handle that ...");
}
}
pub fn loadFont(self: *@This(), file: [*:0]const u8) i32 { // todo: better errorhandling ... there are many different reasons this might fail
if (fonts_count >= fonts.len) {
return -1;
}
var freetype_load_error = freetype2.FT_New_Face(library, file, 0, &fonts[fonts_count]);
if (freetype_load_error != 0) {
// todo: handle error?
return -1;
}
fonts_count += 1;
return @intCast(i32, fonts_count) - 1;
}
pub const RenderedGlyphInfo = struct {
pixels: [*]const u8 = undefined,
width: u32 = 0,
height: u32 = 0,
offset_x: i32 = 0,
offset_y: i32 = 0,
};
pub fn renderGlyph(self: @This(), font_index: i32, pixel_height: u32, code: u32) RenderedGlyphInfo {
var idx = @intCast(usize, font_index);
var size_error = freetype2.FT_Set_Pixel_Sizes(fonts[idx], 0, pixel_height);
var glyph_index = freetype2.FT_Get_Char_Index(fonts[idx], code);
var glyph_load_error = freetype2.FT_Load_Glyph(fonts[idx], glyph_index, 0);
var glyph_render_error = freetype2.FT_Render_Glyph(fonts[idx].*.glyph, freetype2.FT_Render_Mode.FT_RENDER_MODE_NORMAL);
var ret = .{
.pixels = fonts[idx].*.glyph.*.bitmap.buffer,
.width = fonts[idx].*.glyph.*.bitmap.width,
.height = fonts[idx].*.glyph.*.bitmap.rows,
.offset_x = fonts[idx].*.glyph.*.bitmap_left,
.offset_y = fonts[idx].*.glyph.*.bitmap_top,
};
return ret;
}
};
test "load example font" {
var rast: FontRasterizer = .{};
std.debug.print("\nrast: {s}\n", .{rast});
rast.init();
var font_index = rast.loadFont("./ProggyVector Regular.ttf");
var glyph_info = rast.renderGlyph(font_index, 60, 'A');
var y: u32 = 0;
while (y < glyph_info.height) {
defer y += 1;
var x: u32 = 0;
while (x < glyph_info.width) {
defer x += 1;
std.debug.print("{x:0>2} ", .{glyph_info.pixels[x + y * glyph_info.width]});
}
std.debug.print("\n", .{});
}
}
|
font.zig
|
const aoc = @import("../aoc.zig");
const std = @import("std");
const Allocator = std.mem.Allocator;
const Combinator = struct {
pub const CombinationResult = struct {
unprocessed: Elements = undefined,
sum: usize = 0,
product: usize = 1,
};
const Elements = []const usize;
const ResultBuf = std.ArrayList(usize);
elements: Elements,
unprocessed_buf: ResultBuf,
r: u6 = undefined,
last_bitmask: usize = undefined,
max_bitmask: usize = undefined,
pub fn init(allocator: Allocator, elements: Elements) Combinator {
return Combinator {
.elements = elements,
.unprocessed_buf = ResultBuf.init(allocator),
};
}
pub fn deinit(self: *Combinator) void {
self.unprocessed_buf.deinit();
}
pub fn reset_with_combinations(self: *Combinator, r: u6) void {
self.r = r;
self.last_bitmask = (@intCast(usize, 1) << r) - 1;
self.max_bitmask = self.last_bitmask << (@intCast(u6, self.elements.len) - r);
}
pub fn next(self: *Combinator) !?CombinationResult {
while (self.last_bitmask <= self.max_bitmask) {
const bitmask = self.last_bitmask;
self.last_bitmask += 1;
if (@popCount(usize, bitmask) == self.r) {
self.unprocessed_buf.items.len = 0;
var result = CombinationResult {};
var idx: usize = 0;
while (idx < self.elements.len) : (idx += 1) {
const element = self.elements[idx];
if ((@intCast(usize, 1) << @intCast(u6, idx)) & bitmask == 0) {
try self.unprocessed_buf.append(element);
}
else {
result.sum += element;
result.product *= element;
}
}
result.unprocessed = self.unprocessed_buf.items;
return result;
}
}
return null;
}
};
const QuantumEntanglement = struct {
const Weights = std.ArrayList(usize);
allocator: Allocator,
weights: Weights,
total_weight: usize = 0,
fn init(allocator: Allocator) QuantumEntanglement {
return QuantumEntanglement { .allocator = allocator, .weights = Weights.init(allocator) };
}
fn deinit(self: *QuantumEntanglement) void {
self.weights.deinit();
}
fn addWeight(self: *QuantumEntanglement, weight: usize) !void {
try self.weights.append(weight);
self.total_weight += weight;
}
fn calcMinQe(self: *QuantumEntanglement, groups: u8) !usize {
const target_weight = self.total_weight / groups;
const max_usize: usize = std.math.maxInt(usize);
var min_qe = max_usize;
var combinator = Combinator.init(self.allocator, self.weights.items);
defer combinator.deinit();
var r: u6 = 1;
while (min_qe == max_usize) : (r += 1) {
combinator.reset_with_combinations(r);
while (try combinator.next()) |result| {
if (result.sum == target_weight and result.product < min_qe and
try self.isValidGroup(result.unprocessed, groups - 1, r, target_weight)) {
min_qe = result.product;
}
}
}
return min_qe;
}
fn isValidGroup(self: *QuantumEntanglement, group: []const usize, depth: u8, min_r: u6, target_weight: usize) anyerror!bool {
var combinator = Combinator.init(self.allocator, group);
defer combinator.deinit();
var r: u6 = min_r;
while (r <= group.len / depth) : (r += 1) {
combinator.reset_with_combinations(r);
while (try combinator.next()) |result| {
if (result.sum == target_weight) {
if (depth == 2) {
return true;
}
if (try self.isValidGroup(result.unprocessed, depth - 1, r, target_weight)) {
return true;
}
}
}
}
return false;
}
fn printSlice(slice: []const usize) void {
for (slice) |a| {
std.debug.print("{} ", .{a});
}
std.debug.print("\n", .{});
}
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var qe = QuantumEntanglement.init(problem.allocator);
defer qe.deinit();
while (problem.line()) |line| {
const weight = try std.fmt.parseInt(usize, line, 10);
try qe.addWeight(weight);
}
const qe1 = try qe.calcMinQe(3);
const qe2 = try qe.calcMinQe(4);
return problem.solution(qe1, qe2);
}
|
src/main/zig/2015/day24.zig
|
const std = @import("std");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const log = std.log.scoped(.sema);
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const TypedValue = @import("TypedValue.zig");
const ir = @import("ir.zig");
const zir = @import("zir.zig");
const Module = @import("Module.zig");
const Inst = ir.Inst;
const Body = ir.Body;
const trace = @import("tracy.zig").trace;
const Scope = Module.Scope;
const InnerError = Module.InnerError;
const Decl = Module.Decl;
pub fn analyzeInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Inst {
switch (old_inst.tag) {
.alloc => return zirAlloc(mod, scope, old_inst.castTag(.alloc).?),
.alloc_mut => return zirAllocMut(mod, scope, old_inst.castTag(.alloc_mut).?),
.alloc_inferred => return zirAllocInferred(mod, scope, old_inst.castTag(.alloc_inferred).?, .inferred_alloc_const),
.alloc_inferred_mut => return zirAllocInferred(mod, scope, old_inst.castTag(.alloc_inferred_mut).?, .inferred_alloc_mut),
.arg => return zirArg(mod, scope, old_inst.castTag(.arg).?),
.bitcast_ref => return zirBitcastRef(mod, scope, old_inst.castTag(.bitcast_ref).?),
.bitcast_result_ptr => return zirBitcastResultPtr(mod, scope, old_inst.castTag(.bitcast_result_ptr).?),
.block => return zirBlock(mod, scope, old_inst.castTag(.block).?, false),
.block_comptime => return zirBlock(mod, scope, old_inst.castTag(.block_comptime).?, true),
.block_flat => return zirBlockFlat(mod, scope, old_inst.castTag(.block_flat).?, false),
.block_comptime_flat => return zirBlockFlat(mod, scope, old_inst.castTag(.block_comptime_flat).?, true),
.@"break" => return zirBreak(mod, scope, old_inst.castTag(.@"break").?),
.breakpoint => return zirBreakpoint(mod, scope, old_inst.castTag(.breakpoint).?),
.break_void => return zirBreakVoid(mod, scope, old_inst.castTag(.break_void).?),
.call => return zirCall(mod, scope, old_inst.castTag(.call).?),
.coerce_result_ptr => return zirCoerceResultPtr(mod, scope, old_inst.castTag(.coerce_result_ptr).?),
.compile_error => return zirCompileError(mod, scope, old_inst.castTag(.compile_error).?),
.compile_log => return zirCompileLog(mod, scope, old_inst.castTag(.compile_log).?),
.@"const" => return zirConst(mod, scope, old_inst.castTag(.@"const").?),
.dbg_stmt => return zirDbgStmt(mod, scope, old_inst.castTag(.dbg_stmt).?),
.decl_ref => return zirDeclRef(mod, scope, old_inst.castTag(.decl_ref).?),
.decl_ref_str => return zirDeclRefStr(mod, scope, old_inst.castTag(.decl_ref_str).?),
.decl_val => return zirDeclVal(mod, scope, old_inst.castTag(.decl_val).?),
.ensure_result_used => return zirEnsureResultUsed(mod, scope, old_inst.castTag(.ensure_result_used).?),
.ensure_result_non_error => return zirEnsureResultNonError(mod, scope, old_inst.castTag(.ensure_result_non_error).?),
.indexable_ptr_len => return zirIndexablePtrLen(mod, scope, old_inst.castTag(.indexable_ptr_len).?),
.ref => return zirRef(mod, scope, old_inst.castTag(.ref).?),
.resolve_inferred_alloc => return zirResolveInferredAlloc(mod, scope, old_inst.castTag(.resolve_inferred_alloc).?),
.ret_ptr => return zirRetPtr(mod, scope, old_inst.castTag(.ret_ptr).?),
.ret_type => return zirRetType(mod, scope, old_inst.castTag(.ret_type).?),
.store_to_block_ptr => return zirStoreToBlockPtr(mod, scope, old_inst.castTag(.store_to_block_ptr).?),
.store_to_inferred_ptr => return zirStoreToInferredPtr(mod, scope, old_inst.castTag(.store_to_inferred_ptr).?),
.single_const_ptr_type => return zirSimplePtrType(mod, scope, old_inst.castTag(.single_const_ptr_type).?, false, .One),
.single_mut_ptr_type => return zirSimplePtrType(mod, scope, old_inst.castTag(.single_mut_ptr_type).?, true, .One),
.many_const_ptr_type => return zirSimplePtrType(mod, scope, old_inst.castTag(.many_const_ptr_type).?, false, .Many),
.many_mut_ptr_type => return zirSimplePtrType(mod, scope, old_inst.castTag(.many_mut_ptr_type).?, true, .Many),
.c_const_ptr_type => return zirSimplePtrType(mod, scope, old_inst.castTag(.c_const_ptr_type).?, false, .C),
.c_mut_ptr_type => return zirSimplePtrType(mod, scope, old_inst.castTag(.c_mut_ptr_type).?, true, .C),
.const_slice_type => return zirSimplePtrType(mod, scope, old_inst.castTag(.const_slice_type).?, false, .Slice),
.mut_slice_type => return zirSimplePtrType(mod, scope, old_inst.castTag(.mut_slice_type).?, true, .Slice),
.ptr_type => return zirPtrType(mod, scope, old_inst.castTag(.ptr_type).?),
.store => return zirStore(mod, scope, old_inst.castTag(.store).?),
.set_eval_branch_quota => return zirSetEvalBranchQuota(mod, scope, old_inst.castTag(.set_eval_branch_quota).?),
.str => return zirStr(mod, scope, old_inst.castTag(.str).?),
.int => return zirInt(mod, scope, old_inst.castTag(.int).?),
.int_type => return zirIntType(mod, scope, old_inst.castTag(.int_type).?),
.loop => return zirLoop(mod, scope, old_inst.castTag(.loop).?),
.param_type => return zirParamType(mod, scope, old_inst.castTag(.param_type).?),
.ptrtoint => return zirPtrtoint(mod, scope, old_inst.castTag(.ptrtoint).?),
.field_ptr => return zirFieldPtr(mod, scope, old_inst.castTag(.field_ptr).?),
.field_val => return zirFieldVal(mod, scope, old_inst.castTag(.field_val).?),
.field_ptr_named => return zirFieldPtrNamed(mod, scope, old_inst.castTag(.field_ptr_named).?),
.field_val_named => return zirFieldValNamed(mod, scope, old_inst.castTag(.field_val_named).?),
.deref => return zirDeref(mod, scope, old_inst.castTag(.deref).?),
.as => return zirAs(mod, scope, old_inst.castTag(.as).?),
.@"asm" => return zirAsm(mod, scope, old_inst.castTag(.@"asm").?),
.unreachable_safe => return zirUnreachable(mod, scope, old_inst.castTag(.unreachable_safe).?, true),
.unreachable_unsafe => return zirUnreachable(mod, scope, old_inst.castTag(.unreachable_unsafe).?, false),
.@"return" => return zirReturn(mod, scope, old_inst.castTag(.@"return").?),
.return_void => return zirReturnVoid(mod, scope, old_inst.castTag(.return_void).?),
.@"fn" => return zirFn(mod, scope, old_inst.castTag(.@"fn").?),
.@"export" => return zirExport(mod, scope, old_inst.castTag(.@"export").?),
.primitive => return zirPrimitive(mod, scope, old_inst.castTag(.primitive).?),
.fn_type => return zirFnType(mod, scope, old_inst.castTag(.fn_type).?, false),
.fn_type_cc => return zirFnTypeCc(mod, scope, old_inst.castTag(.fn_type_cc).?, false),
.fn_type_var_args => return zirFnType(mod, scope, old_inst.castTag(.fn_type_var_args).?, true),
.fn_type_cc_var_args => return zirFnTypeCc(mod, scope, old_inst.castTag(.fn_type_cc_var_args).?, true),
.intcast => return zirIntcast(mod, scope, old_inst.castTag(.intcast).?),
.bitcast => return zirBitcast(mod, scope, old_inst.castTag(.bitcast).?),
.floatcast => return zirFloatcast(mod, scope, old_inst.castTag(.floatcast).?),
.elem_ptr => return zirElemPtr(mod, scope, old_inst.castTag(.elem_ptr).?),
.elem_val => return zirElemVal(mod, scope, old_inst.castTag(.elem_val).?),
.add => return zirArithmetic(mod, scope, old_inst.castTag(.add).?),
.addwrap => return zirArithmetic(mod, scope, old_inst.castTag(.addwrap).?),
.sub => return zirArithmetic(mod, scope, old_inst.castTag(.sub).?),
.subwrap => return zirArithmetic(mod, scope, old_inst.castTag(.subwrap).?),
.mul => return zirArithmetic(mod, scope, old_inst.castTag(.mul).?),
.mulwrap => return zirArithmetic(mod, scope, old_inst.castTag(.mulwrap).?),
.div => return zirArithmetic(mod, scope, old_inst.castTag(.div).?),
.mod_rem => return zirArithmetic(mod, scope, old_inst.castTag(.mod_rem).?),
.array_cat => return zirArrayCat(mod, scope, old_inst.castTag(.array_cat).?),
.array_mul => return zirArrayMul(mod, scope, old_inst.castTag(.array_mul).?),
.bit_and => return zirBitwise(mod, scope, old_inst.castTag(.bit_and).?),
.bit_not => return zirBitNot(mod, scope, old_inst.castTag(.bit_not).?),
.bit_or => return zirBitwise(mod, scope, old_inst.castTag(.bit_or).?),
.xor => return zirBitwise(mod, scope, old_inst.castTag(.xor).?),
.shl => return zirShl(mod, scope, old_inst.castTag(.shl).?),
.shr => return zirShr(mod, scope, old_inst.castTag(.shr).?),
.cmp_lt => return zirCmp(mod, scope, old_inst.castTag(.cmp_lt).?, .lt),
.cmp_lte => return zirCmp(mod, scope, old_inst.castTag(.cmp_lte).?, .lte),
.cmp_eq => return zirCmp(mod, scope, old_inst.castTag(.cmp_eq).?, .eq),
.cmp_gte => return zirCmp(mod, scope, old_inst.castTag(.cmp_gte).?, .gte),
.cmp_gt => return zirCmp(mod, scope, old_inst.castTag(.cmp_gt).?, .gt),
.cmp_neq => return zirCmp(mod, scope, old_inst.castTag(.cmp_neq).?, .neq),
.condbr => return zirCondbr(mod, scope, old_inst.castTag(.condbr).?),
.is_null => return zirIsNull(mod, scope, old_inst.castTag(.is_null).?, false),
.is_non_null => return zirIsNull(mod, scope, old_inst.castTag(.is_non_null).?, true),
.is_null_ptr => return zirIsNullPtr(mod, scope, old_inst.castTag(.is_null_ptr).?, false),
.is_non_null_ptr => return zirIsNullPtr(mod, scope, old_inst.castTag(.is_non_null_ptr).?, true),
.is_err => return zirIsErr(mod, scope, old_inst.castTag(.is_err).?),
.is_err_ptr => return zirIsErrPtr(mod, scope, old_inst.castTag(.is_err_ptr).?),
.bool_not => return zirBoolNot(mod, scope, old_inst.castTag(.bool_not).?),
.typeof => return zirTypeof(mod, scope, old_inst.castTag(.typeof).?),
.typeof_peer => return zirTypeofPeer(mod, scope, old_inst.castTag(.typeof_peer).?),
.optional_type => return zirOptionalType(mod, scope, old_inst.castTag(.optional_type).?),
.optional_type_from_ptr_elem => return zirOptionalTypeFromPtrElem(mod, scope, old_inst.castTag(.optional_type_from_ptr_elem).?),
.optional_payload_safe => return zirOptionalPayload(mod, scope, old_inst.castTag(.optional_payload_safe).?, true),
.optional_payload_unsafe => return zirOptionalPayload(mod, scope, old_inst.castTag(.optional_payload_unsafe).?, false),
.optional_payload_safe_ptr => return zirOptionalPayloadPtr(mod, scope, old_inst.castTag(.optional_payload_safe_ptr).?, true),
.optional_payload_unsafe_ptr => return zirOptionalPayloadPtr(mod, scope, old_inst.castTag(.optional_payload_unsafe_ptr).?, false),
.err_union_payload_safe => return zirErrUnionPayload(mod, scope, old_inst.castTag(.err_union_payload_safe).?, true),
.err_union_payload_unsafe => return zirErrUnionPayload(mod, scope, old_inst.castTag(.err_union_payload_unsafe).?, false),
.err_union_payload_safe_ptr => return zirErrUnionPayloadPtr(mod, scope, old_inst.castTag(.err_union_payload_safe_ptr).?, true),
.err_union_payload_unsafe_ptr => return zirErrUnionPayloadPtr(mod, scope, old_inst.castTag(.err_union_payload_unsafe_ptr).?, false),
.err_union_code => return zirErrUnionCode(mod, scope, old_inst.castTag(.err_union_code).?),
.err_union_code_ptr => return zirErrUnionCodePtr(mod, scope, old_inst.castTag(.err_union_code_ptr).?),
.ensure_err_payload_void => return zirEnsureErrPayloadVoid(mod, scope, old_inst.castTag(.ensure_err_payload_void).?),
.array_type => return zirArrayType(mod, scope, old_inst.castTag(.array_type).?),
.array_type_sentinel => return zirArrayTypeSentinel(mod, scope, old_inst.castTag(.array_type_sentinel).?),
.enum_literal => return zirEnumLiteral(mod, scope, old_inst.castTag(.enum_literal).?),
.merge_error_sets => return zirMergeErrorSets(mod, scope, old_inst.castTag(.merge_error_sets).?),
.error_union_type => return zirErrorUnionType(mod, scope, old_inst.castTag(.error_union_type).?),
.anyframe_type => return zirAnyframeType(mod, scope, old_inst.castTag(.anyframe_type).?),
.error_set => return zirErrorSet(mod, scope, old_inst.castTag(.error_set).?),
.error_value => return zirErrorValue(mod, scope, old_inst.castTag(.error_value).?),
.slice => return zirSlice(mod, scope, old_inst.castTag(.slice).?),
.slice_start => return zirSliceStart(mod, scope, old_inst.castTag(.slice_start).?),
.import => return zirImport(mod, scope, old_inst.castTag(.import).?),
.bool_and => return zirBoolOp(mod, scope, old_inst.castTag(.bool_and).?),
.bool_or => return zirBoolOp(mod, scope, old_inst.castTag(.bool_or).?),
.void_value => return mod.constVoid(scope, old_inst.src),
.switchbr => return zirSwitchBr(mod, scope, old_inst.castTag(.switchbr).?, false),
.switchbr_ref => return zirSwitchBr(mod, scope, old_inst.castTag(.switchbr_ref).?, true),
.switch_range => return zirSwitchRange(mod, scope, old_inst.castTag(.switch_range).?),
.@"await" => return zirAwait(mod, scope, old_inst.castTag(.@"await").?),
.nosuspend_await => return zirAwait(mod, scope, old_inst.castTag(.nosuspend_await).?),
.@"resume" => return zirResume(mod, scope, old_inst.castTag(.@"resume").?),
.@"suspend" => return zirSuspend(mod, scope, old_inst.castTag(.@"suspend").?),
.suspend_block => return zirSuspendBlock(mod, scope, old_inst.castTag(.suspend_block).?),
.container_field_named,
.container_field_typed,
.container_field,
.enum_type,
.union_type,
.struct_type,
=> return mod.fail(scope, old_inst.src, "TODO analyze container instructions", .{}),
}
}
pub fn analyzeBody(mod: *Module, block: *Scope.Block, body: zir.Body) !void {
const tracy = trace(@src());
defer tracy.end();
for (body.instructions) |src_inst| {
const analyzed_inst = try analyzeInst(mod, &block.base, src_inst);
try block.inst_table.putNoClobber(src_inst, analyzed_inst);
if (analyzed_inst.ty.zigTypeTag() == .NoReturn) {
break;
}
}
}
pub fn analyzeBodyValueAsType(
mod: *Module,
block_scope: *Scope.Block,
zir_result_inst: *zir.Inst,
body: zir.Body,
) !Type {
try analyzeBody(mod, block_scope, body);
const result_inst = block_scope.inst_table.get(zir_result_inst).?;
const val = try mod.resolveConstValue(&block_scope.base, result_inst);
return val.toType(block_scope.base.arena());
}
pub fn resolveInst(mod: *Module, scope: *Scope, zir_inst: *zir.Inst) InnerError!*Inst {
const block = scope.cast(Scope.Block).?;
return block.inst_table.get(zir_inst).?; // Instruction does not dominate all uses!
}
fn resolveConstString(mod: *Module, scope: *Scope, old_inst: *zir.Inst) ![]u8 {
const new_inst = try resolveInst(mod, scope, old_inst);
const wanted_type = Type.initTag(.const_slice_u8);
const coerced_inst = try mod.coerce(scope, wanted_type, new_inst);
const val = try mod.resolveConstValue(scope, coerced_inst);
return val.toAllocatedBytes(scope.arena());
}
fn resolveType(mod: *Module, scope: *Scope, old_inst: *zir.Inst) !Type {
const new_inst = try resolveInst(mod, scope, old_inst);
const wanted_type = Type.initTag(.@"type");
const coerced_inst = try mod.coerce(scope, wanted_type, new_inst);
const val = try mod.resolveConstValue(scope, coerced_inst);
return val.toType(scope.arena());
}
/// Appropriate to call when the coercion has already been done by result
/// location semantics. Asserts the value fits in the provided `Int` type.
/// Only supports `Int` types 64 bits or less.
fn resolveAlreadyCoercedInt(
mod: *Module,
scope: *Scope,
old_inst: *zir.Inst,
comptime Int: type,
) !Int {
comptime assert(@typeInfo(Int).Int.bits <= 64);
const new_inst = try resolveInst(mod, scope, old_inst);
const val = try mod.resolveConstValue(scope, new_inst);
switch (@typeInfo(Int).Int.signedness) {
.signed => return @intCast(Int, val.toSignedInt()),
.unsigned => return @intCast(Int, val.toUnsignedInt()),
}
}
fn resolveInt(mod: *Module, scope: *Scope, old_inst: *zir.Inst, dest_type: Type) !u64 {
const new_inst = try resolveInst(mod, scope, old_inst);
const coerced = try mod.coerce(scope, dest_type, new_inst);
const val = try mod.resolveConstValue(scope, coerced);
return val.toUnsignedInt();
}
pub fn resolveInstConst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!TypedValue {
const new_inst = try resolveInst(mod, scope, old_inst);
const val = try mod.resolveConstValue(scope, new_inst);
return TypedValue{
.ty = new_inst.ty,
.val = val,
};
}
fn zirConst(mod: *Module, scope: *Scope, const_inst: *zir.Inst.Const) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// Move the TypedValue from old memory to new memory. This allows freeing the ZIR instructions
// after analysis.
const typed_value_copy = try const_inst.positionals.typed_value.copy(scope.arena());
return mod.constInst(scope, const_inst.base.src, typed_value_copy);
}
fn analyzeConstInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!TypedValue {
const new_inst = try analyzeInst(mod, scope, old_inst);
return TypedValue{
.ty = new_inst.ty,
.val = try mod.resolveConstValue(scope, new_inst),
};
}
fn zirBitcastRef(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inst.base.src, "TODO implement zir_sema.zirBitcastRef", .{});
}
fn zirBitcastResultPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inst.base.src, "TODO implement zir_sema.zirBitcastResultPtr", .{});
}
fn zirCoerceResultPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inst.base.src, "TODO implement zirCoerceResultPtr", .{});
}
fn zirRetPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const b = try mod.requireFunctionBlock(scope, inst.base.src);
const fn_ty = b.func.?.owner_decl.typed_value.most_recent.typed_value.ty;
const ret_type = fn_ty.fnReturnType();
const ptr_type = try mod.simplePtrType(scope, inst.base.src, ret_type, true, .One);
return mod.addNoOp(b, inst.base.src, ptr_type, .alloc);
}
fn zirRef(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, inst.positionals.operand);
return mod.analyzeRef(scope, inst.base.src, operand);
}
fn zirRetType(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const b = try mod.requireFunctionBlock(scope, inst.base.src);
const fn_ty = b.func.?.owner_decl.typed_value.most_recent.typed_value.ty;
const ret_type = fn_ty.fnReturnType();
return mod.constType(scope, inst.base.src, ret_type);
}
fn zirEnsureResultUsed(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, inst.positionals.operand);
switch (operand.ty.zigTypeTag()) {
.Void, .NoReturn => return mod.constVoid(scope, operand.src),
else => return mod.fail(scope, operand.src, "expression value is ignored", .{}),
}
}
fn zirEnsureResultNonError(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, inst.positionals.operand);
switch (operand.ty.zigTypeTag()) {
.ErrorSet, .ErrorUnion => return mod.fail(scope, operand.src, "error is discarded", .{}),
else => return mod.constVoid(scope, operand.src),
}
}
fn zirIndexablePtrLen(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const array_ptr = try resolveInst(mod, scope, inst.positionals.operand);
const elem_ty = array_ptr.ty.elemType();
if (!elem_ty.isIndexable()) {
const msg = msg: {
const msg = try mod.errMsg(
scope,
inst.base.src,
"type '{}' does not support indexing",
.{elem_ty},
);
errdefer msg.destroy(mod.gpa);
try mod.errNote(
scope,
inst.base.src,
msg,
"for loop operand must be an array, slice, tuple, or vector",
.{},
);
break :msg msg;
};
return mod.failWithOwnedErrorMsg(scope, msg);
}
const result_ptr = try mod.namedFieldPtr(scope, inst.base.src, array_ptr, "len", inst.base.src);
return mod.analyzeDeref(scope, inst.base.src, result_ptr, result_ptr.src);
}
fn zirAlloc(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const var_type = try resolveType(mod, scope, inst.positionals.operand);
const ptr_type = try mod.simplePtrType(scope, inst.base.src, var_type, true, .One);
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
return mod.addNoOp(b, inst.base.src, ptr_type, .alloc);
}
fn zirAllocMut(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const var_type = try resolveType(mod, scope, inst.positionals.operand);
try mod.validateVarType(scope, inst.base.src, var_type);
const ptr_type = try mod.simplePtrType(scope, inst.base.src, var_type, true, .One);
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
return mod.addNoOp(b, inst.base.src, ptr_type, .alloc);
}
fn zirAllocInferred(
mod: *Module,
scope: *Scope,
inst: *zir.Inst.NoOp,
mut_tag: Type.Tag,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const val_payload = try scope.arena().create(Value.Payload.InferredAlloc);
val_payload.* = .{
.data = .{},
};
// `Module.constInst` does not add the instruction to the block because it is
// not needed in the case of constant values. However here, we plan to "downgrade"
// to a normal instruction when we hit `resolve_inferred_alloc`. So we append
// to the block even though it is currently a `.constant`.
const result = try mod.constInst(scope, inst.base.src, .{
.ty = switch (mut_tag) {
.inferred_alloc_const => Type.initTag(.inferred_alloc_const),
.inferred_alloc_mut => Type.initTag(.inferred_alloc_mut),
else => unreachable,
},
.val = Value.initPayload(&val_payload.base),
});
const block = try mod.requireFunctionBlock(scope, inst.base.src);
try block.instructions.append(mod.gpa, result);
return result;
}
fn zirResolveInferredAlloc(
mod: *Module,
scope: *Scope,
inst: *zir.Inst.UnOp,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, inst.positionals.operand);
const ptr_val = ptr.castTag(.constant).?.val;
const inferred_alloc = ptr_val.castTag(.inferred_alloc).?;
const peer_inst_list = inferred_alloc.data.stored_inst_list.items;
const final_elem_ty = try mod.resolvePeerTypes(scope, peer_inst_list);
const var_is_mut = switch (ptr.ty.tag()) {
.inferred_alloc_const => false,
.inferred_alloc_mut => true,
else => unreachable,
};
if (var_is_mut) {
try mod.validateVarType(scope, inst.base.src, final_elem_ty);
}
const final_ptr_ty = try mod.simplePtrType(scope, inst.base.src, final_elem_ty, true, .One);
// Change it to a normal alloc.
ptr.ty = final_ptr_ty;
ptr.tag = .alloc;
return mod.constVoid(scope, inst.base.src);
}
fn zirStoreToBlockPtr(
mod: *Module,
scope: *Scope,
inst: *zir.Inst.BinOp,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, inst.positionals.lhs);
const value = try resolveInst(mod, scope, inst.positionals.rhs);
const ptr_ty = try mod.simplePtrType(scope, inst.base.src, value.ty, true, .One);
// TODO detect when this store should be done at compile-time. For example,
// if expressions should force it when the condition is compile-time known.
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
const bitcasted_ptr = try mod.addUnOp(b, inst.base.src, ptr_ty, .bitcast, ptr);
return mod.storePtr(scope, inst.base.src, bitcasted_ptr, value);
}
fn zirStoreToInferredPtr(
mod: *Module,
scope: *Scope,
inst: *zir.Inst.BinOp,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, inst.positionals.lhs);
const value = try resolveInst(mod, scope, inst.positionals.rhs);
const inferred_alloc = ptr.castTag(.constant).?.val.castTag(.inferred_alloc).?;
// Add the stored instruction to the set we will use to resolve peer types
// for the inferred allocation.
try inferred_alloc.data.stored_inst_list.append(scope.arena(), value);
// Create a runtime bitcast instruction with exactly the type the pointer wants.
const ptr_ty = try mod.simplePtrType(scope, inst.base.src, value.ty, true, .One);
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
const bitcasted_ptr = try mod.addUnOp(b, inst.base.src, ptr_ty, .bitcast, ptr);
return mod.storePtr(scope, inst.base.src, bitcasted_ptr, value);
}
fn zirSetEvalBranchQuota(
mod: *Module,
scope: *Scope,
inst: *zir.Inst.UnOp,
) InnerError!*Inst {
const b = try mod.requireFunctionBlock(scope, inst.base.src);
const quota = try resolveAlreadyCoercedInt(mod, scope, inst.positionals.operand, u32);
if (b.branch_quota.* < quota)
b.branch_quota.* = quota;
return mod.constVoid(scope, inst.base.src);
}
fn zirStore(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, inst.positionals.lhs);
const value = try resolveInst(mod, scope, inst.positionals.rhs);
return mod.storePtr(scope, inst.base.src, ptr, value);
}
fn zirParamType(mod: *Module, scope: *Scope, inst: *zir.Inst.ParamType) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const fn_inst = try resolveInst(mod, scope, inst.positionals.func);
const arg_index = inst.positionals.arg_index;
const fn_ty: Type = switch (fn_inst.ty.zigTypeTag()) {
.Fn => fn_inst.ty,
.BoundFn => {
return mod.fail(scope, fn_inst.src, "TODO implement zirParamType for method call syntax", .{});
},
else => {
return mod.fail(scope, fn_inst.src, "expected function, found '{}'", .{fn_inst.ty});
},
};
const param_count = fn_ty.fnParamLen();
if (arg_index >= param_count) {
if (fn_ty.fnIsVarArgs()) {
return mod.constType(scope, inst.base.src, Type.initTag(.var_args_param));
}
return mod.fail(scope, inst.base.src, "arg index {d} out of bounds; '{}' has {d} argument(s)", .{
arg_index,
fn_ty,
param_count,
});
}
// TODO support generic functions
const param_type = fn_ty.fnParamType(arg_index);
return mod.constType(scope, inst.base.src, param_type);
}
fn zirStr(mod: *Module, scope: *Scope, str_inst: *zir.Inst.Str) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// The bytes references memory inside the ZIR module, which can get deallocated
// after semantic analysis is complete. We need the memory to be in the new anonymous Decl's arena.
var new_decl_arena = std.heap.ArenaAllocator.init(mod.gpa);
errdefer new_decl_arena.deinit();
const arena_bytes = try new_decl_arena.allocator.dupe(u8, str_inst.positionals.bytes);
const decl_ty = try Type.Tag.array_u8_sentinel_0.create(&new_decl_arena.allocator, arena_bytes.len);
const decl_val = try Value.Tag.bytes.create(&new_decl_arena.allocator, arena_bytes);
const new_decl = try mod.createAnonymousDecl(scope, &new_decl_arena, .{
.ty = decl_ty,
.val = decl_val,
});
return mod.analyzeDeclRef(scope, str_inst.base.src, new_decl);
}
fn zirInt(mod: *Module, scope: *Scope, inst: *zir.Inst.Int) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.constIntBig(scope, inst.base.src, Type.initTag(.comptime_int), inst.positionals.int);
}
fn zirExport(mod: *Module, scope: *Scope, export_inst: *zir.Inst.Export) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const symbol_name = try resolveConstString(mod, scope, export_inst.positionals.symbol_name);
const exported_decl = mod.lookupDeclName(scope, export_inst.positionals.decl_name) orelse
return mod.fail(scope, export_inst.base.src, "decl '{s}' not found", .{export_inst.positionals.decl_name});
try mod.analyzeExport(scope, export_inst.base.src, symbol_name, exported_decl);
return mod.constVoid(scope, export_inst.base.src);
}
fn zirCompileError(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const msg = try resolveConstString(mod, scope, inst.positionals.operand);
return mod.fail(scope, inst.base.src, "{s}", .{msg});
}
fn zirCompileLog(mod: *Module, scope: *Scope, inst: *zir.Inst.CompileLog) InnerError!*Inst {
var managed = mod.compile_log_text.toManaged(mod.gpa);
defer mod.compile_log_text = managed.moveToUnmanaged();
const writer = managed.writer();
for (inst.positionals.to_log) |arg_inst, i| {
if (i != 0) try writer.print(", ", .{});
const arg = try resolveInst(mod, scope, arg_inst);
if (arg.value()) |val| {
try writer.print("@as({}, {})", .{ arg.ty, val });
} else {
try writer.print("@as({}, [runtime value])", .{arg.ty});
}
}
try writer.print("\n", .{});
const gop = try mod.compile_log_decls.getOrPut(mod.gpa, scope.ownerDecl().?);
if (!gop.found_existing) {
gop.entry.value = .{
.file_scope = scope.getFileScope(),
.byte_offset = inst.base.src,
};
}
return mod.constVoid(scope, inst.base.src);
}
fn zirArg(mod: *Module, scope: *Scope, inst: *zir.Inst.Arg) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const b = try mod.requireFunctionBlock(scope, inst.base.src);
if (b.inlining) |inlining| {
const param_index = inlining.param_index;
inlining.param_index += 1;
return inlining.casted_args[param_index];
}
const fn_ty = b.func.?.owner_decl.typed_value.most_recent.typed_value.ty;
const param_index = b.instructions.items.len;
const param_count = fn_ty.fnParamLen();
if (param_index >= param_count) {
return mod.fail(scope, inst.base.src, "parameter index {d} outside list of length {d}", .{
param_index,
param_count,
});
}
const param_type = fn_ty.fnParamType(param_index);
const name = try scope.arena().dupeZ(u8, inst.positionals.name);
return mod.addArg(b, inst.base.src, param_type, name);
}
fn zirLoop(mod: *Module, scope: *Scope, inst: *zir.Inst.Loop) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const parent_block = scope.cast(Scope.Block).?;
// Reserve space for a Loop instruction so that generated Break instructions can
// point to it, even if it doesn't end up getting used because the code ends up being
// comptime evaluated.
const loop_inst = try parent_block.arena.create(Inst.Loop);
loop_inst.* = .{
.base = .{
.tag = Inst.Loop.base_tag,
.ty = Type.initTag(.noreturn),
.src = inst.base.src,
},
.body = undefined,
};
var child_block: Scope.Block = .{
.parent = parent_block,
.inst_table = parent_block.inst_table,
.func = parent_block.func,
.owner_decl = parent_block.owner_decl,
.src_decl = parent_block.src_decl,
.instructions = .{},
.arena = parent_block.arena,
.inlining = parent_block.inlining,
.is_comptime = parent_block.is_comptime,
.branch_quota = parent_block.branch_quota,
};
defer child_block.instructions.deinit(mod.gpa);
try analyzeBody(mod, &child_block, inst.positionals.body);
// Loop repetition is implied so the last instruction may or may not be a noreturn instruction.
try parent_block.instructions.append(mod.gpa, &loop_inst.base);
loop_inst.body = .{ .instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items) };
return &loop_inst.base;
}
fn zirBlockFlat(mod: *Module, scope: *Scope, inst: *zir.Inst.Block, is_comptime: bool) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const parent_block = scope.cast(Scope.Block).?;
var child_block = parent_block.makeSubBlock();
defer child_block.instructions.deinit(mod.gpa);
child_block.is_comptime = child_block.is_comptime or is_comptime;
try analyzeBody(mod, &child_block, inst.positionals.body);
// Move the analyzed instructions into the parent block arena.
const copied_instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items);
try parent_block.instructions.appendSlice(mod.gpa, copied_instructions);
// The result of a flat block is the last instruction.
const zir_inst_list = inst.positionals.body.instructions;
const last_zir_inst = zir_inst_list[zir_inst_list.len - 1];
return resolveInst(mod, scope, last_zir_inst);
}
fn zirBlock(
mod: *Module,
scope: *Scope,
inst: *zir.Inst.Block,
is_comptime: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const parent_block = scope.cast(Scope.Block).?;
// Reserve space for a Block instruction so that generated Break instructions can
// point to it, even if it doesn't end up getting used because the code ends up being
// comptime evaluated.
const block_inst = try parent_block.arena.create(Inst.Block);
block_inst.* = .{
.base = .{
.tag = Inst.Block.base_tag,
.ty = undefined, // Set after analysis.
.src = inst.base.src,
},
.body = undefined,
};
var child_block: Scope.Block = .{
.parent = parent_block,
.inst_table = parent_block.inst_table,
.func = parent_block.func,
.owner_decl = parent_block.owner_decl,
.src_decl = parent_block.src_decl,
.instructions = .{},
.arena = parent_block.arena,
// TODO @as here is working around a stage1 miscompilation bug :(
.label = @as(?Scope.Block.Label, Scope.Block.Label{
.zir_block = inst,
.merges = .{
.results = .{},
.br_list = .{},
.block_inst = block_inst,
},
}),
.inlining = parent_block.inlining,
.is_comptime = is_comptime or parent_block.is_comptime,
.branch_quota = parent_block.branch_quota,
};
const merges = &child_block.label.?.merges;
defer child_block.instructions.deinit(mod.gpa);
defer merges.results.deinit(mod.gpa);
defer merges.br_list.deinit(mod.gpa);
try analyzeBody(mod, &child_block, inst.positionals.body);
return analyzeBlockBody(mod, scope, &child_block, merges);
}
fn analyzeBlockBody(
mod: *Module,
scope: *Scope,
child_block: *Scope.Block,
merges: *Scope.Block.Merges,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const parent_block = scope.cast(Scope.Block).?;
// Blocks must terminate with noreturn instruction.
assert(child_block.instructions.items.len != 0);
assert(child_block.instructions.items[child_block.instructions.items.len - 1].ty.isNoReturn());
if (merges.results.items.len == 0) {
// No need for a block instruction. We can put the new instructions
// directly into the parent block.
const copied_instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items);
try parent_block.instructions.appendSlice(mod.gpa, copied_instructions);
return copied_instructions[copied_instructions.len - 1];
}
if (merges.results.items.len == 1) {
const last_inst_index = child_block.instructions.items.len - 1;
const last_inst = child_block.instructions.items[last_inst_index];
if (last_inst.breakBlock()) |br_block| {
if (br_block == merges.block_inst) {
// No need for a block instruction. We can put the new instructions directly
// into the parent block. Here we omit the break instruction.
const copied_instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items[0..last_inst_index]);
try parent_block.instructions.appendSlice(mod.gpa, copied_instructions);
return merges.results.items[0];
}
}
}
// It is impossible to have the number of results be > 1 in a comptime scope.
assert(!child_block.is_comptime); // Should already got a compile error in the condbr condition.
// Need to set the type and emit the Block instruction. This allows machine code generation
// to emit a jump instruction to after the block when it encounters the break.
try parent_block.instructions.append(mod.gpa, &merges.block_inst.base);
const resolved_ty = try mod.resolvePeerTypes(scope, merges.results.items);
merges.block_inst.base.ty = resolved_ty;
merges.block_inst.body = .{
.instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items),
};
// Now that the block has its type resolved, we need to go back into all the break
// instructions, and insert type coercion on the operands.
for (merges.br_list.items) |br| {
if (br.operand.ty.eql(resolved_ty)) {
// No type coercion needed.
continue;
}
var coerce_block = parent_block.makeSubBlock();
defer coerce_block.instructions.deinit(mod.gpa);
const coerced_operand = try mod.coerce(&coerce_block.base, resolved_ty, br.operand);
// If no instructions were produced, such as in the case of a coercion of a
// constant value to a new type, we can simply point the br operand to it.
if (coerce_block.instructions.items.len == 0) {
br.operand = coerced_operand;
continue;
}
assert(coerce_block.instructions.items[coerce_block.instructions.items.len - 1] == coerced_operand);
// Here we depend on the br instruction having been over-allocated (if necessary)
// inide analyzeBreak so that it can be converted into a br_block_flat instruction.
const br_src = br.base.src;
const br_ty = br.base.ty;
const br_block_flat = @ptrCast(*Inst.BrBlockFlat, br);
br_block_flat.* = .{
.base = .{
.src = br_src,
.ty = br_ty,
.tag = .br_block_flat,
},
.block = merges.block_inst,
.body = .{
.instructions = try parent_block.arena.dupe(*Inst, coerce_block.instructions.items),
},
};
}
return &merges.block_inst.base;
}
fn zirBreakpoint(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
return mod.addNoOp(b, inst.base.src, Type.initTag(.void), .breakpoint);
}
fn zirBreak(mod: *Module, scope: *Scope, inst: *zir.Inst.Break) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, inst.positionals.operand);
const block = inst.positionals.block;
return analyzeBreak(mod, scope, inst.base.src, block, operand);
}
fn zirBreakVoid(mod: *Module, scope: *Scope, inst: *zir.Inst.BreakVoid) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const block = inst.positionals.block;
const void_inst = try mod.constVoid(scope, inst.base.src);
return analyzeBreak(mod, scope, inst.base.src, block, void_inst);
}
fn analyzeBreak(
mod: *Module,
scope: *Scope,
src: usize,
zir_block: *zir.Inst.Block,
operand: *Inst,
) InnerError!*Inst {
var opt_block = scope.cast(Scope.Block);
while (opt_block) |block| {
if (block.label) |*label| {
if (label.zir_block == zir_block) {
const b = try mod.requireFunctionBlock(scope, src);
// Here we add a br instruction, but we over-allocate a little bit
// (if necessary) to make it possible to convert the instruction into
// a br_block_flat instruction later.
const br = @ptrCast(*Inst.Br, try b.arena.alignedAlloc(
u8,
Inst.convertable_br_align,
Inst.convertable_br_size,
));
br.* = .{
.base = .{
.tag = .br,
.ty = Type.initTag(.noreturn),
.src = src,
},
.operand = operand,
.block = label.merges.block_inst,
};
try b.instructions.append(mod.gpa, &br.base);
try label.merges.results.append(mod.gpa, operand);
try label.merges.br_list.append(mod.gpa, br);
return &br.base;
}
}
opt_block = block.parent;
} else unreachable;
}
fn zirDbgStmt(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
if (scope.cast(Scope.Block)) |b| {
if (!b.is_comptime) {
return mod.addNoOp(b, inst.base.src, Type.initTag(.void), .dbg_stmt);
}
}
return mod.constVoid(scope, inst.base.src);
}
fn zirDeclRefStr(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclRefStr) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const decl_name = try resolveConstString(mod, scope, inst.positionals.name);
return mod.analyzeDeclRefByName(scope, inst.base.src, decl_name);
}
fn zirDeclRef(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclRef) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.analyzeDeclRef(scope, inst.base.src, inst.positionals.decl);
}
fn zirDeclVal(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.analyzeDeclVal(scope, inst.base.src, inst.positionals.decl);
}
fn zirCall(mod: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const func = try resolveInst(mod, scope, inst.positionals.func);
if (func.ty.zigTypeTag() != .Fn)
return mod.fail(scope, inst.positionals.func.src, "type '{}' not a function", .{func.ty});
const cc = func.ty.fnCallingConvention();
if (cc == .Naked) {
// TODO add error note: declared here
return mod.fail(
scope,
inst.positionals.func.src,
"unable to call function with naked calling convention",
.{},
);
}
const call_params_len = inst.positionals.args.len;
const fn_params_len = func.ty.fnParamLen();
if (func.ty.fnIsVarArgs()) {
assert(cc == .C);
if (call_params_len < fn_params_len) {
// TODO add error note: declared here
return mod.fail(
scope,
inst.positionals.func.src,
"expected at least {d} argument(s), found {d}",
.{ fn_params_len, call_params_len },
);
}
} else if (fn_params_len != call_params_len) {
// TODO add error note: declared here
return mod.fail(
scope,
inst.positionals.func.src,
"expected {d} argument(s), found {d}",
.{ fn_params_len, call_params_len },
);
}
if (inst.positionals.modifier == .compile_time) {
return mod.fail(scope, inst.base.src, "TODO implement comptime function calls", .{});
}
if (inst.positionals.modifier != .auto) {
return mod.fail(scope, inst.base.src, "TODO implement call with modifier {}", .{inst.positionals.modifier});
}
// TODO handle function calls of generic functions
const casted_args = try scope.arena().alloc(*Inst, call_params_len);
for (inst.positionals.args) |src_arg, i| {
// the args are already casted to the result of a param type instruction.
casted_args[i] = try resolveInst(mod, scope, src_arg);
}
const ret_type = func.ty.fnReturnType();
const b = try mod.requireFunctionBlock(scope, inst.base.src);
const is_comptime_call = b.is_comptime or inst.positionals.modifier == .compile_time;
const is_inline_call = is_comptime_call or inst.positionals.modifier == .always_inline or
func.ty.fnCallingConvention() == .Inline;
if (is_inline_call) {
const func_val = try mod.resolveConstValue(scope, func);
const module_fn = switch (func_val.tag()) {
.function => func_val.castTag(.function).?.data,
.extern_fn => return mod.fail(scope, inst.base.src, "{s} call of extern function", .{
@as([]const u8, if (is_comptime_call) "comptime" else "inline"),
}),
else => unreachable,
};
// Analyze the ZIR. The same ZIR gets analyzed into a runtime function
// or an inlined call depending on what union tag the `label` field is
// set to in the `Scope.Block`.
// This block instruction will be used to capture the return value from the
// inlined function.
const block_inst = try scope.arena().create(Inst.Block);
block_inst.* = .{
.base = .{
.tag = Inst.Block.base_tag,
.ty = ret_type,
.src = inst.base.src,
},
.body = undefined,
};
// If this is the top of the inline/comptime call stack, we use this data.
// Otherwise we pass on the shared data from the parent scope.
var shared_inlining = Scope.Block.Inlining.Shared{
.branch_count = 0,
.caller = b.func,
};
// This one is shared among sub-blocks within the same callee, but not
// shared among the entire inline/comptime call stack.
var inlining = Scope.Block.Inlining{
.shared = if (b.inlining) |inlining| inlining.shared else &shared_inlining,
.param_index = 0,
.casted_args = casted_args,
.merges = .{
.results = .{},
.br_list = .{},
.block_inst = block_inst,
},
};
var inst_table = Scope.Block.InstTable.init(mod.gpa);
defer inst_table.deinit();
var child_block: Scope.Block = .{
.parent = null,
.inst_table = &inst_table,
.func = module_fn,
.owner_decl = scope.ownerDecl().?,
.src_decl = module_fn.owner_decl,
.instructions = .{},
.arena = scope.arena(),
.label = null,
.inlining = &inlining,
.is_comptime = is_comptime_call,
.branch_quota = b.branch_quota,
};
const merges = &child_block.inlining.?.merges;
defer child_block.instructions.deinit(mod.gpa);
defer merges.results.deinit(mod.gpa);
defer merges.br_list.deinit(mod.gpa);
try mod.emitBackwardBranch(&child_block, inst.base.src);
// This will have return instructions analyzed as break instructions to
// the block_inst above.
try analyzeBody(mod, &child_block, module_fn.zir);
return analyzeBlockBody(mod, scope, &child_block, merges);
}
return mod.addCall(b, inst.base.src, ret_type, func, casted_args);
}
fn zirFn(mod: *Module, scope: *Scope, fn_inst: *zir.Inst.Fn) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const fn_type = try resolveType(mod, scope, fn_inst.positionals.fn_type);
const new_func = try scope.arena().create(Module.Fn);
new_func.* = .{
.state = if (fn_type.fnCallingConvention() == .Inline) .inline_only else .queued,
.zir = fn_inst.positionals.body,
.body = undefined,
.owner_decl = scope.ownerDecl().?,
};
return mod.constInst(scope, fn_inst.base.src, .{
.ty = fn_type,
.val = try Value.Tag.function.create(scope.arena(), new_func),
});
}
fn zirAwait(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
return mod.fail(scope, inst.base.src, "TODO implement await", .{});
}
fn zirResume(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
return mod.fail(scope, inst.base.src, "TODO implement resume", .{});
}
fn zirSuspend(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst {
return mod.fail(scope, inst.base.src, "TODO implement suspend", .{});
}
fn zirSuspendBlock(mod: *Module, scope: *Scope, inst: *zir.Inst.Block) InnerError!*Inst {
return mod.fail(scope, inst.base.src, "TODO implement suspend", .{});
}
fn zirIntType(mod: *Module, scope: *Scope, inttype: *zir.Inst.IntType) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inttype.base.src, "TODO implement inttype", .{});
}
fn zirOptionalType(mod: *Module, scope: *Scope, optional: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const child_type = try resolveType(mod, scope, optional.positionals.operand);
return mod.constType(scope, optional.base.src, try mod.optionalType(scope, child_type));
}
fn zirOptionalTypeFromPtrElem(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, inst.positionals.operand);
const elem_ty = ptr.ty.elemType();
return mod.constType(scope, inst.base.src, try mod.optionalType(scope, elem_ty));
}
fn zirArrayType(mod: *Module, scope: *Scope, array: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// TODO these should be lazily evaluated
const len = try resolveInstConst(mod, scope, array.positionals.lhs);
const elem_type = try resolveType(mod, scope, array.positionals.rhs);
return mod.constType(scope, array.base.src, try mod.arrayType(scope, len.val.toUnsignedInt(), null, elem_type));
}
fn zirArrayTypeSentinel(mod: *Module, scope: *Scope, array: *zir.Inst.ArrayTypeSentinel) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// TODO these should be lazily evaluated
const len = try resolveInstConst(mod, scope, array.positionals.len);
const sentinel = try resolveInstConst(mod, scope, array.positionals.sentinel);
const elem_type = try resolveType(mod, scope, array.positionals.elem_type);
return mod.constType(scope, array.base.src, try mod.arrayType(scope, len.val.toUnsignedInt(), sentinel.val, elem_type));
}
fn zirErrorUnionType(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const error_union = try resolveType(mod, scope, inst.positionals.lhs);
const payload = try resolveType(mod, scope, inst.positionals.rhs);
if (error_union.zigTypeTag() != .ErrorSet) {
return mod.fail(scope, inst.base.src, "expected error set type, found {}", .{error_union.elemType()});
}
return mod.constType(scope, inst.base.src, try mod.errorUnionType(scope, error_union, payload));
}
fn zirAnyframeType(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const return_type = try resolveType(mod, scope, inst.positionals.operand);
return mod.constType(scope, inst.base.src, try mod.anyframeType(scope, return_type));
}
fn zirErrorSet(mod: *Module, scope: *Scope, inst: *zir.Inst.ErrorSet) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// The declarations arena will store the hashmap.
var new_decl_arena = std.heap.ArenaAllocator.init(mod.gpa);
errdefer new_decl_arena.deinit();
const payload = try new_decl_arena.allocator.create(Value.Payload.ErrorSet);
payload.* = .{
.base = .{ .tag = .error_set },
.data = .{
.fields = .{},
.decl = undefined, // populated below
},
};
try payload.data.fields.ensureCapacity(&new_decl_arena.allocator, @intCast(u32, inst.positionals.fields.len));
for (inst.positionals.fields) |field_name| {
const entry = try mod.getErrorValue(field_name);
if (payload.data.fields.fetchPutAssumeCapacity(entry.key, {})) |_| {
return mod.fail(scope, inst.base.src, "duplicate error: '{s}'", .{field_name});
}
}
// TODO create name in format "error:line:column"
const new_decl = try mod.createAnonymousDecl(scope, &new_decl_arena, .{
.ty = Type.initTag(.type),
.val = Value.initPayload(&payload.base),
});
payload.data.decl = new_decl;
return mod.analyzeDeclVal(scope, inst.base.src, new_decl);
}
fn zirErrorValue(mod: *Module, scope: *Scope, inst: *zir.Inst.ErrorValue) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// Create an anonymous error set type with only this error value, and return the value.
const entry = try mod.getErrorValue(inst.positionals.name);
const result_type = try Type.Tag.error_set_single.create(scope.arena(), entry.key);
return mod.constInst(scope, inst.base.src, .{
.ty = result_type,
.val = try Value.Tag.@"error".create(scope.arena(), .{
.name = entry.key,
}),
});
}
fn zirMergeErrorSets(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const rhs_ty = try resolveType(mod, scope, inst.positionals.rhs);
const lhs_ty = try resolveType(mod, scope, inst.positionals.lhs);
if (rhs_ty.zigTypeTag() != .ErrorSet)
return mod.fail(scope, inst.positionals.rhs.src, "expected error set type, found {}", .{rhs_ty});
if (lhs_ty.zigTypeTag() != .ErrorSet)
return mod.fail(scope, inst.positionals.lhs.src, "expected error set type, found {}", .{lhs_ty});
// anything merged with anyerror is anyerror
if (lhs_ty.tag() == .anyerror or rhs_ty.tag() == .anyerror)
return mod.constInst(scope, inst.base.src, .{
.ty = Type.initTag(.type),
.val = Value.initTag(.anyerror_type),
});
// The declarations arena will store the hashmap.
var new_decl_arena = std.heap.ArenaAllocator.init(mod.gpa);
errdefer new_decl_arena.deinit();
const payload = try new_decl_arena.allocator.create(Value.Payload.ErrorSet);
payload.* = .{
.base = .{ .tag = .error_set },
.data = .{
.fields = .{},
.decl = undefined, // populated below
},
};
try payload.data.fields.ensureCapacity(&new_decl_arena.allocator, @intCast(u32, switch (rhs_ty.tag()) {
.error_set_single => 1,
.error_set => rhs_ty.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields.size,
else => unreachable,
} + switch (lhs_ty.tag()) {
.error_set_single => 1,
.error_set => lhs_ty.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields.size,
else => unreachable,
}));
switch (lhs_ty.tag()) {
.error_set_single => {
const name = lhs_ty.castTag(.error_set_single).?.data;
payload.data.fields.putAssumeCapacity(name, {});
},
.error_set => {
var multiple = lhs_ty.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields;
var it = multiple.iterator();
while (it.next()) |entry| {
payload.data.fields.putAssumeCapacity(entry.key, entry.value);
}
},
else => unreachable,
}
switch (rhs_ty.tag()) {
.error_set_single => {
const name = rhs_ty.castTag(.error_set_single).?.data;
payload.data.fields.putAssumeCapacity(name, {});
},
.error_set => {
var multiple = rhs_ty.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields;
var it = multiple.iterator();
while (it.next()) |entry| {
payload.data.fields.putAssumeCapacity(entry.key, entry.value);
}
},
else => unreachable,
}
// TODO create name in format "error:line:column"
const new_decl = try mod.createAnonymousDecl(scope, &new_decl_arena, .{
.ty = Type.initTag(.type),
.val = Value.initPayload(&payload.base),
});
payload.data.decl = new_decl;
return mod.analyzeDeclVal(scope, inst.base.src, new_decl);
}
fn zirEnumLiteral(mod: *Module, scope: *Scope, inst: *zir.Inst.EnumLiteral) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const duped_name = try scope.arena().dupe(u8, inst.positionals.name);
return mod.constInst(scope, inst.base.src, .{
.ty = Type.initTag(.enum_literal),
.val = try Value.Tag.enum_literal.create(scope.arena(), duped_name),
});
}
/// Pointer in, pointer out.
fn zirOptionalPayloadPtr(
mod: *Module,
scope: *Scope,
unwrap: *zir.Inst.UnOp,
safety_check: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const optional_ptr = try resolveInst(mod, scope, unwrap.positionals.operand);
assert(optional_ptr.ty.zigTypeTag() == .Pointer);
const opt_type = optional_ptr.ty.elemType();
if (opt_type.zigTypeTag() != .Optional) {
return mod.fail(scope, unwrap.base.src, "expected optional type, found {}", .{opt_type});
}
const child_type = try opt_type.optionalChildAlloc(scope.arena());
const child_pointer = try mod.simplePtrType(scope, unwrap.base.src, child_type, !optional_ptr.ty.isConstPtr(), .One);
if (optional_ptr.value()) |pointer_val| {
const val = try pointer_val.pointerDeref(scope.arena());
if (val.isNull()) {
return mod.fail(scope, unwrap.base.src, "unable to unwrap null", .{});
}
// The same Value represents the pointer to the optional and the payload.
return mod.constInst(scope, unwrap.base.src, .{
.ty = child_pointer,
.val = pointer_val,
});
}
const b = try mod.requireRuntimeBlock(scope, unwrap.base.src);
if (safety_check and mod.wantSafety(scope)) {
const is_non_null = try mod.addUnOp(b, unwrap.base.src, Type.initTag(.bool), .is_non_null_ptr, optional_ptr);
try mod.addSafetyCheck(b, is_non_null, .unwrap_null);
}
return mod.addUnOp(b, unwrap.base.src, child_pointer, .optional_payload_ptr, optional_ptr);
}
/// Value in, value out.
fn zirOptionalPayload(
mod: *Module,
scope: *Scope,
unwrap: *zir.Inst.UnOp,
safety_check: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, unwrap.positionals.operand);
const opt_type = operand.ty;
if (opt_type.zigTypeTag() != .Optional) {
return mod.fail(scope, unwrap.base.src, "expected optional type, found {}", .{opt_type});
}
const child_type = try opt_type.optionalChildAlloc(scope.arena());
if (operand.value()) |val| {
if (val.isNull()) {
return mod.fail(scope, unwrap.base.src, "unable to unwrap null", .{});
}
return mod.constInst(scope, unwrap.base.src, .{
.ty = child_type,
.val = val,
});
}
const b = try mod.requireRuntimeBlock(scope, unwrap.base.src);
if (safety_check and mod.wantSafety(scope)) {
const is_non_null = try mod.addUnOp(b, unwrap.base.src, Type.initTag(.bool), .is_non_null, operand);
try mod.addSafetyCheck(b, is_non_null, .unwrap_null);
}
return mod.addUnOp(b, unwrap.base.src, child_type, .optional_payload, operand);
}
/// Value in, value out
fn zirErrUnionPayload(mod: *Module, scope: *Scope, unwrap: *zir.Inst.UnOp, safety_check: bool) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, unwrap.positionals.operand);
if (operand.ty.zigTypeTag() != .ErrorUnion)
return mod.fail(scope, operand.src, "expected error union type, found '{}'", .{operand.ty});
if (operand.value()) |val| {
if (val.getError()) |name| {
return mod.fail(scope, unwrap.base.src, "caught unexpected error '{s}'", .{name});
}
const data = val.castTag(.error_union).?.data;
return mod.constInst(scope, unwrap.base.src, .{
.ty = operand.ty.castTag(.error_union).?.data.payload,
.val = data,
});
}
const b = try mod.requireRuntimeBlock(scope, unwrap.base.src);
if (safety_check and mod.wantSafety(scope)) {
const is_non_err = try mod.addUnOp(b, unwrap.base.src, Type.initTag(.bool), .is_err, operand);
try mod.addSafetyCheck(b, is_non_err, .unwrap_errunion);
}
return mod.addUnOp(b, unwrap.base.src, operand.ty.castTag(.error_union).?.data.payload, .unwrap_errunion_payload, operand);
}
/// Pointer in, pointer out
fn zirErrUnionPayloadPtr(mod: *Module, scope: *Scope, unwrap: *zir.Inst.UnOp, safety_check: bool) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, unwrap.positionals.operand);
assert(operand.ty.zigTypeTag() == .Pointer);
if (operand.ty.elemType().zigTypeTag() != .ErrorUnion)
return mod.fail(scope, unwrap.base.src, "expected error union type, found {}", .{operand.ty.elemType()});
const operand_pointer_ty = try mod.simplePtrType(scope, unwrap.base.src, operand.ty.elemType().castTag(.error_union).?.data.payload, !operand.ty.isConstPtr(), .One);
if (operand.value()) |pointer_val| {
const val = try pointer_val.pointerDeref(scope.arena());
if (val.getError()) |name| {
return mod.fail(scope, unwrap.base.src, "caught unexpected error '{s}'", .{name});
}
const data = val.castTag(.error_union).?.data;
// The same Value represents the pointer to the error union and the payload.
return mod.constInst(scope, unwrap.base.src, .{
.ty = operand_pointer_ty,
.val = try Value.Tag.ref_val.create(
scope.arena(),
data,
),
});
}
const b = try mod.requireRuntimeBlock(scope, unwrap.base.src);
if (safety_check and mod.wantSafety(scope)) {
const is_non_err = try mod.addUnOp(b, unwrap.base.src, Type.initTag(.bool), .is_err, operand);
try mod.addSafetyCheck(b, is_non_err, .unwrap_errunion);
}
return mod.addUnOp(b, unwrap.base.src, operand_pointer_ty, .unwrap_errunion_payload_ptr, operand);
}
/// Value in, value out
fn zirErrUnionCode(mod: *Module, scope: *Scope, unwrap: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, unwrap.positionals.operand);
if (operand.ty.zigTypeTag() != .ErrorUnion)
return mod.fail(scope, unwrap.base.src, "expected error union type, found '{}'", .{operand.ty});
if (operand.value()) |val| {
assert(val.getError() != null);
const data = val.castTag(.error_union).?.data;
return mod.constInst(scope, unwrap.base.src, .{
.ty = operand.ty.castTag(.error_union).?.data.error_set,
.val = data,
});
}
const b = try mod.requireRuntimeBlock(scope, unwrap.base.src);
return mod.addUnOp(b, unwrap.base.src, operand.ty.castTag(.error_union).?.data.payload, .unwrap_errunion_err, operand);
}
/// Pointer in, value out
fn zirErrUnionCodePtr(mod: *Module, scope: *Scope, unwrap: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, unwrap.positionals.operand);
assert(operand.ty.zigTypeTag() == .Pointer);
if (operand.ty.elemType().zigTypeTag() != .ErrorUnion)
return mod.fail(scope, unwrap.base.src, "expected error union type, found {}", .{operand.ty.elemType()});
if (operand.value()) |pointer_val| {
const val = try pointer_val.pointerDeref(scope.arena());
assert(val.getError() != null);
const data = val.castTag(.error_union).?.data;
return mod.constInst(scope, unwrap.base.src, .{
.ty = operand.ty.elemType().castTag(.error_union).?.data.error_set,
.val = data,
});
}
const b = try mod.requireRuntimeBlock(scope, unwrap.base.src);
return mod.addUnOp(b, unwrap.base.src, operand.ty.castTag(.error_union).?.data.payload, .unwrap_errunion_err_ptr, operand);
}
fn zirEnsureErrPayloadVoid(mod: *Module, scope: *Scope, unwrap: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, unwrap.positionals.operand);
if (operand.ty.zigTypeTag() != .ErrorUnion)
return mod.fail(scope, unwrap.base.src, "expected error union type, found '{}'", .{operand.ty});
if (operand.ty.castTag(.error_union).?.data.payload.zigTypeTag() != .Void) {
return mod.fail(scope, unwrap.base.src, "expression value is ignored", .{});
}
return mod.constVoid(scope, unwrap.base.src);
}
fn zirFnType(mod: *Module, scope: *Scope, fntype: *zir.Inst.FnType, var_args: bool) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return fnTypeCommon(
mod,
scope,
&fntype.base,
fntype.positionals.param_types,
fntype.positionals.return_type,
.Unspecified,
var_args,
);
}
fn zirFnTypeCc(mod: *Module, scope: *Scope, fntype: *zir.Inst.FnTypeCc, var_args: bool) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const cc_tv = try resolveInstConst(mod, scope, fntype.positionals.cc);
// TODO once we're capable of importing and analyzing decls from
// std.builtin, this needs to change
const cc_str = cc_tv.val.castTag(.enum_literal).?.data;
const cc = std.meta.stringToEnum(std.builtin.CallingConvention, cc_str) orelse
return mod.fail(scope, fntype.positionals.cc.src, "Unknown calling convention {s}", .{cc_str});
return fnTypeCommon(
mod,
scope,
&fntype.base,
fntype.positionals.param_types,
fntype.positionals.return_type,
cc,
var_args,
);
}
fn fnTypeCommon(
mod: *Module,
scope: *Scope,
zir_inst: *zir.Inst,
zir_param_types: []*zir.Inst,
zir_return_type: *zir.Inst,
cc: std.builtin.CallingConvention,
var_args: bool,
) InnerError!*Inst {
const return_type = try resolveType(mod, scope, zir_return_type);
// Hot path for some common function types.
if (zir_param_types.len == 0 and !var_args) {
if (return_type.zigTypeTag() == .NoReturn and cc == .Unspecified) {
return mod.constType(scope, zir_inst.src, Type.initTag(.fn_noreturn_no_args));
}
if (return_type.zigTypeTag() == .Void and cc == .Unspecified) {
return mod.constType(scope, zir_inst.src, Type.initTag(.fn_void_no_args));
}
if (return_type.zigTypeTag() == .NoReturn and cc == .Naked) {
return mod.constType(scope, zir_inst.src, Type.initTag(.fn_naked_noreturn_no_args));
}
if (return_type.zigTypeTag() == .Void and cc == .C) {
return mod.constType(scope, zir_inst.src, Type.initTag(.fn_ccc_void_no_args));
}
}
const arena = scope.arena();
const param_types = try arena.alloc(Type, zir_param_types.len);
for (zir_param_types) |param_type, i| {
const resolved = try resolveType(mod, scope, param_type);
// TODO skip for comptime params
if (!resolved.isValidVarType(false)) {
return mod.fail(scope, param_type.src, "parameter of type '{}' must be declared comptime", .{resolved});
}
param_types[i] = resolved;
}
const fn_ty = try Type.Tag.function.create(arena, .{
.param_types = param_types,
.return_type = return_type,
.cc = cc,
.is_var_args = var_args,
});
return mod.constType(scope, zir_inst.src, fn_ty);
}
fn zirPrimitive(mod: *Module, scope: *Scope, primitive: *zir.Inst.Primitive) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.constInst(scope, primitive.base.src, primitive.positionals.tag.toTypedValue());
}
fn zirAs(mod: *Module, scope: *Scope, as: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const dest_type = try resolveType(mod, scope, as.positionals.lhs);
const new_inst = try resolveInst(mod, scope, as.positionals.rhs);
return mod.coerce(scope, dest_type, new_inst);
}
fn zirPtrtoint(mod: *Module, scope: *Scope, ptrtoint: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, ptrtoint.positionals.operand);
if (ptr.ty.zigTypeTag() != .Pointer) {
return mod.fail(scope, ptrtoint.positionals.operand.src, "expected pointer, found '{}'", .{ptr.ty});
}
// TODO handle known-pointer-address
const b = try mod.requireRuntimeBlock(scope, ptrtoint.base.src);
const ty = Type.initTag(.usize);
return mod.addUnOp(b, ptrtoint.base.src, ty, .ptrtoint, ptr);
}
fn zirFieldVal(mod: *Module, scope: *Scope, inst: *zir.Inst.Field) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const object = try resolveInst(mod, scope, inst.positionals.object);
const field_name = inst.positionals.field_name;
const object_ptr = try mod.analyzeRef(scope, inst.base.src, object);
const result_ptr = try mod.namedFieldPtr(scope, inst.base.src, object_ptr, field_name, inst.base.src);
return mod.analyzeDeref(scope, inst.base.src, result_ptr, result_ptr.src);
}
fn zirFieldPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.Field) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const object_ptr = try resolveInst(mod, scope, inst.positionals.object);
const field_name = inst.positionals.field_name;
return mod.namedFieldPtr(scope, inst.base.src, object_ptr, field_name, inst.base.src);
}
fn zirFieldValNamed(mod: *Module, scope: *Scope, inst: *zir.Inst.FieldNamed) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const object = try resolveInst(mod, scope, inst.positionals.object);
const field_name = try resolveConstString(mod, scope, inst.positionals.field_name);
const fsrc = inst.positionals.field_name.src;
const object_ptr = try mod.analyzeRef(scope, inst.base.src, object);
const result_ptr = try mod.namedFieldPtr(scope, inst.base.src, object_ptr, field_name, fsrc);
return mod.analyzeDeref(scope, inst.base.src, result_ptr, result_ptr.src);
}
fn zirFieldPtrNamed(mod: *Module, scope: *Scope, inst: *zir.Inst.FieldNamed) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const object_ptr = try resolveInst(mod, scope, inst.positionals.object);
const field_name = try resolveConstString(mod, scope, inst.positionals.field_name);
const fsrc = inst.positionals.field_name.src;
return mod.namedFieldPtr(scope, inst.base.src, object_ptr, field_name, fsrc);
}
fn zirIntcast(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const dest_type = try resolveType(mod, scope, inst.positionals.lhs);
const operand = try resolveInst(mod, scope, inst.positionals.rhs);
const dest_is_comptime_int = switch (dest_type.zigTypeTag()) {
.ComptimeInt => true,
.Int => false,
else => return mod.fail(
scope,
inst.positionals.lhs.src,
"expected integer type, found '{}'",
.{
dest_type,
},
),
};
switch (operand.ty.zigTypeTag()) {
.ComptimeInt, .Int => {},
else => return mod.fail(
scope,
inst.positionals.rhs.src,
"expected integer type, found '{}'",
.{operand.ty},
),
}
if (operand.value() != null) {
return mod.coerce(scope, dest_type, operand);
} else if (dest_is_comptime_int) {
return mod.fail(scope, inst.base.src, "unable to cast runtime value to 'comptime_int'", .{});
}
return mod.fail(scope, inst.base.src, "TODO implement analyze widen or shorten int", .{});
}
fn zirBitcast(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const dest_type = try resolveType(mod, scope, inst.positionals.lhs);
const operand = try resolveInst(mod, scope, inst.positionals.rhs);
return mod.bitcast(scope, dest_type, operand);
}
fn zirFloatcast(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const dest_type = try resolveType(mod, scope, inst.positionals.lhs);
const operand = try resolveInst(mod, scope, inst.positionals.rhs);
const dest_is_comptime_float = switch (dest_type.zigTypeTag()) {
.ComptimeFloat => true,
.Float => false,
else => return mod.fail(
scope,
inst.positionals.lhs.src,
"expected float type, found '{}'",
.{
dest_type,
},
),
};
switch (operand.ty.zigTypeTag()) {
.ComptimeFloat, .Float, .ComptimeInt => {},
else => return mod.fail(
scope,
inst.positionals.rhs.src,
"expected float type, found '{}'",
.{operand.ty},
),
}
if (operand.value() != null) {
return mod.coerce(scope, dest_type, operand);
} else if (dest_is_comptime_float) {
return mod.fail(scope, inst.base.src, "unable to cast runtime value to 'comptime_float'", .{});
}
return mod.fail(scope, inst.base.src, "TODO implement analyze widen or shorten float", .{});
}
fn zirElemVal(mod: *Module, scope: *Scope, inst: *zir.Inst.Elem) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const array = try resolveInst(mod, scope, inst.positionals.array);
const array_ptr = try mod.analyzeRef(scope, inst.base.src, array);
const elem_index = try resolveInst(mod, scope, inst.positionals.index);
const result_ptr = try mod.elemPtr(scope, inst.base.src, array_ptr, elem_index);
return mod.analyzeDeref(scope, inst.base.src, result_ptr, result_ptr.src);
}
fn zirElemPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.Elem) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const array_ptr = try resolveInst(mod, scope, inst.positionals.array);
const elem_index = try resolveInst(mod, scope, inst.positionals.index);
return mod.elemPtr(scope, inst.base.src, array_ptr, elem_index);
}
fn zirSlice(mod: *Module, scope: *Scope, inst: *zir.Inst.Slice) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const array_ptr = try resolveInst(mod, scope, inst.positionals.array_ptr);
const start = try resolveInst(mod, scope, inst.positionals.start);
const end = if (inst.kw_args.end) |end| try resolveInst(mod, scope, end) else null;
const sentinel = if (inst.kw_args.sentinel) |sentinel| try resolveInst(mod, scope, sentinel) else null;
return mod.analyzeSlice(scope, inst.base.src, array_ptr, start, end, sentinel);
}
fn zirSliceStart(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const array_ptr = try resolveInst(mod, scope, inst.positionals.lhs);
const start = try resolveInst(mod, scope, inst.positionals.rhs);
return mod.analyzeSlice(scope, inst.base.src, array_ptr, start, null, null);
}
fn zirSwitchRange(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const start = try resolveInst(mod, scope, inst.positionals.lhs);
const end = try resolveInst(mod, scope, inst.positionals.rhs);
switch (start.ty.zigTypeTag()) {
.Int, .ComptimeInt => {},
else => return mod.constVoid(scope, inst.base.src),
}
switch (end.ty.zigTypeTag()) {
.Int, .ComptimeInt => {},
else => return mod.constVoid(scope, inst.base.src),
}
// .switch_range must be inside a comptime scope
const start_val = start.value().?;
const end_val = end.value().?;
if (start_val.compare(.gte, end_val)) {
return mod.fail(scope, inst.base.src, "range start value must be smaller than the end value", .{});
}
return mod.constVoid(scope, inst.base.src);
}
fn zirSwitchBr(mod: *Module, scope: *Scope, inst: *zir.Inst.SwitchBr, ref: bool) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const target_ptr = try resolveInst(mod, scope, inst.positionals.target);
const target = if (ref)
try mod.analyzeDeref(scope, inst.base.src, target_ptr, inst.positionals.target.src)
else
target_ptr;
try validateSwitch(mod, scope, target, inst);
if (try mod.resolveDefinedValue(scope, target)) |target_val| {
for (inst.positionals.cases) |case| {
const resolved = try resolveInst(mod, scope, case.item);
const casted = try mod.coerce(scope, target.ty, resolved);
const item = try mod.resolveConstValue(scope, casted);
if (target_val.eql(item)) {
try analyzeBody(mod, scope.cast(Scope.Block).?, case.body);
return mod.constNoReturn(scope, inst.base.src);
}
}
try analyzeBody(mod, scope.cast(Scope.Block).?, inst.positionals.else_body);
return mod.constNoReturn(scope, inst.base.src);
}
if (inst.positionals.cases.len == 0) {
// no cases just analyze else_branch
try analyzeBody(mod, scope.cast(Scope.Block).?, inst.positionals.else_body);
return mod.constNoReturn(scope, inst.base.src);
}
const parent_block = try mod.requireRuntimeBlock(scope, inst.base.src);
const cases = try parent_block.arena.alloc(Inst.SwitchBr.Case, inst.positionals.cases.len);
var case_block: Scope.Block = .{
.parent = parent_block,
.inst_table = parent_block.inst_table,
.func = parent_block.func,
.owner_decl = parent_block.owner_decl,
.src_decl = parent_block.src_decl,
.instructions = .{},
.arena = parent_block.arena,
.inlining = parent_block.inlining,
.is_comptime = parent_block.is_comptime,
.branch_quota = parent_block.branch_quota,
};
defer case_block.instructions.deinit(mod.gpa);
for (inst.positionals.cases) |case, i| {
// Reset without freeing.
case_block.instructions.items.len = 0;
const resolved = try resolveInst(mod, scope, case.item);
const casted = try mod.coerce(scope, target.ty, resolved);
const item = try mod.resolveConstValue(scope, casted);
try analyzeBody(mod, &case_block, case.body);
cases[i] = .{
.item = item,
.body = .{ .instructions = try parent_block.arena.dupe(*Inst, case_block.instructions.items) },
};
}
case_block.instructions.items.len = 0;
try analyzeBody(mod, &case_block, inst.positionals.else_body);
const else_body: ir.Body = .{
.instructions = try parent_block.arena.dupe(*Inst, case_block.instructions.items),
};
return mod.addSwitchBr(parent_block, inst.base.src, target, cases, else_body);
}
fn validateSwitch(mod: *Module, scope: *Scope, target: *Inst, inst: *zir.Inst.SwitchBr) InnerError!void {
// validate usage of '_' prongs
if (inst.positionals.special_prong == .underscore and target.ty.zigTypeTag() != .Enum) {
return mod.fail(scope, inst.base.src, "'_' prong only allowed when switching on non-exhaustive enums", .{});
// TODO notes "'_' prong here" inst.positionals.cases[last].src
}
// check that target type supports ranges
if (inst.positionals.range) |range_inst| {
switch (target.ty.zigTypeTag()) {
.Int, .ComptimeInt => {},
else => {
return mod.fail(scope, target.src, "ranges not allowed when switching on type {}", .{target.ty});
// TODO notes "range used here" range_inst.src
},
}
}
// validate for duplicate items/missing else prong
switch (target.ty.zigTypeTag()) {
.Enum => return mod.fail(scope, inst.base.src, "TODO validateSwitch .Enum", .{}),
.ErrorSet => return mod.fail(scope, inst.base.src, "TODO validateSwitch .ErrorSet", .{}),
.Union => return mod.fail(scope, inst.base.src, "TODO validateSwitch .Union", .{}),
.Int, .ComptimeInt => {
var range_set = @import("RangeSet.zig").init(mod.gpa);
defer range_set.deinit();
for (inst.positionals.items) |item| {
const maybe_src = if (item.castTag(.switch_range)) |range| blk: {
const start_resolved = try resolveInst(mod, scope, range.positionals.lhs);
const start_casted = try mod.coerce(scope, target.ty, start_resolved);
const end_resolved = try resolveInst(mod, scope, range.positionals.rhs);
const end_casted = try mod.coerce(scope, target.ty, end_resolved);
break :blk try range_set.add(
try mod.resolveConstValue(scope, start_casted),
try mod.resolveConstValue(scope, end_casted),
item.src,
);
} else blk: {
const resolved = try resolveInst(mod, scope, item);
const casted = try mod.coerce(scope, target.ty, resolved);
const value = try mod.resolveConstValue(scope, casted);
break :blk try range_set.add(value, value, item.src);
};
if (maybe_src) |previous_src| {
return mod.fail(scope, item.src, "duplicate switch value", .{});
// TODO notes "previous value is here" previous_src
}
}
if (target.ty.zigTypeTag() == .Int) {
var arena = std.heap.ArenaAllocator.init(mod.gpa);
defer arena.deinit();
const start = try target.ty.minInt(&arena, mod.getTarget());
const end = try target.ty.maxInt(&arena, mod.getTarget());
if (try range_set.spans(start, end)) {
if (inst.positionals.special_prong == .@"else") {
return mod.fail(scope, inst.base.src, "unreachable else prong, all cases already handled", .{});
}
return;
}
}
if (inst.positionals.special_prong != .@"else") {
return mod.fail(scope, inst.base.src, "switch must handle all possibilities", .{});
}
},
.Bool => {
var true_count: u8 = 0;
var false_count: u8 = 0;
for (inst.positionals.items) |item| {
const resolved = try resolveInst(mod, scope, item);
const casted = try mod.coerce(scope, Type.initTag(.bool), resolved);
if ((try mod.resolveConstValue(scope, casted)).toBool()) {
true_count += 1;
} else {
false_count += 1;
}
if (true_count + false_count > 2) {
return mod.fail(scope, item.src, "duplicate switch value", .{});
}
}
if ((true_count + false_count < 2) and inst.positionals.special_prong != .@"else") {
return mod.fail(scope, inst.base.src, "switch must handle all possibilities", .{});
}
if ((true_count + false_count == 2) and inst.positionals.special_prong == .@"else") {
return mod.fail(scope, inst.base.src, "unreachable else prong, all cases already handled", .{});
}
},
.EnumLiteral, .Void, .Fn, .Pointer, .Type => {
if (inst.positionals.special_prong != .@"else") {
return mod.fail(scope, inst.base.src, "else prong required when switching on type '{}'", .{target.ty});
}
var seen_values = std.HashMap(Value, usize, Value.hash, Value.eql, std.hash_map.DefaultMaxLoadPercentage).init(mod.gpa);
defer seen_values.deinit();
for (inst.positionals.items) |item| {
const resolved = try resolveInst(mod, scope, item);
const casted = try mod.coerce(scope, target.ty, resolved);
const val = try mod.resolveConstValue(scope, casted);
if (try seen_values.fetchPut(val, item.src)) |prev| {
return mod.fail(scope, item.src, "duplicate switch value", .{});
// TODO notes "previous value here" prev.value
}
}
},
.ErrorUnion,
.NoReturn,
.Array,
.Struct,
.Undefined,
.Null,
.Optional,
.BoundFn,
.Opaque,
.Vector,
.Frame,
.AnyFrame,
.ComptimeFloat,
.Float,
=> {
return mod.fail(scope, target.src, "invalid switch target type '{}'", .{target.ty});
},
}
}
fn zirImport(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveConstString(mod, scope, inst.positionals.operand);
const file_scope = mod.analyzeImport(scope, inst.base.src, operand) catch |err| switch (err) {
error.ImportOutsidePkgPath => {
return mod.fail(scope, inst.base.src, "import of file outside package path: '{s}'", .{operand});
},
error.FileNotFound => {
return mod.fail(scope, inst.base.src, "unable to find '{s}'", .{operand});
},
else => {
// TODO: make sure this gets retried and not cached
return mod.fail(scope, inst.base.src, "unable to open '{s}': {s}", .{ operand, @errorName(err) });
},
};
return mod.constType(scope, inst.base.src, file_scope.root_container.ty);
}
fn zirShl(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inst.base.src, "TODO implement zirShl", .{});
}
fn zirShr(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inst.base.src, "TODO implement zirShr", .{});
}
fn zirBitwise(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const lhs = try resolveInst(mod, scope, inst.positionals.lhs);
const rhs = try resolveInst(mod, scope, inst.positionals.rhs);
const instructions = &[_]*Inst{ lhs, rhs };
const resolved_type = try mod.resolvePeerTypes(scope, instructions);
const casted_lhs = try mod.coerce(scope, resolved_type, lhs);
const casted_rhs = try mod.coerce(scope, resolved_type, rhs);
const scalar_type = if (resolved_type.zigTypeTag() == .Vector)
resolved_type.elemType()
else
resolved_type;
const scalar_tag = scalar_type.zigTypeTag();
if (lhs.ty.zigTypeTag() == .Vector and rhs.ty.zigTypeTag() == .Vector) {
if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) {
return mod.fail(scope, inst.base.src, "vector length mismatch: {d} and {d}", .{
lhs.ty.arrayLen(),
rhs.ty.arrayLen(),
});
}
return mod.fail(scope, inst.base.src, "TODO implement support for vectors in zirBitwise", .{});
} else if (lhs.ty.zigTypeTag() == .Vector or rhs.ty.zigTypeTag() == .Vector) {
return mod.fail(scope, inst.base.src, "mixed scalar and vector operands to binary expression: '{}' and '{}'", .{
lhs.ty,
rhs.ty,
});
}
const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;
if (!is_int) {
return mod.fail(scope, inst.base.src, "invalid operands to binary bitwise expression: '{s}' and '{s}'", .{ @tagName(lhs.ty.zigTypeTag()), @tagName(rhs.ty.zigTypeTag()) });
}
if (casted_lhs.value()) |lhs_val| {
if (casted_rhs.value()) |rhs_val| {
if (lhs_val.isUndef() or rhs_val.isUndef()) {
return mod.constInst(scope, inst.base.src, .{
.ty = resolved_type,
.val = Value.initTag(.undef),
});
}
return mod.fail(scope, inst.base.src, "TODO implement comptime bitwise operations", .{});
}
}
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
const ir_tag = switch (inst.base.tag) {
.bit_and => Inst.Tag.bit_and,
.bit_or => Inst.Tag.bit_or,
.xor => Inst.Tag.xor,
else => unreachable,
};
return mod.addBinOp(b, inst.base.src, scalar_type, ir_tag, casted_lhs, casted_rhs);
}
fn zirBitNot(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inst.base.src, "TODO implement zirBitNot", .{});
}
fn zirArrayCat(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inst.base.src, "TODO implement zirArrayCat", .{});
}
fn zirArrayMul(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
return mod.fail(scope, inst.base.src, "TODO implement zirArrayMul", .{});
}
fn zirArithmetic(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const lhs = try resolveInst(mod, scope, inst.positionals.lhs);
const rhs = try resolveInst(mod, scope, inst.positionals.rhs);
const instructions = &[_]*Inst{ lhs, rhs };
const resolved_type = try mod.resolvePeerTypes(scope, instructions);
const casted_lhs = try mod.coerce(scope, resolved_type, lhs);
const casted_rhs = try mod.coerce(scope, resolved_type, rhs);
const scalar_type = if (resolved_type.zigTypeTag() == .Vector)
resolved_type.elemType()
else
resolved_type;
const scalar_tag = scalar_type.zigTypeTag();
if (lhs.ty.zigTypeTag() == .Vector and rhs.ty.zigTypeTag() == .Vector) {
if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) {
return mod.fail(scope, inst.base.src, "vector length mismatch: {d} and {d}", .{
lhs.ty.arrayLen(),
rhs.ty.arrayLen(),
});
}
return mod.fail(scope, inst.base.src, "TODO implement support for vectors in zirBinOp", .{});
} else if (lhs.ty.zigTypeTag() == .Vector or rhs.ty.zigTypeTag() == .Vector) {
return mod.fail(scope, inst.base.src, "mixed scalar and vector operands to binary expression: '{}' and '{}'", .{
lhs.ty,
rhs.ty,
});
}
const is_int = scalar_tag == .Int or scalar_tag == .ComptimeInt;
const is_float = scalar_tag == .Float or scalar_tag == .ComptimeFloat;
if (!is_int and !(is_float and floatOpAllowed(inst.base.tag))) {
return mod.fail(scope, inst.base.src, "invalid operands to binary expression: '{s}' and '{s}'", .{ @tagName(lhs.ty.zigTypeTag()), @tagName(rhs.ty.zigTypeTag()) });
}
if (casted_lhs.value()) |lhs_val| {
if (casted_rhs.value()) |rhs_val| {
if (lhs_val.isUndef() or rhs_val.isUndef()) {
return mod.constInst(scope, inst.base.src, .{
.ty = resolved_type,
.val = Value.initTag(.undef),
});
}
return analyzeInstComptimeOp(mod, scope, scalar_type, inst, lhs_val, rhs_val);
}
}
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
const ir_tag = switch (inst.base.tag) {
.add => Inst.Tag.add,
.sub => Inst.Tag.sub,
.mul => Inst.Tag.mul,
else => return mod.fail(scope, inst.base.src, "TODO implement arithmetic for operand '{s}''", .{@tagName(inst.base.tag)}),
};
return mod.addBinOp(b, inst.base.src, scalar_type, ir_tag, casted_lhs, casted_rhs);
}
/// Analyzes operands that are known at comptime
fn analyzeInstComptimeOp(mod: *Module, scope: *Scope, res_type: Type, inst: *zir.Inst.BinOp, lhs_val: Value, rhs_val: Value) InnerError!*Inst {
// incase rhs is 0, simply return lhs without doing any calculations
// TODO Once division is implemented we should throw an error when dividing by 0.
if (rhs_val.compareWithZero(.eq)) {
return mod.constInst(scope, inst.base.src, .{
.ty = res_type,
.val = lhs_val,
});
}
const is_int = res_type.isInt() or res_type.zigTypeTag() == .ComptimeInt;
const value = switch (inst.base.tag) {
.add => blk: {
const val = if (is_int)
try Module.intAdd(scope.arena(), lhs_val, rhs_val)
else
try mod.floatAdd(scope, res_type, inst.base.src, lhs_val, rhs_val);
break :blk val;
},
.sub => blk: {
const val = if (is_int)
try Module.intSub(scope.arena(), lhs_val, rhs_val)
else
try mod.floatSub(scope, res_type, inst.base.src, lhs_val, rhs_val);
break :blk val;
},
else => return mod.fail(scope, inst.base.src, "TODO Implement arithmetic operand '{s}'", .{@tagName(inst.base.tag)}),
};
log.debug("{s}({}, {}) result: {}", .{ @tagName(inst.base.tag), lhs_val, rhs_val, value });
return mod.constInst(scope, inst.base.src, .{
.ty = res_type,
.val = value,
});
}
fn zirDeref(mod: *Module, scope: *Scope, deref: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, deref.positionals.operand);
return mod.analyzeDeref(scope, deref.base.src, ptr, deref.positionals.operand.src);
}
fn zirAsm(mod: *Module, scope: *Scope, assembly: *zir.Inst.Asm) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const return_type = try resolveType(mod, scope, assembly.positionals.return_type);
const asm_source = try resolveConstString(mod, scope, assembly.positionals.asm_source);
const output = if (assembly.kw_args.output) |o| try resolveConstString(mod, scope, o) else null;
const arena = scope.arena();
const inputs = try arena.alloc([]const u8, assembly.kw_args.inputs.len);
const clobbers = try arena.alloc([]const u8, assembly.kw_args.clobbers.len);
const args = try arena.alloc(*Inst, assembly.kw_args.args.len);
for (inputs) |*elem, i| {
elem.* = try arena.dupe(u8, assembly.kw_args.inputs[i]);
}
for (clobbers) |*elem, i| {
elem.* = try arena.dupe(u8, assembly.kw_args.clobbers[i]);
}
for (args) |*elem, i| {
const arg = try resolveInst(mod, scope, assembly.kw_args.args[i]);
elem.* = try mod.coerce(scope, Type.initTag(.usize), arg);
}
const b = try mod.requireRuntimeBlock(scope, assembly.base.src);
const inst = try b.arena.create(Inst.Assembly);
inst.* = .{
.base = .{
.tag = .assembly,
.ty = return_type,
.src = assembly.base.src,
},
.asm_source = asm_source,
.is_volatile = assembly.kw_args.@"volatile",
.output = output,
.inputs = inputs,
.clobbers = clobbers,
.args = args,
};
try b.instructions.append(mod.gpa, &inst.base);
return &inst.base;
}
fn zirCmp(
mod: *Module,
scope: *Scope,
inst: *zir.Inst.BinOp,
op: std.math.CompareOperator,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const lhs = try resolveInst(mod, scope, inst.positionals.lhs);
const rhs = try resolveInst(mod, scope, inst.positionals.rhs);
const is_equality_cmp = switch (op) {
.eq, .neq => true,
else => false,
};
const lhs_ty_tag = lhs.ty.zigTypeTag();
const rhs_ty_tag = rhs.ty.zigTypeTag();
if (is_equality_cmp and lhs_ty_tag == .Null and rhs_ty_tag == .Null) {
// null == null, null != null
return mod.constBool(scope, inst.base.src, op == .eq);
} else if (is_equality_cmp and
((lhs_ty_tag == .Null and rhs_ty_tag == .Optional) or
rhs_ty_tag == .Null and lhs_ty_tag == .Optional))
{
// comparing null with optionals
const opt_operand = if (lhs_ty_tag == .Optional) lhs else rhs;
return mod.analyzeIsNull(scope, inst.base.src, opt_operand, op == .neq);
} else if (is_equality_cmp and
((lhs_ty_tag == .Null and rhs.ty.isCPtr()) or (rhs_ty_tag == .Null and lhs.ty.isCPtr())))
{
return mod.fail(scope, inst.base.src, "TODO implement C pointer cmp", .{});
} else if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) {
const non_null_type = if (lhs_ty_tag == .Null) rhs.ty else lhs.ty;
return mod.fail(scope, inst.base.src, "comparison of '{}' with null", .{non_null_type});
} else if (is_equality_cmp and
((lhs_ty_tag == .EnumLiteral and rhs_ty_tag == .Union) or
(rhs_ty_tag == .EnumLiteral and lhs_ty_tag == .Union)))
{
return mod.fail(scope, inst.base.src, "TODO implement equality comparison between a union's tag value and an enum literal", .{});
} else if (lhs_ty_tag == .ErrorSet and rhs_ty_tag == .ErrorSet) {
if (!is_equality_cmp) {
return mod.fail(scope, inst.base.src, "{s} operator not allowed for errors", .{@tagName(op)});
}
if (rhs.value()) |rval| {
if (lhs.value()) |lval| {
// TODO optimisation oppurtunity: evaluate if std.mem.eql is faster with the names, or calling to Module.getErrorValue to get the values and then compare them is faster
return mod.constBool(scope, inst.base.src, std.mem.eql(u8, lval.castTag(.@"error").?.data.name, rval.castTag(.@"error").?.data.name) == (op == .eq));
}
}
return mod.fail(scope, inst.base.src, "TODO implement equality comparison between runtime errors", .{});
} else if (lhs.ty.isNumeric() and rhs.ty.isNumeric()) {
// This operation allows any combination of integer and float types, regardless of the
// signed-ness, comptime-ness, and bit-width. So peer type resolution is incorrect for
// numeric types.
return mod.cmpNumeric(scope, inst.base.src, lhs, rhs, op);
} else if (lhs_ty_tag == .Type and rhs_ty_tag == .Type) {
if (!is_equality_cmp) {
return mod.fail(scope, inst.base.src, "{s} operator not allowed for types", .{@tagName(op)});
}
return mod.constBool(scope, inst.base.src, lhs.value().?.eql(rhs.value().?) == (op == .eq));
}
return mod.fail(scope, inst.base.src, "TODO implement more cmp analysis", .{});
}
fn zirTypeof(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, inst.positionals.operand);
return mod.constType(scope, inst.base.src, operand.ty);
}
fn zirTypeofPeer(mod: *Module, scope: *Scope, inst: *zir.Inst.TypeOfPeer) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
var insts_to_res = try mod.gpa.alloc(*ir.Inst, inst.positionals.items.len);
defer mod.gpa.free(insts_to_res);
for (inst.positionals.items) |item, i| {
insts_to_res[i] = try resolveInst(mod, scope, item);
}
const pt_res = try mod.resolvePeerTypes(scope, insts_to_res);
return mod.constType(scope, inst.base.src, pt_res);
}
fn zirBoolNot(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const uncasted_operand = try resolveInst(mod, scope, inst.positionals.operand);
const bool_type = Type.initTag(.bool);
const operand = try mod.coerce(scope, bool_type, uncasted_operand);
if (try mod.resolveDefinedValue(scope, operand)) |val| {
return mod.constBool(scope, inst.base.src, !val.toBool());
}
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
return mod.addUnOp(b, inst.base.src, bool_type, .not, operand);
}
fn zirBoolOp(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const bool_type = Type.initTag(.bool);
const uncasted_lhs = try resolveInst(mod, scope, inst.positionals.lhs);
const lhs = try mod.coerce(scope, bool_type, uncasted_lhs);
const uncasted_rhs = try resolveInst(mod, scope, inst.positionals.rhs);
const rhs = try mod.coerce(scope, bool_type, uncasted_rhs);
const is_bool_or = inst.base.tag == .bool_or;
if (lhs.value()) |lhs_val| {
if (rhs.value()) |rhs_val| {
if (is_bool_or) {
return mod.constBool(scope, inst.base.src, lhs_val.toBool() or rhs_val.toBool());
} else {
return mod.constBool(scope, inst.base.src, lhs_val.toBool() and rhs_val.toBool());
}
}
}
const b = try mod.requireRuntimeBlock(scope, inst.base.src);
return mod.addBinOp(b, inst.base.src, bool_type, if (is_bool_or) .bool_or else .bool_and, lhs, rhs);
}
fn zirIsNull(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp, invert_logic: bool) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, inst.positionals.operand);
return mod.analyzeIsNull(scope, inst.base.src, operand, invert_logic);
}
fn zirIsNullPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp, invert_logic: bool) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, inst.positionals.operand);
const loaded = try mod.analyzeDeref(scope, inst.base.src, ptr, ptr.src);
return mod.analyzeIsNull(scope, inst.base.src, loaded, invert_logic);
}
fn zirIsErr(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, inst.positionals.operand);
return mod.analyzeIsErr(scope, inst.base.src, operand);
}
fn zirIsErrPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const ptr = try resolveInst(mod, scope, inst.positionals.operand);
const loaded = try mod.analyzeDeref(scope, inst.base.src, ptr, ptr.src);
return mod.analyzeIsErr(scope, inst.base.src, loaded);
}
fn zirCondbr(mod: *Module, scope: *Scope, inst: *zir.Inst.CondBr) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const uncasted_cond = try resolveInst(mod, scope, inst.positionals.condition);
const cond = try mod.coerce(scope, Type.initTag(.bool), uncasted_cond);
const parent_block = scope.cast(Scope.Block).?;
if (try mod.resolveDefinedValue(scope, cond)) |cond_val| {
const body = if (cond_val.toBool()) &inst.positionals.then_body else &inst.positionals.else_body;
try analyzeBody(mod, parent_block, body.*);
return mod.constNoReturn(scope, inst.base.src);
}
var true_block: Scope.Block = .{
.parent = parent_block,
.inst_table = parent_block.inst_table,
.func = parent_block.func,
.owner_decl = parent_block.owner_decl,
.src_decl = parent_block.src_decl,
.instructions = .{},
.arena = parent_block.arena,
.inlining = parent_block.inlining,
.is_comptime = parent_block.is_comptime,
.branch_quota = parent_block.branch_quota,
};
defer true_block.instructions.deinit(mod.gpa);
try analyzeBody(mod, &true_block, inst.positionals.then_body);
var false_block: Scope.Block = .{
.parent = parent_block,
.inst_table = parent_block.inst_table,
.func = parent_block.func,
.owner_decl = parent_block.owner_decl,
.src_decl = parent_block.src_decl,
.instructions = .{},
.arena = parent_block.arena,
.inlining = parent_block.inlining,
.is_comptime = parent_block.is_comptime,
.branch_quota = parent_block.branch_quota,
};
defer false_block.instructions.deinit(mod.gpa);
try analyzeBody(mod, &false_block, inst.positionals.else_body);
const then_body: ir.Body = .{ .instructions = try scope.arena().dupe(*Inst, true_block.instructions.items) };
const else_body: ir.Body = .{ .instructions = try scope.arena().dupe(*Inst, false_block.instructions.items) };
return mod.addCondBr(parent_block, inst.base.src, cond, then_body, else_body);
}
fn zirUnreachable(
mod: *Module,
scope: *Scope,
unreach: *zir.Inst.NoOp,
safety_check: bool,
) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const b = try mod.requireRuntimeBlock(scope, unreach.base.src);
// TODO Add compile error for @optimizeFor occurring too late in a scope.
if (safety_check and mod.wantSafety(scope)) {
return mod.safetyPanic(b, unreach.base.src, .unreach);
} else {
return mod.addNoOp(b, unreach.base.src, Type.initTag(.noreturn), .unreach);
}
}
fn zirReturn(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const operand = try resolveInst(mod, scope, inst.positionals.operand);
const b = try mod.requireFunctionBlock(scope, inst.base.src);
if (b.inlining) |inlining| {
// We are inlining a function call; rewrite the `ret` as a `break`.
try inlining.merges.results.append(mod.gpa, operand);
const br = try mod.addBr(b, inst.base.src, inlining.merges.block_inst, operand);
return &br.base;
}
return mod.addUnOp(b, inst.base.src, Type.initTag(.noreturn), .ret, operand);
}
fn zirReturnVoid(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const b = try mod.requireFunctionBlock(scope, inst.base.src);
if (b.inlining) |inlining| {
// We are inlining a function call; rewrite the `retvoid` as a `breakvoid`.
const void_inst = try mod.constVoid(scope, inst.base.src);
try inlining.merges.results.append(mod.gpa, void_inst);
const br = try mod.addBr(b, inst.base.src, inlining.merges.block_inst, void_inst);
return &br.base;
}
if (b.func) |func| {
// Need to emit a compile error if returning void is not allowed.
const void_inst = try mod.constVoid(scope, inst.base.src);
const fn_ty = func.owner_decl.typed_value.most_recent.typed_value.ty;
const casted_void = try mod.coerce(scope, fn_ty.fnReturnType(), void_inst);
if (casted_void.ty.zigTypeTag() != .Void) {
return mod.addUnOp(b, inst.base.src, Type.initTag(.noreturn), .ret, casted_void);
}
}
return mod.addNoOp(b, inst.base.src, Type.initTag(.noreturn), .retvoid);
}
fn floatOpAllowed(tag: zir.Inst.Tag) bool {
// extend this swich as additional operators are implemented
return switch (tag) {
.add, .sub => true,
else => false,
};
}
fn zirSimplePtrType(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp, mutable: bool, size: std.builtin.TypeInfo.Pointer.Size) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
const elem_type = try resolveType(mod, scope, inst.positionals.operand);
const ty = try mod.simplePtrType(scope, inst.base.src, elem_type, mutable, size);
return mod.constType(scope, inst.base.src, ty);
}
fn zirPtrType(mod: *Module, scope: *Scope, inst: *zir.Inst.PtrType) InnerError!*Inst {
const tracy = trace(@src());
defer tracy.end();
// TODO lazy values
const @"align" = if (inst.kw_args.@"align") |some|
@truncate(u32, try resolveInt(mod, scope, some, Type.initTag(.u32)))
else
0;
const bit_offset = if (inst.kw_args.align_bit_start) |some|
@truncate(u16, try resolveInt(mod, scope, some, Type.initTag(.u16)))
else
0;
const host_size = if (inst.kw_args.align_bit_end) |some|
@truncate(u16, try resolveInt(mod, scope, some, Type.initTag(.u16)))
else
0;
if (host_size != 0 and bit_offset >= host_size * 8)
return mod.fail(scope, inst.base.src, "bit offset starts after end of host integer", .{});
const sentinel = if (inst.kw_args.sentinel) |some|
(try resolveInstConst(mod, scope, some)).val
else
null;
const elem_type = try resolveType(mod, scope, inst.positionals.child_type);
const ty = try mod.ptrType(
scope,
inst.base.src,
elem_type,
sentinel,
@"align",
bit_offset,
host_size,
inst.kw_args.mutable,
inst.kw_args.@"allowzero",
inst.kw_args.@"volatile",
inst.kw_args.size,
);
return mod.constType(scope, inst.base.src, ty);
}
|
src/zir_sema.zig
|
const std = @import("std");
const mach = @import("mach");
const gpu = @import("gpu");
const zm = @import("zmath");
const zigimg = @import("zigimg");
const glfw = @import("glfw");
const draw = @import("draw.zig");
const Atlas = @import("atlas.zig").Atlas;
const ft = @import("freetype");
const Label = @import("text.zig");
pub const options = mach.Options{ .width = 640, .height = 480 };
pub const App = @This();
const AtlasRGB8 = Atlas(zigimg.color.Rgba32);
pipeline: gpu.RenderPipeline,
queue: gpu.Queue,
vertex_buffer: gpu.Buffer,
vertices: std.ArrayList(draw.Vertex),
update_vertex_buffer: bool,
vertex_uniform_buffer: gpu.Buffer,
update_vertex_uniform_buffer: bool,
frag_uniform_buffer: gpu.Buffer,
fragment_uniform_list: std.ArrayList(draw.FragUniform),
update_frag_uniform_buffer: bool,
bind_group: gpu.BindGroup,
texture_atlas_data: AtlasRGB8,
pub fn init(app: *App, engine: *mach.Engine) !void {
try engine.core.setSizeLimits(.{ .width = 20, .height = 20 }, .{ .width = null, .height = null });
const queue = engine.gpu_driver.device.getQueue();
// TODO: Refactor texture atlas size number
app.texture_atlas_data = try AtlasRGB8.init(engine.allocator, 1280);
const atlas_size = gpu.Extent3D{ .width = app.texture_atlas_data.size, .height = app.texture_atlas_data.size };
const atlas_float_size = @intToFloat(f32, app.texture_atlas_data.size);
const texture = engine.gpu_driver.device.createTexture(&.{
.size = atlas_size,
.format = .rgba8_unorm,
.usage = .{
.texture_binding = true,
.copy_dst = true,
.render_attachment = true,
},
});
const data_layout = gpu.Texture.DataLayout{
.bytes_per_row = @intCast(u32, atlas_size.width * 4),
.rows_per_image = @intCast(u32, atlas_size.height),
};
const img = try zigimg.Image.fromMemory(engine.allocator, @embedFile("../assets/gotta-go-fast.png"));
defer img.deinit();
const atlas_img_region = try app.texture_atlas_data.reserve(engine.allocator, @truncate(u32, img.width), @truncate(u32, img.height));
const img_uv_data = atlas_img_region.getUVData(atlas_float_size);
switch (img.pixels.?) {
.Rgba32 => |pixels| app.texture_atlas_data.set(atlas_img_region, pixels),
.Rgb24 => |pixels| {
const data = try rgb24ToRgba32(engine.allocator, pixels);
defer data.deinit(engine.allocator);
app.texture_atlas_data.set(atlas_img_region, data.Rgba32);
},
else => @panic("unsupported image color format"),
}
const white_tex_scale = 80;
const atlas_white_region = try app.texture_atlas_data.reserve(engine.allocator, white_tex_scale, white_tex_scale);
const white_texture_uv_data = atlas_white_region.getUVData(atlas_float_size);
var white_tex_data = try engine.allocator.alloc(zigimg.color.Rgba32, white_tex_scale * white_tex_scale);
std.mem.set(zigimg.color.Rgba32, white_tex_data, zigimg.color.Rgba32.initRGB(0xff, 0xff, 0xff));
app.texture_atlas_data.set(atlas_white_region, white_tex_data);
app.vertices = try std.ArrayList(draw.Vertex).initCapacity(engine.allocator, 9);
app.fragment_uniform_list = try std.ArrayList(draw.FragUniform).initCapacity(engine.allocator, 3);
// Quick test for using freetype
const lib = try ft.Library.init();
defer lib.deinit();
var label = try Label.init(lib, "freetype/upstream/assets/FiraSans-Regular.ttf", 0, 40, engine.allocator);
defer label.deinit();
try label.print(app, "All your game's bases are belong to us", .{}, @Vector(2, f32){ 0, 420 }, @Vector(4, f32){ 1, 1, 1, 1 });
queue.writeTexture(
&.{ .texture = texture },
&data_layout,
&.{ .width = app.texture_atlas_data.size, .height = app.texture_atlas_data.size },
zigimg.color.Rgba32,
app.texture_atlas_data.data,
);
const wsize = try engine.core.getWindowSize();
const window_width = @intToFloat(f32, wsize.width);
const window_height = @intToFloat(f32, wsize.height);
const triangle_scale = 250;
_ = window_width;
_ = window_height;
_ = triangle_scale;
_ = img_uv_data;
_ = white_texture_uv_data;
// try draw.equilateralTriangle(app, .{ window_width / 2, window_height / 2 }, triangle_scale, .{}, img_uv_data);
// try draw.equilateralTriangle(app, .{ window_width / 2, window_height / 2 - triangle_scale }, triangle_scale, .{ .type = .concave }, img_uv_data);
// try draw.equilateralTriangle(app, .{ window_width / 2 - triangle_scale, window_height / 2 - triangle_scale / 2 }, triangle_scale, .{ .type = .convex }, white_texture_uv_data);
// try draw.quad(app, .{ 0, 0 }, .{ 480, 480 }, .{}, .{ .bottom_left = .{ 0, 0 }, .width_and_height = .{ 1, 1 } });
// try draw.circle(app, .{ window_width / 2, window_height / 2 }, window_height / 2 - 10, .{ 0, 0.5, 0.75, 1.0 }, white_texture_uv_data);
const vs_module = engine.gpu_driver.device.createShaderModule(&.{
.label = "my vertex shader",
.code = .{ .wgsl = @embedFile("vert.wgsl") },
});
const fs_module = engine.gpu_driver.device.createShaderModule(&.{
.label = "my fragment shader",
.code = .{ .wgsl = @embedFile("frag.wgsl") },
});
const blend = gpu.BlendState{
.color = .{
.operation = .add,
.src_factor = .src_alpha,
.dst_factor = .one_minus_src_alpha,
},
.alpha = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .zero,
},
};
const color_target = gpu.ColorTargetState{
.format = engine.gpu_driver.swap_chain_format,
.blend = &blend,
.write_mask = gpu.ColorWriteMask.all,
};
const fragment = gpu.FragmentState{
.module = fs_module,
.entry_point = "main",
.targets = &.{color_target},
.constants = null,
};
const vbgle = gpu.BindGroupLayout.Entry.buffer(0, .{ .vertex = true }, .uniform, true, 0);
const fbgle = gpu.BindGroupLayout.Entry.buffer(1, .{ .fragment = true }, .read_only_storage, true, 0);
const sbgle = gpu.BindGroupLayout.Entry.sampler(2, .{ .fragment = true }, .filtering);
const tbgle = gpu.BindGroupLayout.Entry.texture(3, .{ .fragment = true }, .float, .dimension_2d, false);
const bgl = engine.gpu_driver.device.createBindGroupLayout(
&gpu.BindGroupLayout.Descriptor{
.entries = &.{ vbgle, fbgle, sbgle, tbgle },
},
);
const bind_group_layouts = [_]gpu.BindGroupLayout{bgl};
const pipeline_layout = engine.gpu_driver.device.createPipelineLayout(&.{
.bind_group_layouts = &bind_group_layouts,
});
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
.fragment = &fragment,
.layout = pipeline_layout,
.depth_stencil = null,
.vertex = .{
.module = vs_module,
.entry_point = "main",
.buffers = &.{draw.VERTEX_BUFFER_LAYOUT},
},
.multisample = .{
.count = 1,
.mask = 0xFFFFFFFF,
.alpha_to_coverage_enabled = false,
},
.primitive = .{
.front_face = .ccw,
.cull_mode = .none,
.topology = .triangle_list,
.strip_index_format = .none,
},
};
const vertex_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .copy_dst = true, .vertex = true },
.size = @sizeOf(draw.Vertex) * app.vertices.items.len,
.mapped_at_creation = false,
});
const vertex_uniform_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .copy_dst = true, .uniform = true },
.size = @sizeOf(draw.VertexUniform),
.mapped_at_creation = false,
});
const frag_uniform_buffer = engine.gpu_driver.device.createBuffer(&.{
.usage = .{ .copy_dst = true, .storage = true },
.size = @sizeOf(draw.FragUniform) * app.fragment_uniform_list.items.len,
.mapped_at_creation = false,
});
const sampler = engine.gpu_driver.device.createSampler(&.{
.mag_filter = .linear,
.min_filter = .linear,
});
const bind_group = engine.gpu_driver.device.createBindGroup(
&gpu.BindGroup.Descriptor{
.layout = bgl,
.entries = &.{
gpu.BindGroup.Entry.buffer(0, vertex_uniform_buffer, 0, @sizeOf(draw.VertexUniform)),
gpu.BindGroup.Entry.buffer(1, frag_uniform_buffer, 0, @sizeOf(draw.FragUniform) * app.vertices.items.len / 3),
gpu.BindGroup.Entry.sampler(2, sampler),
gpu.BindGroup.Entry.textureView(3, texture.createView(&gpu.TextureView.Descriptor{ .dimension = .dimension_2d })),
},
},
);
app.pipeline = engine.gpu_driver.device.createRenderPipeline(&pipeline_descriptor);
app.queue = queue;
app.vertex_buffer = vertex_buffer;
app.vertex_uniform_buffer = vertex_uniform_buffer;
app.frag_uniform_buffer = frag_uniform_buffer;
app.bind_group = bind_group;
app.update_vertex_buffer = true;
app.update_vertex_uniform_buffer = true;
app.update_frag_uniform_buffer = true;
vs_module.release();
fs_module.release();
pipeline_layout.release();
bgl.release();
}
pub fn deinit(app: *App, engine: *mach.Engine) void {
app.vertex_buffer.release();
app.vertex_uniform_buffer.release();
app.frag_uniform_buffer.release();
app.bind_group.release();
app.vertices.deinit();
app.fragment_uniform_list.deinit();
app.texture_atlas_data.deinit(engine.allocator);
}
pub fn update(app: *App, engine: *mach.Engine) !bool {
while (engine.core.pollEvent()) |event| {
switch (event) {
.key_press => |ev| {
if (ev.key == .space)
engine.core.setShouldClose(true);
},
else => {},
}
}
const back_buffer_view = engine.gpu_driver.swap_chain.?.getCurrentTextureView();
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.resolve_target = null,
.clear_value = std.mem.zeroes(gpu.Color),
.load_op = .clear,
.store_op = .store,
};
const encoder = engine.gpu_driver.device.createCommandEncoder(null);
const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment},
};
{
if (app.update_vertex_buffer) {
encoder.writeBuffer(app.vertex_buffer, 0, draw.Vertex, app.vertices.items);
app.update_vertex_buffer = false;
}
if (app.update_frag_uniform_buffer) {
encoder.writeBuffer(app.frag_uniform_buffer, 0, draw.FragUniform, app.fragment_uniform_list.items);
app.update_frag_uniform_buffer = false;
}
if (app.update_vertex_uniform_buffer) {
encoder.writeBuffer(app.vertex_uniform_buffer, 0, draw.VertexUniform, &.{try getVertexUniformBufferObject(engine)});
app.update_vertex_uniform_buffer = false;
}
}
const pass = encoder.beginRenderPass(&render_pass_info);
pass.setPipeline(app.pipeline);
pass.setVertexBuffer(0, app.vertex_buffer, 0, @sizeOf(draw.Vertex) * app.vertices.items.len);
pass.setBindGroup(0, app.bind_group, &.{ 0, 0 });
pass.draw(@truncate(u32, app.vertices.items.len), 1, 0, 0);
pass.end();
pass.release();
var command = encoder.finish(null);
encoder.release();
app.queue.submit(&.{command});
command.release();
engine.gpu_driver.swap_chain.?.present();
back_buffer_view.release();
return true;
}
pub fn resize(app: *App, _: *mach.Engine, _: u32, _: u32) !void {
app.update_vertex_uniform_buffer = true;
}
fn rgb24ToRgba32(allocator: std.mem.Allocator, in: []zigimg.color.Rgb24) !zigimg.color.ColorStorage {
const out = try zigimg.color.ColorStorage.init(allocator, .Rgba32, in.len);
var i: usize = 0;
while (i < in.len) : (i += 1) {
out.Rgba32[i] = zigimg.color.Rgba32{ .R = in[i].R, .G = in[i].G, .B = in[i].B, .A = 255 };
}
return out;
}
// Move to draw.zig
pub fn getVertexUniformBufferObject(engine: *mach.Engine) !draw.VertexUniform {
// Note: We use window width/height here, not framebuffer width/height.
// On e.g. macOS, window size may be 640x480 while framebuffer size may be
// 1280x960 (subpixels.) Doing this lets us use a pixel, not subpixel,
// coordinate system.
const window_size = try engine.core.getWindowSize();
const proj = zm.orthographicRh(
@intToFloat(f32, window_size.width),
@intToFloat(f32, window_size.height),
-100,
100,
);
const mvp = zm.mul(proj, zm.translation(-1, -1, 0));
return draw.VertexUniform{
.mat = mvp,
};
}
|
examples/gkurve/main.zig
|
const testing = @import("std").testing;
const Document = @import("xml").Document;
const full = @import("full.zig");
test "encoding to XML" {
var doc = try Document.new();
defer doc.deinit();
var root = try doc.createElement("root");
try doc.appendChild(root);
{
var element1 = try doc.createElement("element1");
try root.appendChild(element1);
try element1.setAttribute("attr1", "hello");
try element1.setAttribute("attr2", "world");
{
var child1 = try doc.createElement("child1");
try element1.appendChild(child1);
var child1_text = try doc.createTextNode("I am required");
try child1.appendChild(child1_text);
}
{
var int_child = try doc.createElement("int-child");
try element1.appendChild(int_child);
var int_child_text = try doc.createTextNode("-23");
try int_child.appendChild(int_child_text);
}
{
var wacky_child = try doc.createElement("wacky:child");
try element1.appendChild(wacky_child);
var wacky_child_text = try doc.createTextNode("1");
try wacky_child.appendChild(wacky_child_text);
}
}
{
var element2 = try doc.createElement("element2");
try root.appendChild(element2);
{
var child2 = try doc.createElement("child2");
try element2.appendChild(child2);
var child2_text = try doc.createTextNode("I am optional");
try child2.appendChild(child2_text);
}
{
var repeated = try doc.createElement("repeated");
try element2.appendChild(repeated);
var anotherone = try doc.createElement("anotherone");
try repeated.appendChild(anotherone);
var anotherone_text = try doc.createTextNode("Another one");
try anotherone.appendChild(anotherone_text);
}
{
var repeated = try doc.createElement("repeated");
try element2.appendChild(repeated);
var anotherone = try doc.createElement("anotherone");
try repeated.appendChild(anotherone);
try anotherone.setAttribute("optionalattr", "yes");
var anotherone_text = try doc.createTextNode("Another two");
try anotherone.appendChild(anotherone_text);
}
}
var string = try doc.toStringWithProlog();
defer string.deinit();
try testing.expectEqualStrings(full.file, string.string);
}
test "decoding from XML" {
var doc = try Document.fromString(full.file);
defer doc.deinit();
const root = (try doc.getElementsByTagName("root").getSingleItem()).Element;
const element1 = (try root.getElementsByTagName("element1").getSingleItem()).Element;
try testing.expectEqualStrings("hello", element1.getAttribute("attr1").?);
try testing.expectEqualStrings("world", element1.getAttribute("attr2").?);
try testing.expect(element1.getAttribute("bogus") == null);
const child1 = (try element1.getElementsByTagName("child1").getSingleItem()).Element;
const child1_text = (try child1.getFirstChild()).?.TextNode;
try testing.expectEqualStrings("I am required", child1_text.getValue());
const int_child = (try element1.getElementsByTagName("int-child").getSingleItem()).Element;
const int_child_text = (try int_child.getFirstChild()).?.TextNode;
try testing.expectEqualStrings("-23", int_child_text.getValue());
const wacky_child = (try element1.getElementsByTagName("wacky:child").getSingleItem()).Element;
const wacky_child_text = (try wacky_child.getFirstChild()).?.TextNode;
try testing.expectEqualStrings("1", wacky_child_text.getValue());
const bogus_children = element1.getElementsByTagName("bogus");
try testing.expectEqual(@as(usize, 0), bogus_children.getLength());
const element2 = (try root.getElementsByTagName("element2").getSingleItem()).Element;
const child2 = (try element2.getElementsByTagName("child2").getSingleItem()).Element;
const child2_text = (try child2.getFirstChild()).?.TextNode;
try testing.expectEqualStrings("I am optional", child2_text.getValue());
var repeated_iter = element2.getElementsByTagName("repeated").iterator();
const repeated1 = (try repeated_iter.next()).?.Element;
const anotherone1 = (try repeated1.getElementsByTagName("anotherone").getSingleItem()).Element;
const anotherone1_text = (try anotherone1.getFirstChild()).?.TextNode;
try testing.expectEqualStrings("Another one", anotherone1_text.getValue());
const repeated2 = (try repeated_iter.next()).?.Element;
const anotherone2 = (try repeated2.getElementsByTagName("anotherone").getSingleItem()).Element;
const anotherone2_text = (try anotherone2.getFirstChild()).?.TextNode;
try testing.expectEqualStrings("Another two", anotherone2_text.getValue());
try testing.expectEqualStrings("yes", anotherone2.getAttribute("optionalattr").?);
try testing.expect((try repeated_iter.next()) == null);
}
|
test/test_xml.zig
|
const std = @import("std");
const mem = std.mem;
const Unassigned = @This();
allocator: *mem.Allocator,
array: []bool,
lo: u21 = 888,
hi: u21 = 1114111,
pub fn init(allocator: *mem.Allocator) !Unassigned {
var instance = Unassigned{
.allocator = allocator,
.array = try allocator.alloc(bool, 1113224),
};
mem.set(bool, instance.array, false);
var index: u21 = 0;
index = 0;
while (index <= 1) : (index += 1) {
instance.array[index] = true;
}
index = 8;
while (index <= 11) : (index += 1) {
instance.array[index] = true;
}
instance.array[19] = true;
instance.array[21] = true;
instance.array[42] = true;
instance.array[440] = true;
index = 479;
while (index <= 480) : (index += 1) {
instance.array[index] = true;
}
index = 531;
while (index <= 532) : (index += 1) {
instance.array[index] = true;
}
instance.array[536] = true;
index = 592;
while (index <= 599) : (index += 1) {
instance.array[index] = true;
}
index = 627;
while (index <= 630) : (index += 1) {
instance.array[index] = true;
}
index = 637;
while (index <= 647) : (index += 1) {
instance.array[index] = true;
}
instance.array[677] = true;
instance.array[918] = true;
index = 979;
while (index <= 980) : (index += 1) {
instance.array[index] = true;
}
index = 1082;
while (index <= 1095) : (index += 1) {
instance.array[index] = true;
}
index = 1155;
while (index <= 1156) : (index += 1) {
instance.array[index] = true;
}
index = 1206;
while (index <= 1207) : (index += 1) {
instance.array[index] = true;
}
instance.array[1223] = true;
index = 1252;
while (index <= 1253) : (index += 1) {
instance.array[index] = true;
}
instance.array[1255] = true;
index = 1267;
while (index <= 1319) : (index += 1) {
instance.array[index] = true;
}
instance.array[1341] = true;
index = 1360;
while (index <= 1370) : (index += 1) {
instance.array[index] = true;
}
instance.array[1548] = true;
index = 1557;
while (index <= 1558) : (index += 1) {
instance.array[index] = true;
}
index = 1561;
while (index <= 1562) : (index += 1) {
instance.array[index] = true;
}
instance.array[1585] = true;
instance.array[1593] = true;
index = 1595;
while (index <= 1597) : (index += 1) {
instance.array[index] = true;
}
index = 1602;
while (index <= 1603) : (index += 1) {
instance.array[index] = true;
}
index = 1613;
while (index <= 1614) : (index += 1) {
instance.array[index] = true;
}
index = 1617;
while (index <= 1618) : (index += 1) {
instance.array[index] = true;
}
index = 1623;
while (index <= 1630) : (index += 1) {
instance.array[index] = true;
}
index = 1632;
while (index <= 1635) : (index += 1) {
instance.array[index] = true;
}
instance.array[1638] = true;
index = 1644;
while (index <= 1645) : (index += 1) {
instance.array[index] = true;
}
index = 1671;
while (index <= 1672) : (index += 1) {
instance.array[index] = true;
}
instance.array[1676] = true;
index = 1683;
while (index <= 1686) : (index += 1) {
instance.array[index] = true;
}
index = 1689;
while (index <= 1690) : (index += 1) {
instance.array[index] = true;
}
instance.array[1713] = true;
instance.array[1721] = true;
instance.array[1724] = true;
instance.array[1727] = true;
index = 1730;
while (index <= 1731) : (index += 1) {
instance.array[index] = true;
}
instance.array[1733] = true;
index = 1739;
while (index <= 1742) : (index += 1) {
instance.array[index] = true;
}
index = 1745;
while (index <= 1746) : (index += 1) {
instance.array[index] = true;
}
index = 1750;
while (index <= 1752) : (index += 1) {
instance.array[index] = true;
}
index = 1754;
while (index <= 1760) : (index += 1) {
instance.array[index] = true;
}
instance.array[1765] = true;
index = 1767;
while (index <= 1773) : (index += 1) {
instance.array[index] = true;
}
index = 1791;
while (index <= 1800) : (index += 1) {
instance.array[index] = true;
}
instance.array[1804] = true;
instance.array[1814] = true;
instance.array[1818] = true;
instance.array[1841] = true;
instance.array[1849] = true;
instance.array[1852] = true;
index = 1858;
while (index <= 1859) : (index += 1) {
instance.array[index] = true;
}
instance.array[1870] = true;
instance.array[1874] = true;
index = 1878;
while (index <= 1879) : (index += 1) {
instance.array[index] = true;
}
index = 1881;
while (index <= 1895) : (index += 1) {
instance.array[index] = true;
}
index = 1900;
while (index <= 1901) : (index += 1) {
instance.array[index] = true;
}
index = 1914;
while (index <= 1920) : (index += 1) {
instance.array[index] = true;
}
instance.array[1928] = true;
instance.array[1932] = true;
index = 1941;
while (index <= 1942) : (index += 1) {
instance.array[index] = true;
}
index = 1945;
while (index <= 1946) : (index += 1) {
instance.array[index] = true;
}
instance.array[1969] = true;
instance.array[1977] = true;
instance.array[1980] = true;
index = 1986;
while (index <= 1987) : (index += 1) {
instance.array[index] = true;
}
index = 1997;
while (index <= 1998) : (index += 1) {
instance.array[index] = true;
}
index = 2001;
while (index <= 2002) : (index += 1) {
instance.array[index] = true;
}
index = 2006;
while (index <= 2012) : (index += 1) {
instance.array[index] = true;
}
index = 2016;
while (index <= 2019) : (index += 1) {
instance.array[index] = true;
}
instance.array[2022] = true;
index = 2028;
while (index <= 2029) : (index += 1) {
instance.array[index] = true;
}
index = 2048;
while (index <= 2057) : (index += 1) {
instance.array[index] = true;
}
instance.array[2060] = true;
index = 2067;
while (index <= 2069) : (index += 1) {
instance.array[index] = true;
}
instance.array[2073] = true;
index = 2078;
while (index <= 2080) : (index += 1) {
instance.array[index] = true;
}
instance.array[2083] = true;
instance.array[2085] = true;
index = 2088;
while (index <= 2090) : (index += 1) {
instance.array[index] = true;
}
index = 2093;
while (index <= 2095) : (index += 1) {
instance.array[index] = true;
}
index = 2099;
while (index <= 2101) : (index += 1) {
instance.array[index] = true;
}
index = 2114;
while (index <= 2117) : (index += 1) {
instance.array[index] = true;
}
index = 2123;
while (index <= 2125) : (index += 1) {
instance.array[index] = true;
}
instance.array[2129] = true;
index = 2134;
while (index <= 2135) : (index += 1) {
instance.array[index] = true;
}
index = 2137;
while (index <= 2142) : (index += 1) {
instance.array[index] = true;
}
index = 2144;
while (index <= 2157) : (index += 1) {
instance.array[index] = true;
}
index = 2179;
while (index <= 2183) : (index += 1) {
instance.array[index] = true;
}
instance.array[2197] = true;
instance.array[2201] = true;
instance.array[2225] = true;
index = 2242;
while (index <= 2244) : (index += 1) {
instance.array[index] = true;
}
instance.array[2253] = true;
instance.array[2257] = true;
index = 2262;
while (index <= 2268) : (index += 1) {
instance.array[index] = true;
}
instance.array[2271] = true;
index = 2275;
while (index <= 2279) : (index += 1) {
instance.array[index] = true;
}
index = 2284;
while (index <= 2285) : (index += 1) {
instance.array[index] = true;
}
index = 2296;
while (index <= 2302) : (index += 1) {
instance.array[index] = true;
}
instance.array[2325] = true;
instance.array[2329] = true;
instance.array[2353] = true;
instance.array[2364] = true;
index = 2370;
while (index <= 2371) : (index += 1) {
instance.array[index] = true;
}
instance.array[2381] = true;
instance.array[2385] = true;
index = 2390;
while (index <= 2396) : (index += 1) {
instance.array[index] = true;
}
index = 2399;
while (index <= 2405) : (index += 1) {
instance.array[index] = true;
}
instance.array[2407] = true;
index = 2412;
while (index <= 2413) : (index += 1) {
instance.array[index] = true;
}
instance.array[2424] = true;
index = 2427;
while (index <= 2439) : (index += 1) {
instance.array[index] = true;
}
instance.array[2453] = true;
instance.array[2457] = true;
instance.array[2509] = true;
instance.array[2513] = true;
index = 2520;
while (index <= 2523) : (index += 1) {
instance.array[index] = true;
}
index = 2540;
while (index <= 2541) : (index += 1) {
instance.array[index] = true;
}
instance.array[2568] = true;
instance.array[2572] = true;
index = 2591;
while (index <= 2593) : (index += 1) {
instance.array[index] = true;
}
instance.array[2618] = true;
instance.array[2628] = true;
index = 2630;
while (index <= 2631) : (index += 1) {
instance.array[index] = true;
}
index = 2639;
while (index <= 2641) : (index += 1) {
instance.array[index] = true;
}
index = 2643;
while (index <= 2646) : (index += 1) {
instance.array[index] = true;
}
instance.array[2653] = true;
instance.array[2655] = true;
index = 2664;
while (index <= 2669) : (index += 1) {
instance.array[index] = true;
}
index = 2680;
while (index <= 2681) : (index += 1) {
instance.array[index] = true;
}
index = 2685;
while (index <= 2696) : (index += 1) {
instance.array[index] = true;
}
index = 2755;
while (index <= 2758) : (index += 1) {
instance.array[index] = true;
}
index = 2788;
while (index <= 2824) : (index += 1) {
instance.array[index] = true;
}
instance.array[2827] = true;
instance.array[2829] = true;
instance.array[2835] = true;
instance.array[2860] = true;
instance.array[2862] = true;
index = 2886;
while (index <= 2887) : (index += 1) {
instance.array[index] = true;
}
instance.array[2893] = true;
instance.array[2895] = true;
index = 2902;
while (index <= 2903) : (index += 1) {
instance.array[index] = true;
}
index = 2914;
while (index <= 2915) : (index += 1) {
instance.array[index] = true;
}
index = 2920;
while (index <= 2951) : (index += 1) {
instance.array[index] = true;
}
instance.array[3024] = true;
index = 3061;
while (index <= 3064) : (index += 1) {
instance.array[index] = true;
}
instance.array[3104] = true;
instance.array[3141] = true;
instance.array[3157] = true;
index = 3171;
while (index <= 3207) : (index += 1) {
instance.array[index] = true;
}
instance.array[3406] = true;
index = 3408;
while (index <= 3412) : (index += 1) {
instance.array[index] = true;
}
index = 3414;
while (index <= 3415) : (index += 1) {
instance.array[index] = true;
}
instance.array[3793] = true;
index = 3798;
while (index <= 3799) : (index += 1) {
instance.array[index] = true;
}
instance.array[3807] = true;
instance.array[3809] = true;
index = 3814;
while (index <= 3815) : (index += 1) {
instance.array[index] = true;
}
instance.array[3857] = true;
index = 3862;
while (index <= 3863) : (index += 1) {
instance.array[index] = true;
}
instance.array[3897] = true;
index = 3902;
while (index <= 3903) : (index += 1) {
instance.array[index] = true;
}
instance.array[3911] = true;
instance.array[3913] = true;
index = 3918;
while (index <= 3919) : (index += 1) {
instance.array[index] = true;
}
instance.array[3935] = true;
instance.array[3993] = true;
index = 3998;
while (index <= 3999) : (index += 1) {
instance.array[index] = true;
}
index = 4067;
while (index <= 4068) : (index += 1) {
instance.array[index] = true;
}
index = 4101;
while (index <= 4103) : (index += 1) {
instance.array[index] = true;
}
index = 4130;
while (index <= 4135) : (index += 1) {
instance.array[index] = true;
}
index = 4222;
while (index <= 4223) : (index += 1) {
instance.array[index] = true;
}
index = 4230;
while (index <= 4231) : (index += 1) {
instance.array[index] = true;
}
index = 4901;
while (index <= 4903) : (index += 1) {
instance.array[index] = true;
}
index = 4993;
while (index <= 4999) : (index += 1) {
instance.array[index] = true;
}
instance.array[5013] = true;
index = 5021;
while (index <= 5031) : (index += 1) {
instance.array[index] = true;
}
index = 5055;
while (index <= 5063) : (index += 1) {
instance.array[index] = true;
}
index = 5084;
while (index <= 5095) : (index += 1) {
instance.array[index] = true;
}
instance.array[5109] = true;
instance.array[5113] = true;
index = 5116;
while (index <= 5127) : (index += 1) {
instance.array[index] = true;
}
index = 5222;
while (index <= 5223) : (index += 1) {
instance.array[index] = true;
}
index = 5234;
while (index <= 5239) : (index += 1) {
instance.array[index] = true;
}
index = 5250;
while (index <= 5255) : (index += 1) {
instance.array[index] = true;
}
instance.array[5271] = true;
index = 5282;
while (index <= 5287) : (index += 1) {
instance.array[index] = true;
}
index = 5377;
while (index <= 5383) : (index += 1) {
instance.array[index] = true;
}
index = 5427;
while (index <= 5431) : (index += 1) {
instance.array[index] = true;
}
index = 5502;
while (index <= 5511) : (index += 1) {
instance.array[index] = true;
}
instance.array[5543] = true;
index = 5556;
while (index <= 5559) : (index += 1) {
instance.array[index] = true;
}
index = 5572;
while (index <= 5575) : (index += 1) {
instance.array[index] = true;
}
index = 5577;
while (index <= 5579) : (index += 1) {
instance.array[index] = true;
}
index = 5622;
while (index <= 5623) : (index += 1) {
instance.array[index] = true;
}
index = 5629;
while (index <= 5639) : (index += 1) {
instance.array[index] = true;
}
index = 5684;
while (index <= 5687) : (index += 1) {
instance.array[index] = true;
}
index = 5714;
while (index <= 5719) : (index += 1) {
instance.array[index] = true;
}
index = 5731;
while (index <= 5733) : (index += 1) {
instance.array[index] = true;
}
index = 5796;
while (index <= 5797) : (index += 1) {
instance.array[index] = true;
}
instance.array[5863] = true;
index = 5893;
while (index <= 5894) : (index += 1) {
instance.array[index] = true;
}
index = 5906;
while (index <= 5911) : (index += 1) {
instance.array[index] = true;
}
index = 5922;
while (index <= 5927) : (index += 1) {
instance.array[index] = true;
}
index = 5942;
while (index <= 5943) : (index += 1) {
instance.array[index] = true;
}
index = 5961;
while (index <= 6023) : (index += 1) {
instance.array[index] = true;
}
index = 6100;
while (index <= 6103) : (index += 1) {
instance.array[index] = true;
}
index = 6149;
while (index <= 6151) : (index += 1) {
instance.array[index] = true;
}
index = 6268;
while (index <= 6275) : (index += 1) {
instance.array[index] = true;
}
index = 6336;
while (index <= 6338) : (index += 1) {
instance.array[index] = true;
}
index = 6354;
while (index <= 6356) : (index += 1) {
instance.array[index] = true;
}
index = 6417;
while (index <= 6423) : (index += 1) {
instance.array[index] = true;
}
index = 6467;
while (index <= 6468) : (index += 1) {
instance.array[index] = true;
}
index = 6480;
while (index <= 6487) : (index += 1) {
instance.array[index] = true;
}
index = 6531;
while (index <= 6535) : (index += 1) {
instance.array[index] = true;
}
instance.array[6786] = true;
index = 7070;
while (index <= 7071) : (index += 1) {
instance.array[index] = true;
}
index = 7078;
while (index <= 7079) : (index += 1) {
instance.array[index] = true;
}
index = 7118;
while (index <= 7119) : (index += 1) {
instance.array[index] = true;
}
index = 7126;
while (index <= 7127) : (index += 1) {
instance.array[index] = true;
}
instance.array[7136] = true;
instance.array[7138] = true;
instance.array[7140] = true;
instance.array[7142] = true;
index = 7174;
while (index <= 7175) : (index += 1) {
instance.array[index] = true;
}
instance.array[7229] = true;
instance.array[7245] = true;
index = 7260;
while (index <= 7261) : (index += 1) {
instance.array[index] = true;
}
instance.array[7268] = true;
index = 7288;
while (index <= 7289) : (index += 1) {
instance.array[index] = true;
}
instance.array[7293] = true;
instance.array[7303] = true;
instance.array[7405] = true;
index = 7418;
while (index <= 7419) : (index += 1) {
instance.array[index] = true;
}
instance.array[7447] = true;
index = 7461;
while (index <= 7463) : (index += 1) {
instance.array[index] = true;
}
index = 7496;
while (index <= 7511) : (index += 1) {
instance.array[index] = true;
}
index = 7545;
while (index <= 7559) : (index += 1) {
instance.array[index] = true;
}
index = 7700;
while (index <= 7703) : (index += 1) {
instance.array[index] = true;
}
index = 8367;
while (index <= 8391) : (index += 1) {
instance.array[index] = true;
}
index = 8403;
while (index <= 8423) : (index += 1) {
instance.array[index] = true;
}
index = 10236;
while (index <= 10237) : (index += 1) {
instance.array[index] = true;
}
instance.array[10270] = true;
instance.array[10423] = true;
instance.array[10471] = true;
index = 10620;
while (index <= 10624) : (index += 1) {
instance.array[index] = true;
}
instance.array[10670] = true;
index = 10672;
while (index <= 10676) : (index += 1) {
instance.array[index] = true;
}
index = 10678;
while (index <= 10679) : (index += 1) {
instance.array[index] = true;
}
index = 10736;
while (index <= 10742) : (index += 1) {
instance.array[index] = true;
}
index = 10745;
while (index <= 10758) : (index += 1) {
instance.array[index] = true;
}
index = 10783;
while (index <= 10791) : (index += 1) {
instance.array[index] = true;
}
instance.array[10799] = true;
instance.array[10807] = true;
instance.array[10815] = true;
instance.array[10823] = true;
instance.array[10831] = true;
instance.array[10839] = true;
instance.array[10847] = true;
instance.array[10855] = true;
index = 10971;
while (index <= 11015) : (index += 1) {
instance.array[index] = true;
}
instance.array[11042] = true;
index = 11132;
while (index <= 11143) : (index += 1) {
instance.array[index] = true;
}
index = 11358;
while (index <= 11383) : (index += 1) {
instance.array[index] = true;
}
index = 11396;
while (index <= 11399) : (index += 1) {
instance.array[index] = true;
}
instance.array[11464] = true;
index = 11551;
while (index <= 11552) : (index += 1) {
instance.array[index] = true;
}
index = 11656;
while (index <= 11660) : (index += 1) {
instance.array[index] = true;
}
instance.array[11704] = true;
instance.array[11799] = true;
index = 11884;
while (index <= 11895) : (index += 1) {
instance.array[index] = true;
}
instance.array[11943] = true;
index = 40069;
while (index <= 40071) : (index += 1) {
instance.array[index] = true;
}
index = 41237;
while (index <= 41239) : (index += 1) {
instance.array[index] = true;
}
index = 41295;
while (index <= 41303) : (index += 1) {
instance.array[index] = true;
}
index = 41652;
while (index <= 41671) : (index += 1) {
instance.array[index] = true;
}
index = 41856;
while (index <= 41863) : (index += 1) {
instance.array[index] = true;
}
index = 42056;
while (index <= 42057) : (index += 1) {
instance.array[index] = true;
}
index = 42067;
while (index <= 42108) : (index += 1) {
instance.array[index] = true;
}
index = 42165;
while (index <= 42167) : (index += 1) {
instance.array[index] = true;
}
index = 42178;
while (index <= 42183) : (index += 1) {
instance.array[index] = true;
}
index = 42240;
while (index <= 42247) : (index += 1) {
instance.array[index] = true;
}
index = 42318;
while (index <= 42325) : (index += 1) {
instance.array[index] = true;
}
index = 42338;
while (index <= 42343) : (index += 1) {
instance.array[index] = true;
}
index = 42460;
while (index <= 42470) : (index += 1) {
instance.array[index] = true;
}
index = 42501;
while (index <= 42503) : (index += 1) {
instance.array[index] = true;
}
instance.array[42582] = true;
index = 42594;
while (index <= 42597) : (index += 1) {
instance.array[index] = true;
}
instance.array[42631] = true;
index = 42687;
while (index <= 42695) : (index += 1) {
instance.array[index] = true;
}
index = 42710;
while (index <= 42711) : (index += 1) {
instance.array[index] = true;
}
index = 42722;
while (index <= 42723) : (index += 1) {
instance.array[index] = true;
}
index = 42827;
while (index <= 42850) : (index += 1) {
instance.array[index] = true;
}
index = 42879;
while (index <= 42888) : (index += 1) {
instance.array[index] = true;
}
index = 42895;
while (index <= 42896) : (index += 1) {
instance.array[index] = true;
}
index = 42903;
while (index <= 42904) : (index += 1) {
instance.array[index] = true;
}
index = 42911;
while (index <= 42919) : (index += 1) {
instance.array[index] = true;
}
instance.array[42927] = true;
instance.array[42935] = true;
index = 42996;
while (index <= 42999) : (index += 1) {
instance.array[index] = true;
}
index = 43126;
while (index <= 43127) : (index += 1) {
instance.array[index] = true;
}
index = 43138;
while (index <= 43143) : (index += 1) {
instance.array[index] = true;
}
index = 54316;
while (index <= 54327) : (index += 1) {
instance.array[index] = true;
}
index = 54351;
while (index <= 54354) : (index += 1) {
instance.array[index] = true;
}
index = 54404;
while (index <= 54407) : (index += 1) {
instance.array[index] = true;
}
index = 63222;
while (index <= 63223) : (index += 1) {
instance.array[index] = true;
}
index = 63330;
while (index <= 63367) : (index += 1) {
instance.array[index] = true;
}
index = 63375;
while (index <= 63386) : (index += 1) {
instance.array[index] = true;
}
index = 63392;
while (index <= 63396) : (index += 1) {
instance.array[index] = true;
}
instance.array[63423] = true;
instance.array[63429] = true;
instance.array[63431] = true;
instance.array[63434] = true;
instance.array[63437] = true;
index = 63562;
while (index <= 63578) : (index += 1) {
instance.array[index] = true;
}
index = 63944;
while (index <= 63959) : (index += 1) {
instance.array[index] = true;
}
index = 64024;
while (index <= 64025) : (index += 1) {
instance.array[index] = true;
}
index = 64080;
while (index <= 64119) : (index += 1) {
instance.array[index] = true;
}
index = 64134;
while (index <= 64135) : (index += 1) {
instance.array[index] = true;
}
index = 64162;
while (index <= 64167) : (index += 1) {
instance.array[index] = true;
}
instance.array[64219] = true;
instance.array[64239] = true;
index = 64244;
while (index <= 64247) : (index += 1) {
instance.array[index] = true;
}
instance.array[64253] = true;
index = 64389;
while (index <= 64390) : (index += 1) {
instance.array[index] = true;
}
instance.array[64392] = true;
index = 64583;
while (index <= 64585) : (index += 1) {
instance.array[index] = true;
}
index = 64592;
while (index <= 64593) : (index += 1) {
instance.array[index] = true;
}
index = 64600;
while (index <= 64601) : (index += 1) {
instance.array[index] = true;
}
index = 64608;
while (index <= 64609) : (index += 1) {
instance.array[index] = true;
}
index = 64613;
while (index <= 64615) : (index += 1) {
instance.array[index] = true;
}
instance.array[64623] = true;
index = 64631;
while (index <= 64640) : (index += 1) {
instance.array[index] = true;
}
index = 64646;
while (index <= 64647) : (index += 1) {
instance.array[index] = true;
}
instance.array[64660] = true;
instance.array[64687] = true;
instance.array[64707] = true;
instance.array[64710] = true;
index = 64726;
while (index <= 64727) : (index += 1) {
instance.array[index] = true;
}
index = 64742;
while (index <= 64775) : (index += 1) {
instance.array[index] = true;
}
index = 64899;
while (index <= 64903) : (index += 1) {
instance.array[index] = true;
}
index = 64907;
while (index <= 64910) : (index += 1) {
instance.array[index] = true;
}
index = 64956;
while (index <= 64958) : (index += 1) {
instance.array[index] = true;
}
instance.array[65047] = true;
index = 65061;
while (index <= 65063) : (index += 1) {
instance.array[index] = true;
}
index = 65065;
while (index <= 65111) : (index += 1) {
instance.array[index] = true;
}
index = 65158;
while (index <= 65287) : (index += 1) {
instance.array[index] = true;
}
index = 65317;
while (index <= 65319) : (index += 1) {
instance.array[index] = true;
}
index = 65369;
while (index <= 65383) : (index += 1) {
instance.array[index] = true;
}
index = 65412;
while (index <= 65415) : (index += 1) {
instance.array[index] = true;
}
index = 65452;
while (index <= 65460) : (index += 1) {
instance.array[index] = true;
}
index = 65491;
while (index <= 65495) : (index += 1) {
instance.array[index] = true;
}
index = 65539;
while (index <= 65543) : (index += 1) {
instance.array[index] = true;
}
instance.array[65574] = true;
index = 65612;
while (index <= 65615) : (index += 1) {
instance.array[index] = true;
}
index = 65630;
while (index <= 65671) : (index += 1) {
instance.array[index] = true;
}
index = 65830;
while (index <= 65831) : (index += 1) {
instance.array[index] = true;
}
index = 65842;
while (index <= 65847) : (index += 1) {
instance.array[index] = true;
}
index = 65884;
while (index <= 65887) : (index += 1) {
instance.array[index] = true;
}
index = 65924;
while (index <= 65927) : (index += 1) {
instance.array[index] = true;
}
index = 65968;
while (index <= 65975) : (index += 1) {
instance.array[index] = true;
}
index = 66028;
while (index <= 66038) : (index += 1) {
instance.array[index] = true;
}
index = 66040;
while (index <= 66183) : (index += 1) {
instance.array[index] = true;
}
index = 66495;
while (index <= 66503) : (index += 1) {
instance.array[index] = true;
}
index = 66526;
while (index <= 66535) : (index += 1) {
instance.array[index] = true;
}
index = 66544;
while (index <= 66695) : (index += 1) {
instance.array[index] = true;
}
index = 66702;
while (index <= 66703) : (index += 1) {
instance.array[index] = true;
}
instance.array[66705] = true;
instance.array[66750] = true;
index = 66753;
while (index <= 66755) : (index += 1) {
instance.array[index] = true;
}
index = 66757;
while (index <= 66758) : (index += 1) {
instance.array[index] = true;
}
instance.array[66782] = true;
index = 66855;
while (index <= 66862) : (index += 1) {
instance.array[index] = true;
}
index = 66872;
while (index <= 66919) : (index += 1) {
instance.array[index] = true;
}
instance.array[66939] = true;
index = 66942;
while (index <= 66946) : (index += 1) {
instance.array[index] = true;
}
index = 66980;
while (index <= 66982) : (index += 1) {
instance.array[index] = true;
}
index = 67010;
while (index <= 67014) : (index += 1) {
instance.array[index] = true;
}
index = 67016;
while (index <= 67079) : (index += 1) {
instance.array[index] = true;
}
index = 67136;
while (index <= 67139) : (index += 1) {
instance.array[index] = true;
}
index = 67160;
while (index <= 67161) : (index += 1) {
instance.array[index] = true;
}
instance.array[67212] = true;
index = 67215;
while (index <= 67219) : (index += 1) {
instance.array[index] = true;
}
instance.array[67228] = true;
instance.array[67232] = true;
index = 67262;
while (index <= 67263) : (index += 1) {
instance.array[index] = true;
}
index = 67267;
while (index <= 67270) : (index += 1) {
instance.array[index] = true;
}
index = 67281;
while (index <= 67287) : (index += 1) {
instance.array[index] = true;
}
index = 67297;
while (index <= 67303) : (index += 1) {
instance.array[index] = true;
}
index = 67368;
while (index <= 67399) : (index += 1) {
instance.array[index] = true;
}
index = 67439;
while (index <= 67442) : (index += 1) {
instance.array[index] = true;
}
index = 67455;
while (index <= 67463) : (index += 1) {
instance.array[index] = true;
}
index = 67518;
while (index <= 67520) : (index += 1) {
instance.array[index] = true;
}
index = 67550;
while (index <= 67551) : (index += 1) {
instance.array[index] = true;
}
index = 67579;
while (index <= 67583) : (index += 1) {
instance.array[index] = true;
}
index = 67610;
while (index <= 67616) : (index += 1) {
instance.array[index] = true;
}
index = 67621;
while (index <= 67632) : (index += 1) {
instance.array[index] = true;
}
index = 67640;
while (index <= 67719) : (index += 1) {
instance.array[index] = true;
}
index = 67793;
while (index <= 67847) : (index += 1) {
instance.array[index] = true;
}
index = 67899;
while (index <= 67911) : (index += 1) {
instance.array[index] = true;
}
index = 67963;
while (index <= 67969) : (index += 1) {
instance.array[index] = true;
}
index = 68016;
while (index <= 68023) : (index += 1) {
instance.array[index] = true;
}
index = 68034;
while (index <= 68327) : (index += 1) {
instance.array[index] = true;
}
instance.array[68359] = true;
instance.array[68402] = true;
index = 68406;
while (index <= 68407) : (index += 1) {
instance.array[index] = true;
}
index = 68410;
while (index <= 68487) : (index += 1) {
instance.array[index] = true;
}
index = 68528;
while (index <= 68535) : (index += 1) {
instance.array[index] = true;
}
index = 68578;
while (index <= 68663) : (index += 1) {
instance.array[index] = true;
}
index = 68692;
while (index <= 68711) : (index += 1) {
instance.array[index] = true;
}
index = 68735;
while (index <= 68743) : (index += 1) {
instance.array[index] = true;
}
index = 68822;
while (index <= 68825) : (index += 1) {
instance.array[index] = true;
}
index = 68856;
while (index <= 68870) : (index += 1) {
instance.array[index] = true;
}
index = 68938;
while (index <= 68948) : (index += 1) {
instance.array[index] = true;
}
index = 68950;
while (index <= 68951) : (index += 1) {
instance.array[index] = true;
}
index = 68977;
while (index <= 68983) : (index += 1) {
instance.array[index] = true;
}
index = 68994;
while (index <= 68999) : (index += 1) {
instance.array[index] = true;
}
instance.array[69053] = true;
index = 69072;
while (index <= 69079) : (index += 1) {
instance.array[index] = true;
}
index = 69119;
while (index <= 69127) : (index += 1) {
instance.array[index] = true;
}
instance.array[69224] = true;
index = 69245;
while (index <= 69255) : (index += 1) {
instance.array[index] = true;
}
instance.array[69274] = true;
index = 69319;
while (index <= 69383) : (index += 1) {
instance.array[index] = true;
}
instance.array[69391] = true;
instance.array[69393] = true;
instance.array[69398] = true;
instance.array[69414] = true;
index = 69426;
while (index <= 69431) : (index += 1) {
instance.array[index] = true;
}
index = 69491;
while (index <= 69495) : (index += 1) {
instance.array[index] = true;
}
index = 69506;
while (index <= 69511) : (index += 1) {
instance.array[index] = true;
}
instance.array[69516] = true;
index = 69525;
while (index <= 69526) : (index += 1) {
instance.array[index] = true;
}
index = 69529;
while (index <= 69530) : (index += 1) {
instance.array[index] = true;
}
instance.array[69553] = true;
instance.array[69561] = true;
instance.array[69564] = true;
instance.array[69570] = true;
index = 69581;
while (index <= 69582) : (index += 1) {
instance.array[index] = true;
}
index = 69585;
while (index <= 69586) : (index += 1) {
instance.array[index] = true;
}
index = 69590;
while (index <= 69591) : (index += 1) {
instance.array[index] = true;
}
index = 69593;
while (index <= 69598) : (index += 1) {
instance.array[index] = true;
}
index = 69600;
while (index <= 69604) : (index += 1) {
instance.array[index] = true;
}
index = 69612;
while (index <= 69613) : (index += 1) {
instance.array[index] = true;
}
index = 69621;
while (index <= 69623) : (index += 1) {
instance.array[index] = true;
}
index = 69629;
while (index <= 69767) : (index += 1) {
instance.array[index] = true;
}
instance.array[69860] = true;
index = 69866;
while (index <= 69895) : (index += 1) {
instance.array[index] = true;
}
index = 69968;
while (index <= 69975) : (index += 1) {
instance.array[index] = true;
}
index = 69986;
while (index <= 70151) : (index += 1) {
instance.array[index] = true;
}
index = 70206;
while (index <= 70207) : (index += 1) {
instance.array[index] = true;
}
index = 70246;
while (index <= 70279) : (index += 1) {
instance.array[index] = true;
}
index = 70349;
while (index <= 70359) : (index += 1) {
instance.array[index] = true;
}
index = 70370;
while (index <= 70375) : (index += 1) {
instance.array[index] = true;
}
index = 70389;
while (index <= 70407) : (index += 1) {
instance.array[index] = true;
}
index = 70465;
while (index <= 70471) : (index += 1) {
instance.array[index] = true;
}
index = 70482;
while (index <= 70535) : (index += 1) {
instance.array[index] = true;
}
index = 70563;
while (index <= 70564) : (index += 1) {
instance.array[index] = true;
}
index = 70580;
while (index <= 70583) : (index += 1) {
instance.array[index] = true;
}
index = 70600;
while (index <= 70791) : (index += 1) {
instance.array[index] = true;
}
index = 70852;
while (index <= 70951) : (index += 1) {
instance.array[index] = true;
}
index = 71035;
while (index <= 71046) : (index += 1) {
instance.array[index] = true;
}
index = 71055;
while (index <= 71056) : (index += 1) {
instance.array[index] = true;
}
index = 71058;
while (index <= 71059) : (index += 1) {
instance.array[index] = true;
}
instance.array[71068] = true;
instance.array[71071] = true;
instance.array[71102] = true;
index = 71105;
while (index <= 71106) : (index += 1) {
instance.array[index] = true;
}
index = 71119;
while (index <= 71127) : (index += 1) {
instance.array[index] = true;
}
index = 71138;
while (index <= 71207) : (index += 1) {
instance.array[index] = true;
}
index = 71216;
while (index <= 71217) : (index += 1) {
instance.array[index] = true;
}
index = 71264;
while (index <= 71265) : (index += 1) {
instance.array[index] = true;
}
index = 71277;
while (index <= 71303) : (index += 1) {
instance.array[index] = true;
}
index = 71376;
while (index <= 71383) : (index += 1) {
instance.array[index] = true;
}
index = 71467;
while (index <= 71495) : (index += 1) {
instance.array[index] = true;
}
index = 71553;
while (index <= 71815) : (index += 1) {
instance.array[index] = true;
}
instance.array[71825] = true;
instance.array[71871] = true;
index = 71886;
while (index <= 71895) : (index += 1) {
instance.array[index] = true;
}
index = 71925;
while (index <= 71927) : (index += 1) {
instance.array[index] = true;
}
index = 71960;
while (index <= 71961) : (index += 1) {
instance.array[index] = true;
}
instance.array[71984] = true;
index = 71999;
while (index <= 72071) : (index += 1) {
instance.array[index] = true;
}
instance.array[72079] = true;
instance.array[72082] = true;
index = 72127;
while (index <= 72129) : (index += 1) {
instance.array[index] = true;
}
instance.array[72131] = true;
instance.array[72134] = true;
index = 72144;
while (index <= 72151) : (index += 1) {
instance.array[index] = true;
}
index = 72162;
while (index <= 72167) : (index += 1) {
instance.array[index] = true;
}
instance.array[72174] = true;
instance.array[72177] = true;
instance.array[72215] = true;
instance.array[72218] = true;
index = 72225;
while (index <= 72231) : (index += 1) {
instance.array[index] = true;
}
index = 72242;
while (index <= 72551) : (index += 1) {
instance.array[index] = true;
}
index = 72577;
while (index <= 72759) : (index += 1) {
instance.array[index] = true;
}
index = 72761;
while (index <= 72775) : (index += 1) {
instance.array[index] = true;
}
index = 72826;
while (index <= 72838) : (index += 1) {
instance.array[index] = true;
}
index = 73762;
while (index <= 73863) : (index += 1) {
instance.array[index] = true;
}
instance.array[73975] = true;
index = 73981;
while (index <= 73991) : (index += 1) {
instance.array[index] = true;
}
index = 74188;
while (index <= 76935) : (index += 1) {
instance.array[index] = true;
}
instance.array[78007] = true;
index = 78017;
while (index <= 82055) : (index += 1) {
instance.array[index] = true;
}
index = 82639;
while (index <= 91271) : (index += 1) {
instance.array[index] = true;
}
index = 91841;
while (index <= 91847) : (index += 1) {
instance.array[index] = true;
}
instance.array[91879] = true;
index = 91890;
while (index <= 91893) : (index += 1) {
instance.array[index] = true;
}
index = 91896;
while (index <= 91991) : (index += 1) {
instance.array[index] = true;
}
index = 92022;
while (index <= 92023) : (index += 1) {
instance.array[index] = true;
}
index = 92030;
while (index <= 92039) : (index += 1) {
instance.array[index] = true;
}
index = 92110;
while (index <= 92119) : (index += 1) {
instance.array[index] = true;
}
instance.array[92130] = true;
instance.array[92138] = true;
index = 92160;
while (index <= 92164) : (index += 1) {
instance.array[index] = true;
}
index = 92184;
while (index <= 92871) : (index += 1) {
instance.array[index] = true;
}
index = 92963;
while (index <= 93063) : (index += 1) {
instance.array[index] = true;
}
index = 93139;
while (index <= 93142) : (index += 1) {
instance.array[index] = true;
}
index = 93200;
while (index <= 93206) : (index += 1) {
instance.array[index] = true;
}
index = 93224;
while (index <= 93287) : (index += 1) {
instance.array[index] = true;
}
index = 93293;
while (index <= 93303) : (index += 1) {
instance.array[index] = true;
}
index = 93306;
while (index <= 93319) : (index += 1) {
instance.array[index] = true;
}
index = 99456;
while (index <= 99463) : (index += 1) {
instance.array[index] = true;
}
index = 100702;
while (index <= 100743) : (index += 1) {
instance.array[index] = true;
}
index = 100753;
while (index <= 109703) : (index += 1) {
instance.array[index] = true;
}
index = 109991;
while (index <= 110039) : (index += 1) {
instance.array[index] = true;
}
index = 110043;
while (index <= 110059) : (index += 1) {
instance.array[index] = true;
}
index = 110064;
while (index <= 110071) : (index += 1) {
instance.array[index] = true;
}
index = 110468;
while (index <= 112775) : (index += 1) {
instance.array[index] = true;
}
index = 112883;
while (index <= 112887) : (index += 1) {
instance.array[index] = true;
}
index = 112901;
while (index <= 112903) : (index += 1) {
instance.array[index] = true;
}
index = 112913;
while (index <= 112919) : (index += 1) {
instance.array[index] = true;
}
index = 112930;
while (index <= 112931) : (index += 1) {
instance.array[index] = true;
}
index = 112940;
while (index <= 117895) : (index += 1) {
instance.array[index] = true;
}
index = 118142;
while (index <= 118151) : (index += 1) {
instance.array[index] = true;
}
index = 118191;
while (index <= 118192) : (index += 1) {
instance.array[index] = true;
}
index = 118385;
while (index <= 118407) : (index += 1) {
instance.array[index] = true;
}
index = 118478;
while (index <= 118631) : (index += 1) {
instance.array[index] = true;
}
index = 118652;
while (index <= 118663) : (index += 1) {
instance.array[index] = true;
}
index = 118751;
while (index <= 118759) : (index += 1) {
instance.array[index] = true;
}
index = 118785;
while (index <= 118919) : (index += 1) {
instance.array[index] = true;
}
instance.array[119005] = true;
instance.array[119077] = true;
index = 119080;
while (index <= 119081) : (index += 1) {
instance.array[index] = true;
}
index = 119083;
while (index <= 119084) : (index += 1) {
instance.array[index] = true;
}
index = 119087;
while (index <= 119088) : (index += 1) {
instance.array[index] = true;
}
instance.array[119093] = true;
instance.array[119106] = true;
instance.array[119108] = true;
instance.array[119116] = true;
instance.array[119182] = true;
index = 119187;
while (index <= 119188) : (index += 1) {
instance.array[index] = true;
}
instance.array[119197] = true;
instance.array[119205] = true;
instance.array[119234] = true;
instance.array[119239] = true;
instance.array[119245] = true;
index = 119247;
while (index <= 119249) : (index += 1) {
instance.array[index] = true;
}
instance.array[119257] = true;
index = 119598;
while (index <= 119599) : (index += 1) {
instance.array[index] = true;
}
index = 119892;
while (index <= 119893) : (index += 1) {
instance.array[index] = true;
}
index = 120596;
while (index <= 120610) : (index += 1) {
instance.array[index] = true;
}
instance.array[120616] = true;
index = 120632;
while (index <= 121991) : (index += 1) {
instance.array[index] = true;
}
instance.array[121999] = true;
index = 122017;
while (index <= 122018) : (index += 1) {
instance.array[index] = true;
}
instance.array[122026] = true;
instance.array[122029] = true;
index = 122035;
while (index <= 122247) : (index += 1) {
instance.array[index] = true;
}
index = 122293;
while (index <= 122295) : (index += 1) {
instance.array[index] = true;
}
index = 122310;
while (index <= 122311) : (index += 1) {
instance.array[index] = true;
}
index = 122322;
while (index <= 122325) : (index += 1) {
instance.array[index] = true;
}
index = 122328;
while (index <= 122695) : (index += 1) {
instance.array[index] = true;
}
index = 122754;
while (index <= 122758) : (index += 1) {
instance.array[index] = true;
}
index = 122760;
while (index <= 124039) : (index += 1) {
instance.array[index] = true;
}
index = 124237;
while (index <= 124238) : (index += 1) {
instance.array[index] = true;
}
index = 124255;
while (index <= 124295) : (index += 1) {
instance.array[index] = true;
}
index = 124372;
while (index <= 124375) : (index += 1) {
instance.array[index] = true;
}
index = 124386;
while (index <= 124389) : (index += 1) {
instance.array[index] = true;
}
index = 124392;
while (index <= 125176) : (index += 1) {
instance.array[index] = true;
}
index = 125245;
while (index <= 125320) : (index += 1) {
instance.array[index] = true;
}
index = 125382;
while (index <= 125575) : (index += 1) {
instance.array[index] = true;
}
instance.array[125580] = true;
instance.array[125608] = true;
instance.array[125611] = true;
index = 125613;
while (index <= 125614) : (index += 1) {
instance.array[index] = true;
}
instance.array[125616] = true;
instance.array[125627] = true;
instance.array[125632] = true;
instance.array[125634] = true;
index = 125636;
while (index <= 125641) : (index += 1) {
instance.array[index] = true;
}
index = 125643;
while (index <= 125646) : (index += 1) {
instance.array[index] = true;
}
instance.array[125648] = true;
instance.array[125650] = true;
instance.array[125652] = true;
instance.array[125656] = true;
instance.array[125659] = true;
index = 125661;
while (index <= 125662) : (index += 1) {
instance.array[index] = true;
}
instance.array[125664] = true;
instance.array[125666] = true;
instance.array[125668] = true;
instance.array[125670] = true;
instance.array[125672] = true;
instance.array[125675] = true;
index = 125677;
while (index <= 125678) : (index += 1) {
instance.array[index] = true;
}
instance.array[125683] = true;
instance.array[125691] = true;
instance.array[125696] = true;
instance.array[125701] = true;
instance.array[125703] = true;
instance.array[125714] = true;
index = 125732;
while (index <= 125736) : (index += 1) {
instance.array[index] = true;
}
instance.array[125740] = true;
instance.array[125746] = true;
index = 125764;
while (index <= 125815) : (index += 1) {
instance.array[index] = true;
}
index = 125818;
while (index <= 126087) : (index += 1) {
instance.array[index] = true;
}
index = 126132;
while (index <= 126135) : (index += 1) {
instance.array[index] = true;
}
index = 126236;
while (index <= 126247) : (index += 1) {
instance.array[index] = true;
}
index = 126263;
while (index <= 126264) : (index += 1) {
instance.array[index] = true;
}
instance.array[126280] = true;
instance.array[126296] = true;
index = 126334;
while (index <= 126343) : (index += 1) {
instance.array[index] = true;
}
index = 126518;
while (index <= 126573) : (index += 1) {
instance.array[index] = true;
}
index = 126603;
while (index <= 126615) : (index += 1) {
instance.array[index] = true;
}
index = 126660;
while (index <= 126663) : (index += 1) {
instance.array[index] = true;
}
index = 126673;
while (index <= 126679) : (index += 1) {
instance.array[index] = true;
}
index = 126682;
while (index <= 126695) : (index += 1) {
instance.array[index] = true;
}
index = 126702;
while (index <= 126855) : (index += 1) {
instance.array[index] = true;
}
index = 127840;
while (index <= 127847) : (index += 1) {
instance.array[index] = true;
}
index = 127861;
while (index <= 127863) : (index += 1) {
instance.array[index] = true;
}
index = 127877;
while (index <= 127879) : (index += 1) {
instance.array[index] = true;
}
index = 127996;
while (index <= 128007) : (index += 1) {
instance.array[index] = true;
}
index = 128097;
while (index <= 128103) : (index += 1) {
instance.array[index] = true;
}
index = 128116;
while (index <= 128135) : (index += 1) {
instance.array[index] = true;
}
index = 128148;
while (index <= 128151) : (index += 1) {
instance.array[index] = true;
}
index = 128208;
while (index <= 128215) : (index += 1) {
instance.array[index] = true;
}
index = 128226;
while (index <= 128231) : (index += 1) {
instance.array[index] = true;
}
index = 128272;
while (index <= 128279) : (index += 1) {
instance.array[index] = true;
}
index = 128310;
while (index <= 128311) : (index += 1) {
instance.array[index] = true;
}
index = 128314;
while (index <= 128391) : (index += 1) {
instance.array[index] = true;
}
instance.array[128513] = true;
instance.array[128596] = true;
index = 128732;
while (index <= 128743) : (index += 1) {
instance.array[index] = true;
}
index = 128758;
while (index <= 128759) : (index += 1) {
instance.array[index] = true;
}
index = 128765;
while (index <= 128767) : (index += 1) {
instance.array[index] = true;
}
index = 128771;
while (index <= 128775) : (index += 1) {
instance.array[index] = true;
}
index = 128783;
while (index <= 128791) : (index += 1) {
instance.array[index] = true;
}
index = 128817;
while (index <= 128823) : (index += 1) {
instance.array[index] = true;
}
index = 128831;
while (index <= 128839) : (index += 1) {
instance.array[index] = true;
}
index = 128843;
while (index <= 128855) : (index += 1) {
instance.array[index] = true;
}
index = 128863;
while (index <= 128903) : (index += 1) {
instance.array[index] = true;
}
instance.array[129051] = true;
index = 129107;
while (index <= 129143) : (index += 1) {
instance.array[index] = true;
}
index = 129154;
while (index <= 130183) : (index += 1) {
instance.array[index] = true;
}
index = 172902;
while (index <= 172935) : (index += 1) {
instance.array[index] = true;
}
index = 177085;
while (index <= 177095) : (index += 1) {
instance.array[index] = true;
}
index = 177318;
while (index <= 177319) : (index += 1) {
instance.array[index] = true;
}
index = 183082;
while (index <= 183095) : (index += 1) {
instance.array[index] = true;
}
index = 190569;
while (index <= 193671) : (index += 1) {
instance.array[index] = true;
}
index = 194214;
while (index <= 195719) : (index += 1) {
instance.array[index] = true;
}
index = 200659;
while (index <= 916616) : (index += 1) {
instance.array[index] = true;
}
index = 916618;
while (index <= 916647) : (index += 1) {
instance.array[index] = true;
}
index = 916744;
while (index <= 916871) : (index += 1) {
instance.array[index] = true;
}
index = 917112;
while (index <= 982151) : (index += 1) {
instance.array[index] = true;
}
index = 1047686;
while (index <= 1047687) : (index += 1) {
instance.array[index] = true;
}
index = 1113222;
while (index <= 1113223) : (index += 1) {
instance.array[index] = true;
}
// Placeholder: 0. Struct name, 1. Code point kind
return instance;
}
pub fn deinit(self: *Unassigned) void {
self.allocator.free(self.array);
}
// isUnassigned checks if cp is of the kind Unassigned.
pub fn isUnassigned(self: Unassigned, cp: u21) bool {
if (cp < self.lo or cp > self.hi) return false;
const index = cp - self.lo;
return if (index >= self.array.len) false else self.array[index];
}
|
src/components/autogen/DerivedGeneralCategory/Unassigned.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day17.txt");
// const data = "target area: x=20..30, y=-10..-5";
var xmin: i32 = 0;
var ymin: i32 = 0;
var xmax: i32 = 0;
var ymax: i32 = 0;
pub fn main() !void {
var it = tokenize(u8, data, "target area: xy=.,\n\r");
xmin = try parseInt(i32, it.next().?, 10);
xmax = try parseInt(i32, it.next().?, 10);
ymin = try parseInt(i32, it.next().?, 10);
ymax = try parseInt(i32, it.next().?, 10);
var part1 = @divTrunc(((-ymin) * (-ymin - 1)), 2);
var set = Map([2]i32, void).init(gpa);
var vx_min: i32 = 0;
var tx_max: i32 = 0;
var x0: i32 = 1;
while (@divExact(x0 * (x0 + 1), 2) < xmin) : (x0 += 1) {}
vx_min = x0;
while (@divExact(x0 * (x0 + 1), 2) < xmax) : (x0 += 1) {}
tx_max = x0 - 1;
var t: i32 = 1;
while (true) : (t += 1) {
var ys = range_y(t);
if (ys[0] >= -ymin) {
break;
}
var vx = vx_min;
while (vx <= xmax) : (vx += 1) {
var px = x(vx, t);
if (px < xmin or px > xmax) continue;
var vy = ys[0];
while (vy <= ys[1]) : (vy += 1) {
var py = y(vy, t);
if (py < ymin or py > ymax) continue;
try set.put([2]i32{ vx, vy }, {});
}
}
}
print("{}\n", .{part1});
print("{}\n", .{set.count()});
}
fn x(x0: i32, t: i32) i32 {
var n: i32 = min(x0, t);
return n * x0 - @divExact(n * (n - 1), 2);
}
fn y(y0: i32, t: i32) i32 {
return t * y0 - @divExact(t * (t - 1), 2);
}
fn range_y(t: i32) [2]i32 {
var minv = @divTrunc(ymin + @divExact(t * (t - 1), 2), t);
var maxv = @divFloor(ymax + @divExact(t * (t - 1), 2), t);
return [2]i32{ minv, maxv };
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
|
src/day17.zig
|
const std = @import("std");
pub const gpu = @import("gpu/build.zig");
const gpu_dawn = @import("gpu-dawn/build.zig");
pub const glfw = @import("glfw/build.zig");
const Pkg = std.build.Pkg;
pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const gpu_dawn_options = gpu_dawn.Options{
.from_source = b.option(bool, "dawn-from-source", "Build Dawn from source") orelse false,
};
const options = Options{ .gpu_dawn_options = gpu_dawn_options };
const main_tests = b.addTest("src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
main_tests.addPackage(pkg);
main_tests.addPackage(gpu.pkg);
main_tests.addPackage(glfw.pkg);
link(b, main_tests, options);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
// TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939
ensureDependencySubmodule(b.allocator, "examples/libs/zmath") catch unreachable;
ensureDependencySubmodule(b.allocator, "examples/libs/zigimg") catch unreachable;
ensureDependencySubmodule(b.allocator, "examples/assets") catch unreachable;
inline for ([_]ExampleDefinition{
.{ .name = "triangle" },
.{ .name = "boids" },
.{ .name = "rotating-cube", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "two-cubes", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "instanced-cube", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "advanced-gen-texture-light", .packages = &[_]Pkg{Packages.zmath} },
.{ .name = "textured-cube", .packages = &[_]Pkg{ Packages.zmath, Packages.zigimg } },
.{ .name = "fractal-cube", .packages = &[_]Pkg{Packages.zmath} },
}) |example| {
const example_exe = b.addExecutable("example-" ++ example.name, "examples/" ++ example.name ++ "/main.zig");
example_exe.setTarget(target);
example_exe.setBuildMode(mode);
example_exe.addPackage(pkg);
example_exe.addPackage(gpu.pkg);
example_exe.addPackage(glfw.pkg);
inline for (example.packages) |additional_package| {
example_exe.addPackage(additional_package);
}
link(b, example_exe, options);
example_exe.install();
const example_run_cmd = example_exe.run();
example_run_cmd.step.dependOn(b.getInstallStep());
const example_run_step = b.step("run-example-" ++ example.name, "Run the example");
example_run_step.dependOn(&example_run_cmd.step);
}
const shaderexp_exe = b.addExecutable("shaderexp", "shaderexp/main.zig");
shaderexp_exe.setTarget(target);
shaderexp_exe.setBuildMode(mode);
shaderexp_exe.addPackage(pkg);
shaderexp_exe.addPackage(gpu.pkg);
shaderexp_exe.addPackage(glfw.pkg);
link(b, shaderexp_exe, options);
shaderexp_exe.install();
const shaderexp_run_cmd = shaderexp_exe.run();
shaderexp_run_cmd.step.dependOn(b.getInstallStep());
const shaderexp_run_step = b.step("run-shaderexp", "Run shaderexp");
shaderexp_run_step.dependOn(&shaderexp_run_cmd.step);
}
pub const Options = struct {
glfw_options: glfw.Options = .{},
gpu_dawn_options: gpu_dawn.Options = .{},
};
const ExampleDefinition = struct {
name: []const u8,
packages: []const Pkg = &[_]Pkg{},
};
const Packages = struct {
// Declared here because submodule may not be cloned at the time build.zig runs.
const zmath = std.build.Pkg{
.name = "zmath",
.path = .{ .path = "examples/libs/zmath/src/zmath.zig" },
};
const zigimg = std.build.Pkg{
.name = "zigimg",
.path = .{ .path = "examples/libs/zigimg/zigimg.zig" },
};
};
pub const pkg = std.build.Pkg{
.name = "mach",
.path = .{ .path = thisDir() ++ "/src/main.zig" },
.dependencies = &.{ gpu.pkg, glfw.pkg },
};
pub fn link(b: *std.build.Builder, step: *std.build.LibExeObjStep, options: Options) void {
const gpu_options = gpu.Options{
.glfw_options = @bitCast(@import("gpu/libs/mach-glfw/build.zig").Options, options.glfw_options),
.gpu_dawn_options = @bitCast(@import("gpu/libs/mach-gpu-dawn/build.zig").Options, options.gpu_dawn_options),
};
glfw.link(b, step, options.glfw_options);
gpu.link(b, step, gpu_options);
}
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
fn ensureDependencySubmodule(allocator: std.mem.Allocator, path: []const u8) !void {
if (std.process.getEnvVarOwned(allocator, "NO_ENSURE_SUBMODULES")) |no_ensure_submodules| {
if (std.mem.eql(u8, no_ensure_submodules, "true")) return;
} else |_| {}
const child = try std.ChildProcess.init(&.{ "git", "submodule", "update", "--init", path }, allocator);
child.cwd = thisDir();
child.stderr = std.io.getStdErr();
child.stdout = std.io.getStdOut();
_ = try child.spawnAndWait();
}
|
build.zig
|
pub const APOERR_ALREADY_INITIALIZED = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073919));
pub const APOERR_NOT_INITIALIZED = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073918));
pub const APOERR_FORMAT_NOT_SUPPORTED = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073917));
pub const APOERR_INVALID_APO_CLSID = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073916));
pub const APOERR_BUFFERS_OVERLAP = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073915));
pub const APOERR_ALREADY_UNLOCKED = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073914));
pub const APOERR_NUM_CONNECTIONS_INVALID = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073913));
pub const APOERR_INVALID_OUTPUT_MAXFRAMECOUNT = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073912));
pub const APOERR_INVALID_CONNECTION_FORMAT = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073911));
pub const APOERR_APO_LOCKED = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073910));
pub const APOERR_INVALID_COEFFCOUNT = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073909));
pub const APOERR_INVALID_COEFFICIENT = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073908));
pub const APOERR_INVALID_CURVE_PARAM = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073907));
pub const APOERR_INVALID_INPUTID = @import("../../zig.zig").typedConst(HRESULT, @as(i32, -2005073906));
pub const AUDIO_MIN_FRAMERATE = @as(f64, 10);
pub const AUDIO_MAX_FRAMERATE = @as(f64, 384000);
pub const AUDIO_MIN_CHANNELS = @as(u32, 1);
pub const AUDIO_MAX_CHANNELS = @as(u32, 4096);
pub const SID_AudioProcessingObjectRTQueue = Guid.initString("458c1a1f-6899-4c12-99ac-e2e6ac253104");
pub const SID_AudioProcessingObjectLoggingService = Guid.initString("8b8008af-09f9-456e-a173-bdb58499bce7");
pub const AUDIOMEDIATYPE_EQUAL_FORMAT_TYPES = @as(u32, 2);
pub const AUDIOMEDIATYPE_EQUAL_FORMAT_DATA = @as(u32, 4);
pub const AUDIOMEDIATYPE_EQUAL_FORMAT_USER_DATA = @as(u32, 8);
//--------------------------------------------------------------------------------
// Section: Types (44)
//--------------------------------------------------------------------------------
pub const UNCOMPRESSEDAUDIOFORMAT = extern struct {
guidFormatType: Guid,
dwSamplesPerFrame: u32,
dwBytesPerSampleContainer: u32,
dwValidBitsPerSample: u32,
fFramesPerSecond: f32,
dwChannelMask: u32,
};
const IID_IAudioMediaType_Value = Guid.initString("4e997f73-b71f-4798-873b-ed7dfcf15b4d");
pub const IID_IAudioMediaType = &IID_IAudioMediaType_Value;
pub const IAudioMediaType = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
IsCompressedFormat: fn(
self: *const IAudioMediaType,
pfCompressed: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEqual: fn(
self: *const IAudioMediaType,
pIAudioType: ?*IAudioMediaType,
pdwFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAudioFormat: fn(
self: *const IAudioMediaType,
) callconv(@import("std").os.windows.WINAPI) ?*WAVEFORMATEX,
GetUncompressedAudioFormat: fn(
self: *const IAudioMediaType,
pUncompressedAudioFormat: ?*UNCOMPRESSEDAUDIOFORMAT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioMediaType_IsCompressedFormat(self: *const T, pfCompressed: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioMediaType.VTable, self.vtable).IsCompressedFormat(@ptrCast(*const IAudioMediaType, self), pfCompressed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioMediaType_IsEqual(self: *const T, pIAudioType: ?*IAudioMediaType, pdwFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioMediaType.VTable, self.vtable).IsEqual(@ptrCast(*const IAudioMediaType, self), pIAudioType, pdwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioMediaType_GetAudioFormat(self: *const T) callconv(.Inline) ?*WAVEFORMATEX {
return @ptrCast(*const IAudioMediaType.VTable, self.vtable).GetAudioFormat(@ptrCast(*const IAudioMediaType, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioMediaType_GetUncompressedAudioFormat(self: *const T, pUncompressedAudioFormat: ?*UNCOMPRESSEDAUDIOFORMAT) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioMediaType.VTable, self.vtable).GetUncompressedAudioFormat(@ptrCast(*const IAudioMediaType, self), pUncompressedAudioFormat);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const APO_BUFFER_FLAGS = enum(i32) {
INVALID = 0,
VALID = 1,
SILENT = 2,
};
pub const BUFFER_INVALID = APO_BUFFER_FLAGS.INVALID;
pub const BUFFER_VALID = APO_BUFFER_FLAGS.VALID;
pub const BUFFER_SILENT = APO_BUFFER_FLAGS.SILENT;
pub const APO_CONNECTION_PROPERTY = extern struct {
pBuffer: usize,
u32ValidFrameCount: u32,
u32BufferFlags: APO_BUFFER_FLAGS,
u32Signature: u32,
};
pub const APO_CONNECTION_PROPERTY_V2 = extern struct {
property: APO_CONNECTION_PROPERTY,
u64QPCTime: u64,
};
pub const APO_CONNECTION_BUFFER_TYPE = enum(i32) {
ALLOCATED = 0,
EXTERNAL = 1,
DEPENDANT = 2,
};
pub const APO_CONNECTION_BUFFER_TYPE_ALLOCATED = APO_CONNECTION_BUFFER_TYPE.ALLOCATED;
pub const APO_CONNECTION_BUFFER_TYPE_EXTERNAL = APO_CONNECTION_BUFFER_TYPE.EXTERNAL;
pub const APO_CONNECTION_BUFFER_TYPE_DEPENDANT = APO_CONNECTION_BUFFER_TYPE.DEPENDANT;
pub const APO_CONNECTION_DESCRIPTOR = extern struct {
Type: APO_CONNECTION_BUFFER_TYPE,
pBuffer: usize,
u32MaxFrameCount: u32,
pFormat: ?*IAudioMediaType,
u32Signature: u32,
};
pub const APO_FLAG = enum(i32) {
NONE = 0,
INPLACE = 1,
SAMPLESPERFRAME_MUST_MATCH = 2,
FRAMESPERSECOND_MUST_MATCH = 4,
BITSPERSAMPLE_MUST_MATCH = 8,
MIXER = 16,
DEFAULT = 14,
};
pub const APO_FLAG_NONE = APO_FLAG.NONE;
pub const APO_FLAG_INPLACE = APO_FLAG.INPLACE;
pub const APO_FLAG_SAMPLESPERFRAME_MUST_MATCH = APO_FLAG.SAMPLESPERFRAME_MUST_MATCH;
pub const APO_FLAG_FRAMESPERSECOND_MUST_MATCH = APO_FLAG.FRAMESPERSECOND_MUST_MATCH;
pub const APO_FLAG_BITSPERSAMPLE_MUST_MATCH = APO_FLAG.BITSPERSAMPLE_MUST_MATCH;
pub const APO_FLAG_MIXER = APO_FLAG.MIXER;
pub const APO_FLAG_DEFAULT = APO_FLAG.DEFAULT;
pub const APO_REG_PROPERTIES = extern struct {
clsid: Guid,
Flags: APO_FLAG,
szFriendlyName: [256]u16,
szCopyrightInfo: [256]u16,
u32MajorVersion: u32,
u32MinorVersion: u32,
u32MinInputConnections: u32,
u32MaxInputConnections: u32,
u32MinOutputConnections: u32,
u32MaxOutputConnections: u32,
u32MaxInstances: u32,
u32NumAPOInterfaces: u32,
iidAPOInterfaceList: [1]Guid,
};
pub const APOInitBaseStruct = extern struct {
cbSize: u32,
clsid: Guid,
};
pub const AUDIO_FLOW_TYPE = enum(i32) {
LL = 0,
SH = 1,
};
pub const AUDIO_FLOW_PULL = AUDIO_FLOW_TYPE.LL;
pub const AUDIO_FLOW_PUSH = AUDIO_FLOW_TYPE.SH;
pub const EAudioConstriction = enum(i32) {
Off = 0,
@"48_16" = 1,
@"44_16" = 2,
@"14_14" = 3,
Mute = 4,
};
pub const eAudioConstrictionOff = EAudioConstriction.Off;
pub const eAudioConstriction48_16 = EAudioConstriction.@"48_16";
pub const eAudioConstriction44_16 = EAudioConstriction.@"44_16";
pub const eAudioConstriction14_14 = EAudioConstriction.@"14_14";
pub const eAudioConstrictionMute = EAudioConstriction.Mute;
const IID_IAudioProcessingObjectRT_Value = Guid.initString("9e1d6a6d-ddbc-4e95-a4c7-ad64ba37846c");
pub const IID_IAudioProcessingObjectRT = &IID_IAudioProcessingObjectRT_Value;
pub const IAudioProcessingObjectRT = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
APOProcess: fn(
self: *const IAudioProcessingObjectRT,
u32NumInputConnections: u32,
ppInputConnections: ?*?*APO_CONNECTION_PROPERTY,
u32NumOutputConnections: u32,
ppOutputConnections: ?*?*APO_CONNECTION_PROPERTY,
) callconv(@import("std").os.windows.WINAPI) void,
CalcInputFrames: fn(
self: *const IAudioProcessingObjectRT,
u32OutputFrameCount: u32,
) callconv(@import("std").os.windows.WINAPI) u32,
CalcOutputFrames: fn(
self: *const IAudioProcessingObjectRT,
u32InputFrameCount: u32,
) callconv(@import("std").os.windows.WINAPI) u32,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectRT_APOProcess(self: *const T, u32NumInputConnections: u32, ppInputConnections: ?*?*APO_CONNECTION_PROPERTY, u32NumOutputConnections: u32, ppOutputConnections: ?*?*APO_CONNECTION_PROPERTY) callconv(.Inline) void {
return @ptrCast(*const IAudioProcessingObjectRT.VTable, self.vtable).APOProcess(@ptrCast(*const IAudioProcessingObjectRT, self), u32NumInputConnections, ppInputConnections, u32NumOutputConnections, ppOutputConnections);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectRT_CalcInputFrames(self: *const T, u32OutputFrameCount: u32) callconv(.Inline) u32 {
return @ptrCast(*const IAudioProcessingObjectRT.VTable, self.vtable).CalcInputFrames(@ptrCast(*const IAudioProcessingObjectRT, self), u32OutputFrameCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectRT_CalcOutputFrames(self: *const T, u32InputFrameCount: u32) callconv(.Inline) u32 {
return @ptrCast(*const IAudioProcessingObjectRT.VTable, self.vtable).CalcOutputFrames(@ptrCast(*const IAudioProcessingObjectRT, self), u32InputFrameCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IAudioProcessingObjectVBR_Value = Guid.initString("7ba1db8f-78ad-49cd-9591-f79d80a17c81");
pub const IID_IAudioProcessingObjectVBR = &IID_IAudioProcessingObjectVBR_Value;
pub const IAudioProcessingObjectVBR = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CalcMaxInputFrames: fn(
self: *const IAudioProcessingObjectVBR,
u32MaxOutputFrameCount: u32,
pu32InputFrameCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CalcMaxOutputFrames: fn(
self: *const IAudioProcessingObjectVBR,
u32MaxInputFrameCount: u32,
pu32OutputFrameCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectVBR_CalcMaxInputFrames(self: *const T, u32MaxOutputFrameCount: u32, pu32InputFrameCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObjectVBR.VTable, self.vtable).CalcMaxInputFrames(@ptrCast(*const IAudioProcessingObjectVBR, self), u32MaxOutputFrameCount, pu32InputFrameCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectVBR_CalcMaxOutputFrames(self: *const T, u32MaxInputFrameCount: u32, pu32OutputFrameCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObjectVBR.VTable, self.vtable).CalcMaxOutputFrames(@ptrCast(*const IAudioProcessingObjectVBR, self), u32MaxInputFrameCount, pu32OutputFrameCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IAudioProcessingObjectConfiguration_Value = Guid.initString("0e5ed805-aba6-49c3-8f9a-2b8c889c4fa8");
pub const IID_IAudioProcessingObjectConfiguration = &IID_IAudioProcessingObjectConfiguration_Value;
pub const IAudioProcessingObjectConfiguration = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
LockForProcess: fn(
self: *const IAudioProcessingObjectConfiguration,
u32NumInputConnections: u32,
ppInputConnections: ?*?*APO_CONNECTION_DESCRIPTOR,
u32NumOutputConnections: u32,
ppOutputConnections: ?*?*APO_CONNECTION_DESCRIPTOR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnlockForProcess: fn(
self: *const IAudioProcessingObjectConfiguration,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectConfiguration_LockForProcess(self: *const T, u32NumInputConnections: u32, ppInputConnections: ?*?*APO_CONNECTION_DESCRIPTOR, u32NumOutputConnections: u32, ppOutputConnections: ?*?*APO_CONNECTION_DESCRIPTOR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObjectConfiguration.VTable, self.vtable).LockForProcess(@ptrCast(*const IAudioProcessingObjectConfiguration, self), u32NumInputConnections, ppInputConnections, u32NumOutputConnections, ppOutputConnections);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectConfiguration_UnlockForProcess(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObjectConfiguration.VTable, self.vtable).UnlockForProcess(@ptrCast(*const IAudioProcessingObjectConfiguration, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IAudioProcessingObject_Value = Guid.initString("fd7f2b29-24d0-4b5c-b177-592c39f9ca10");
pub const IID_IAudioProcessingObject = &IID_IAudioProcessingObject_Value;
pub const IAudioProcessingObject = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Reset: fn(
self: *const IAudioProcessingObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLatency: fn(
self: *const IAudioProcessingObject,
pTime: ?*i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRegistrationProperties: fn(
self: *const IAudioProcessingObject,
ppRegProps: ?*?*APO_REG_PROPERTIES,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Initialize: fn(
self: *const IAudioProcessingObject,
cbDataSize: u32,
pbyData: [*:0]u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsInputFormatSupported: fn(
self: *const IAudioProcessingObject,
pOppositeFormat: ?*IAudioMediaType,
pRequestedInputFormat: ?*IAudioMediaType,
ppSupportedInputFormat: ?*?*IAudioMediaType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsOutputFormatSupported: fn(
self: *const IAudioProcessingObject,
pOppositeFormat: ?*IAudioMediaType,
pRequestedOutputFormat: ?*IAudioMediaType,
ppSupportedOutputFormat: ?*?*IAudioMediaType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInputChannelCount: fn(
self: *const IAudioProcessingObject,
pu32ChannelCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObject_Reset(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObject.VTable, self.vtable).Reset(@ptrCast(*const IAudioProcessingObject, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObject_GetLatency(self: *const T, pTime: ?*i64) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObject.VTable, self.vtable).GetLatency(@ptrCast(*const IAudioProcessingObject, self), pTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObject_GetRegistrationProperties(self: *const T, ppRegProps: ?*?*APO_REG_PROPERTIES) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObject.VTable, self.vtable).GetRegistrationProperties(@ptrCast(*const IAudioProcessingObject, self), ppRegProps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObject_Initialize(self: *const T, cbDataSize: u32, pbyData: [*:0]u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObject.VTable, self.vtable).Initialize(@ptrCast(*const IAudioProcessingObject, self), cbDataSize, pbyData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObject_IsInputFormatSupported(self: *const T, pOppositeFormat: ?*IAudioMediaType, pRequestedInputFormat: ?*IAudioMediaType, ppSupportedInputFormat: ?*?*IAudioMediaType) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObject.VTable, self.vtable).IsInputFormatSupported(@ptrCast(*const IAudioProcessingObject, self), pOppositeFormat, pRequestedInputFormat, ppSupportedInputFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObject_IsOutputFormatSupported(self: *const T, pOppositeFormat: ?*IAudioMediaType, pRequestedOutputFormat: ?*IAudioMediaType, ppSupportedOutputFormat: ?*?*IAudioMediaType) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObject.VTable, self.vtable).IsOutputFormatSupported(@ptrCast(*const IAudioProcessingObject, self), pOppositeFormat, pRequestedOutputFormat, ppSupportedOutputFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObject_GetInputChannelCount(self: *const T, pu32ChannelCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObject.VTable, self.vtable).GetInputChannelCount(@ptrCast(*const IAudioProcessingObject, self), pu32ChannelCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IAudioDeviceModulesClient_Value = Guid.initString("98f37dac-d0b6-49f5-896a-aa4d169a4c48");
pub const IID_IAudioDeviceModulesClient = &IID_IAudioDeviceModulesClient_Value;
pub const IAudioDeviceModulesClient = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetAudioDeviceModulesManager: fn(
self: *const IAudioDeviceModulesClient,
pAudioDeviceModulesManager: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioDeviceModulesClient_SetAudioDeviceModulesManager(self: *const T, pAudioDeviceModulesManager: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioDeviceModulesClient.VTable, self.vtable).SetAudioDeviceModulesManager(@ptrCast(*const IAudioDeviceModulesClient, self), pAudioDeviceModulesManager);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const FNAPONOTIFICATIONCALLBACK = fn(
pProperties: ?*APO_REG_PROPERTIES,
pvRefData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
const IID_IAudioSystemEffects_Value = Guid.initString("5fa00f27-add6-499a-8a9d-6b98521fa75b");
pub const IID_IAudioSystemEffects = &IID_IAudioSystemEffects_Value;
pub const IAudioSystemEffects = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IAudioSystemEffects2_Value = Guid.initString("bafe99d2-7436-44ce-9e0e-4d89afbfff56");
pub const IID_IAudioSystemEffects2 = &IID_IAudioSystemEffects2_Value;
pub const IAudioSystemEffects2 = extern struct {
pub const VTable = extern struct {
base: IAudioSystemEffects.VTable,
GetEffectsList: fn(
self: *const IAudioSystemEffects2,
ppEffectsIds: ?*?*Guid,
pcEffects: ?*u32,
Event: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IAudioSystemEffects.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioSystemEffects2_GetEffectsList(self: *const T, ppEffectsIds: ?*?*Guid, pcEffects: ?*u32, Event: ?HANDLE) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioSystemEffects2.VTable, self.vtable).GetEffectsList(@ptrCast(*const IAudioSystemEffects2, self), ppEffectsIds, pcEffects, Event);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IAudioSystemEffectsCustomFormats_Value = Guid.initString("b1176e34-bb7f-4f05-bebd-1b18a534e097");
pub const IID_IAudioSystemEffectsCustomFormats = &IID_IAudioSystemEffectsCustomFormats_Value;
pub const IAudioSystemEffectsCustomFormats = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetFormatCount: fn(
self: *const IAudioSystemEffectsCustomFormats,
pcFormats: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFormat: fn(
self: *const IAudioSystemEffectsCustomFormats,
nFormat: u32,
ppFormat: ?*?*IAudioMediaType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFormatRepresentation: fn(
self: *const IAudioSystemEffectsCustomFormats,
nFormat: u32,
ppwstrFormatRep: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioSystemEffectsCustomFormats_GetFormatCount(self: *const T, pcFormats: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioSystemEffectsCustomFormats.VTable, self.vtable).GetFormatCount(@ptrCast(*const IAudioSystemEffectsCustomFormats, self), pcFormats);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioSystemEffectsCustomFormats_GetFormat(self: *const T, nFormat: u32, ppFormat: ?*?*IAudioMediaType) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioSystemEffectsCustomFormats.VTable, self.vtable).GetFormat(@ptrCast(*const IAudioSystemEffectsCustomFormats, self), nFormat, ppFormat);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioSystemEffectsCustomFormats_GetFormatRepresentation(self: *const T, nFormat: u32, ppwstrFormatRep: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioSystemEffectsCustomFormats.VTable, self.vtable).GetFormatRepresentation(@ptrCast(*const IAudioSystemEffectsCustomFormats, self), nFormat, ppwstrFormatRep);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IApoAuxiliaryInputConfiguration_Value = Guid.initString("4ceb0aab-fa19-48ed-a857-87771ae1b768");
pub const IID_IApoAuxiliaryInputConfiguration = &IID_IApoAuxiliaryInputConfiguration_Value;
pub const IApoAuxiliaryInputConfiguration = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AddAuxiliaryInput: fn(
self: *const IApoAuxiliaryInputConfiguration,
dwInputId: u32,
cbDataSize: u32,
pbyData: [*:0]u8,
pInputConnection: ?*APO_CONNECTION_DESCRIPTOR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveAuxiliaryInput: fn(
self: *const IApoAuxiliaryInputConfiguration,
dwInputId: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsInputFormatSupported: fn(
self: *const IApoAuxiliaryInputConfiguration,
pRequestedInputFormat: ?*IAudioMediaType,
ppSupportedInputFormat: ?*?*IAudioMediaType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApoAuxiliaryInputConfiguration_AddAuxiliaryInput(self: *const T, dwInputId: u32, cbDataSize: u32, pbyData: [*:0]u8, pInputConnection: ?*APO_CONNECTION_DESCRIPTOR) callconv(.Inline) HRESULT {
return @ptrCast(*const IApoAuxiliaryInputConfiguration.VTable, self.vtable).AddAuxiliaryInput(@ptrCast(*const IApoAuxiliaryInputConfiguration, self), dwInputId, cbDataSize, pbyData, pInputConnection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApoAuxiliaryInputConfiguration_RemoveAuxiliaryInput(self: *const T, dwInputId: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IApoAuxiliaryInputConfiguration.VTable, self.vtable).RemoveAuxiliaryInput(@ptrCast(*const IApoAuxiliaryInputConfiguration, self), dwInputId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApoAuxiliaryInputConfiguration_IsInputFormatSupported(self: *const T, pRequestedInputFormat: ?*IAudioMediaType, ppSupportedInputFormat: ?*?*IAudioMediaType) callconv(.Inline) HRESULT {
return @ptrCast(*const IApoAuxiliaryInputConfiguration.VTable, self.vtable).IsInputFormatSupported(@ptrCast(*const IApoAuxiliaryInputConfiguration, self), pRequestedInputFormat, ppSupportedInputFormat);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IApoAuxiliaryInputRT_Value = Guid.initString("f851809c-c177-49a0-b1b2-b66f017943ab");
pub const IID_IApoAuxiliaryInputRT = &IID_IApoAuxiliaryInputRT_Value;
pub const IApoAuxiliaryInputRT = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
AcceptInput: fn(
self: *const IApoAuxiliaryInputRT,
dwInputId: u32,
pInputConnection: ?*const APO_CONNECTION_PROPERTY,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IApoAuxiliaryInputRT_AcceptInput(self: *const T, dwInputId: u32, pInputConnection: ?*const APO_CONNECTION_PROPERTY) callconv(.Inline) void {
return @ptrCast(*const IApoAuxiliaryInputRT.VTable, self.vtable).AcceptInput(@ptrCast(*const IApoAuxiliaryInputRT, self), dwInputId, pInputConnection);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IApoAcousticEchoCancellation_Value = Guid.initString("25385759-3236-4101-a943-25693dfb5d2d");
pub const IID_IApoAcousticEchoCancellation = &IID_IApoAcousticEchoCancellation_Value;
pub const IApoAcousticEchoCancellation = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
pub const APOInitSystemEffects = extern struct {
APOInit: APOInitBaseStruct,
pAPOEndpointProperties: ?*IPropertyStore,
pAPOSystemEffectsProperties: ?*IPropertyStore,
pReserved: ?*anyopaque,
pDeviceCollection: ?*IMMDeviceCollection,
};
pub const APOInitSystemEffects2 = extern struct {
APOInit: APOInitBaseStruct,
pAPOEndpointProperties: ?*IPropertyStore,
pAPOSystemEffectsProperties: ?*IPropertyStore,
pReserved: ?*anyopaque,
pDeviceCollection: ?*IMMDeviceCollection,
nSoftwareIoDeviceInCollection: u32,
nSoftwareIoConnectorIndex: u32,
AudioProcessingMode: Guid,
InitializeForDiscoveryOnly: BOOL,
};
pub const AudioFXExtensionParams = extern struct {
AddPageParam: LPARAM,
pwstrEndpointID: ?PWSTR,
pFxProperties: ?*IPropertyStore,
};
pub const AUDIO_SYSTEMEFFECT_STATE = enum(i32) {
FF = 0,
N = 1,
};
pub const AUDIO_SYSTEMEFFECT_STATE_OFF = AUDIO_SYSTEMEFFECT_STATE.FF;
pub const AUDIO_SYSTEMEFFECT_STATE_ON = AUDIO_SYSTEMEFFECT_STATE.N;
pub const AUDIO_SYSTEMEFFECT = extern struct {
id: Guid,
canSetState: BOOL,
state: AUDIO_SYSTEMEFFECT_STATE,
};
const IID_IAudioSystemEffects3_Value = Guid.initString("c58b31cd-fc6a-4255-bc1f-ad29bb0a4a17");
pub const IID_IAudioSystemEffects3 = &IID_IAudioSystemEffects3_Value;
pub const IAudioSystemEffects3 = extern struct {
pub const VTable = extern struct {
base: IAudioSystemEffects2.VTable,
GetControllableSystemEffectsList: fn(
self: *const IAudioSystemEffects3,
effects: ?*?*AUDIO_SYSTEMEFFECT,
numEffects: ?*u32,
event: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAudioSystemEffectState: fn(
self: *const IAudioSystemEffects3,
effectId: Guid,
state: AUDIO_SYSTEMEFFECT_STATE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IAudioSystemEffects2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioSystemEffects3_GetControllableSystemEffectsList(self: *const T, effects: ?*?*AUDIO_SYSTEMEFFECT, numEffects: ?*u32, event: ?HANDLE) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioSystemEffects3.VTable, self.vtable).GetControllableSystemEffectsList(@ptrCast(*const IAudioSystemEffects3, self), effects, numEffects, event);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioSystemEffects3_SetAudioSystemEffectState(self: *const T, effectId: Guid, state: AUDIO_SYSTEMEFFECT_STATE) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioSystemEffects3.VTable, self.vtable).SetAudioSystemEffectState(@ptrCast(*const IAudioSystemEffects3, self), effectId, state);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const APOInitSystemEffects3 = extern struct {
APOInit: APOInitBaseStruct,
pAPOEndpointProperties: ?*IPropertyStore,
pServiceProvider: ?*IServiceProvider,
pDeviceCollection: ?*IMMDeviceCollection,
nSoftwareIoDeviceInCollection: u32,
nSoftwareIoConnectorIndex: u32,
AudioProcessingMode: Guid,
InitializeForDiscoveryOnly: BOOL,
};
const IID_IAudioProcessingObjectRTQueueService_Value = Guid.initString("acd65e2f-955b-4b57-b9bf-ac297bb752c9");
pub const IID_IAudioProcessingObjectRTQueueService = &IID_IAudioProcessingObjectRTQueueService_Value;
pub const IAudioProcessingObjectRTQueueService = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetRealTimeWorkQueue: fn(
self: *const IAudioProcessingObjectRTQueueService,
workQueueId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectRTQueueService_GetRealTimeWorkQueue(self: *const T, workQueueId: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObjectRTQueueService.VTable, self.vtable).GetRealTimeWorkQueue(@ptrCast(*const IAudioProcessingObjectRTQueueService, self), workQueueId);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const APO_LOG_LEVEL = enum(i32) {
ALWAYS = 0,
CRITICAL = 1,
ERROR = 2,
WARNING = 3,
INFO = 4,
VERBOSE = 5,
};
pub const APO_LOG_LEVEL_ALWAYS = APO_LOG_LEVEL.ALWAYS;
pub const APO_LOG_LEVEL_CRITICAL = APO_LOG_LEVEL.CRITICAL;
pub const APO_LOG_LEVEL_ERROR = APO_LOG_LEVEL.ERROR;
pub const APO_LOG_LEVEL_WARNING = APO_LOG_LEVEL.WARNING;
pub const APO_LOG_LEVEL_INFO = APO_LOG_LEVEL.INFO;
pub const APO_LOG_LEVEL_VERBOSE = APO_LOG_LEVEL.VERBOSE;
const IID_IAudioProcessingObjectLoggingService_Value = Guid.initString("698f0107-1745-4708-95a5-d84478a62a65");
pub const IID_IAudioProcessingObjectLoggingService = &IID_IAudioProcessingObjectLoggingService_Value;
pub const IAudioProcessingObjectLoggingService = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ApoLog: fn(
self: *const IAudioProcessingObjectLoggingService,
level: APO_LOG_LEVEL,
format: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectLoggingService_ApoLog(self: *const T, level: APO_LOG_LEVEL, format: ?[*:0]const u16) callconv(.Inline) void {
return @ptrCast(*const IAudioProcessingObjectLoggingService.VTable, self.vtable).ApoLog(@ptrCast(*const IAudioProcessingObjectLoggingService, self), level, format);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const APO_NOTIFICATION_TYPE = enum(i32) {
NONE = 0,
ENDPOINT_VOLUME = 1,
ENDPOINT_PROPERTY_CHANGE = 2,
SYSTEM_EFFECTS_PROPERTY_CHANGE = 3,
};
pub const APO_NOTIFICATION_TYPE_NONE = APO_NOTIFICATION_TYPE.NONE;
pub const APO_NOTIFICATION_TYPE_ENDPOINT_VOLUME = APO_NOTIFICATION_TYPE.ENDPOINT_VOLUME;
pub const APO_NOTIFICATION_TYPE_ENDPOINT_PROPERTY_CHANGE = APO_NOTIFICATION_TYPE.ENDPOINT_PROPERTY_CHANGE;
pub const APO_NOTIFICATION_TYPE_SYSTEM_EFFECTS_PROPERTY_CHANGE = APO_NOTIFICATION_TYPE.SYSTEM_EFFECTS_PROPERTY_CHANGE;
pub const AUDIO_ENDPOINT_VOLUME_CHANGE_NOTIFICATION = extern struct {
endpoint: ?*IMMDevice,
volume: ?*AUDIO_VOLUME_NOTIFICATION_DATA,
};
pub const AUDIO_ENDPOINT_PROPERTY_CHANGE_NOTIFICATION = extern struct {
endpoint: ?*IMMDevice,
propertyStore: ?*IPropertyStore,
propertyKey: PROPERTYKEY,
};
pub const AUDIO_SYSTEMEFFECTS_PROPERTY_CHANGE_NOTIFICATION = extern struct {
endpoint: ?*IMMDevice,
propertyStoreContext: Guid,
propertyStoreType: __MIDL___MIDL_itf_mmdeviceapi_0000_0008_0002,
propertyStore: ?*IPropertyStore,
propertyKey: PROPERTYKEY,
};
pub const APO_NOTIFICATION = extern struct {
type: APO_NOTIFICATION_TYPE,
Anonymous: extern union {
audioEndpointVolumeChange: AUDIO_ENDPOINT_VOLUME_CHANGE_NOTIFICATION,
audioEndpointPropertyChange: AUDIO_ENDPOINT_PROPERTY_CHANGE_NOTIFICATION,
audioSystemEffectsPropertyChange: AUDIO_SYSTEMEFFECTS_PROPERTY_CHANGE_NOTIFICATION,
},
};
pub const AUDIO_ENDPOINT_VOLUME_APO_NOTIFICATION_DESCRIPTOR = extern struct {
device: ?*IMMDevice,
};
pub const AUDIO_ENDPOINT_PROPERTY_CHANGE_APO_NOTIFICATION_DESCRIPTOR = extern struct {
device: ?*IMMDevice,
};
pub const AUDIO_SYSTEMEFFECTS_PROPERTY_CHANGE_APO_NOTIFICATION_DESCRIPTOR = extern struct {
device: ?*IMMDevice,
propertyStoreContext: Guid,
};
pub const APO_NOTIFICATION_DESCRIPTOR = extern struct {
type: APO_NOTIFICATION_TYPE,
Anonymous: extern union {
audioEndpointVolume: AUDIO_ENDPOINT_VOLUME_APO_NOTIFICATION_DESCRIPTOR,
audioEndpointPropertyChange: AUDIO_ENDPOINT_PROPERTY_CHANGE_APO_NOTIFICATION_DESCRIPTOR,
audioSystemEffectsPropertyChange: AUDIO_SYSTEMEFFECTS_PROPERTY_CHANGE_APO_NOTIFICATION_DESCRIPTOR,
},
};
const IID_IAudioProcessingObjectNotifications_Value = Guid.initString("56b0c76f-02fd-4b21-a52e-9f8219fc86e4");
pub const IID_IAudioProcessingObjectNotifications = &IID_IAudioProcessingObjectNotifications_Value;
pub const IAudioProcessingObjectNotifications = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetApoNotificationRegistrationInfo: fn(
self: *const IAudioProcessingObjectNotifications,
apoNotifications: [*]?*APO_NOTIFICATION_DESCRIPTOR,
count: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandleNotification: fn(
self: *const IAudioProcessingObjectNotifications,
apoNotification: ?*APO_NOTIFICATION,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectNotifications_GetApoNotificationRegistrationInfo(self: *const T, apoNotifications: [*]?*APO_NOTIFICATION_DESCRIPTOR, count: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IAudioProcessingObjectNotifications.VTable, self.vtable).GetApoNotificationRegistrationInfo(@ptrCast(*const IAudioProcessingObjectNotifications, self), apoNotifications, count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IAudioProcessingObjectNotifications_HandleNotification(self: *const T, apoNotification: ?*APO_NOTIFICATION) callconv(.Inline) void {
return @ptrCast(*const IAudioProcessingObjectNotifications.VTable, self.vtable).HandleNotification(@ptrCast(*const IAudioProcessingObjectNotifications, self), apoNotification);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (15)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const __MIDL___MIDL_itf_mmdeviceapi_0000_0008_0002 = @import("../../media/audio.zig").__MIDL___MIDL_itf_mmdeviceapi_0000_0008_0002;
const AUDIO_VOLUME_NOTIFICATION_DATA = @import("../../media/audio.zig").AUDIO_VOLUME_NOTIFICATION_DATA;
const BOOL = @import("../../foundation.zig").BOOL;
const HANDLE = @import("../../foundation.zig").HANDLE;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IMMDevice = @import("../../media/audio.zig").IMMDevice;
const IMMDeviceCollection = @import("../../media/audio.zig").IMMDeviceCollection;
const IPropertyStore = @import("../../ui/shell/properties_system.zig").IPropertyStore;
const IServiceProvider = @import("../../system/com.zig").IServiceProvider;
const IUnknown = @import("../../system/com.zig").IUnknown;
const LPARAM = @import("../../foundation.zig").LPARAM;
const PROPERTYKEY = @import("../../ui/shell/properties_system.zig").PROPERTYKEY;
const PWSTR = @import("../../foundation.zig").PWSTR;
const WAVEFORMATEX = @import("../../media/audio.zig").WAVEFORMATEX;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "FNAPONOTIFICATIONCALLBACK")) { _ = FNAPONOTIFICATIONCALLBACK; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
win32/media/audio/apo.zig
|
const std = @import("std");
const assert = std.debug.assert;
const log = std.log.scoped(.state_machine);
usingnamespace @import("tigerbeetle.zig");
const HashMapAccounts = std.AutoHashMap(u128, Account);
const HashMapTransfers = std.AutoHashMap(u128, Transfer);
const HashMapCommits = std.AutoHashMap(u128, Commit);
pub const StateMachine = struct {
pub const Operation = enum(u8) {
/// Operations reserved by VR protocol (for all state machines):
reserved,
init,
register,
/// Operations exported by TigerBeetle:
create_accounts,
create_transfers,
commit_transfers,
lookup_accounts,
pub fn jsonStringify(self: Command, options: StringifyOptions, writer: anytype) !void {
try std.fmt.format(writer, "\"{}\"", .{@tagName(self)});
}
};
allocator: *std.mem.Allocator,
prepare_timestamp: u64,
commit_timestamp: u64,
accounts: HashMapAccounts,
transfers: HashMapTransfers,
commits: HashMapCommits,
pub fn init(
allocator: *std.mem.Allocator,
accounts_max: usize,
transfers_max: usize,
commits_max: usize,
) !StateMachine {
var accounts = HashMapAccounts.init(allocator);
errdefer accounts.deinit();
try accounts.ensureCapacity(@intCast(u32, accounts_max));
var transfers = HashMapTransfers.init(allocator);
errdefer transfers.deinit();
try transfers.ensureCapacity(@intCast(u32, transfers_max));
var commits = HashMapCommits.init(allocator);
errdefer commits.deinit();
try commits.ensureCapacity(@intCast(u32, commits_max));
// TODO After recovery, set prepare_timestamp max(wall clock, op timestamp).
// TODO After recovery, set commit_timestamp max(wall clock, commit timestamp).
return StateMachine{
.allocator = allocator,
.prepare_timestamp = 0,
.commit_timestamp = 0,
.accounts = accounts,
.transfers = transfers,
.commits = commits,
};
}
pub fn deinit(self: *StateMachine) void {
self.accounts.deinit();
self.transfers.deinit();
self.commits.deinit();
}
pub fn Event(comptime operation: Operation) type {
return switch (operation) {
.create_accounts => Account,
.create_transfers => Transfer,
.commit_transfers => Commit,
.lookup_accounts => u128,
else => unreachable,
};
}
pub fn Result(comptime operation: Operation) type {
return switch (operation) {
.create_accounts => CreateAccountsResult,
.create_transfers => CreateTransfersResult,
.commit_transfers => CommitTransfersResult,
.lookup_accounts => Account,
else => unreachable,
};
}
pub fn prepare(self: *StateMachine, realtime: i64, operation: Operation, input: []u8) void {
switch (operation) {
.init => unreachable,
.register => {},
.create_accounts => self.prepare_timestamps(realtime, .create_accounts, input),
.create_transfers => self.prepare_timestamps(realtime, .create_transfers, input),
.commit_transfers => self.prepare_timestamps(realtime, .commit_transfers, input),
.lookup_accounts => {},
else => unreachable,
}
}
fn prepare_timestamps(
self: *StateMachine,
realtime: i64,
comptime operation: Operation,
input: []u8,
) void {
// Guard against the wall clock going backwards by taking the max with timestamps issued:
self.prepare_timestamp = std.math.max(
// The cluster `commit_timestamp` may be ahead of our `prepare_timestamp` because this
// may be our first prepare as a recently elected leader:
std.math.max(self.prepare_timestamp, self.commit_timestamp) + 1,
@intCast(u64, realtime),
);
assert(self.prepare_timestamp > self.commit_timestamp);
var sum_reserved_timestamps: usize = 0;
var events = std.mem.bytesAsSlice(Event(operation), input);
for (events) |*event| {
sum_reserved_timestamps += event.timestamp;
self.prepare_timestamp += 1;
event.timestamp = self.prepare_timestamp;
}
// The client is responsible for ensuring that timestamps are reserved:
// Use a single branch condition to detect non-zero reserved timestamps.
// Summing then branching once is faster than branching every iteration of the loop.
assert(sum_reserved_timestamps == 0);
}
pub fn commit(
self: *StateMachine,
client: u128,
operation: Operation,
input: []const u8,
output: []u8,
) usize {
return switch (operation) {
.init => unreachable,
.register => 0,
.create_accounts => self.execute(.create_accounts, input, output),
.create_transfers => self.execute(.create_transfers, input, output),
.commit_transfers => self.execute(.commit_transfers, input, output),
.lookup_accounts => self.execute_lookup_accounts(input, output),
else => unreachable,
};
}
fn execute(
self: *StateMachine,
comptime operation: Operation,
input: []const u8,
output: []u8,
) usize {
comptime assert(operation != .lookup_accounts);
const events = std.mem.bytesAsSlice(Event(operation), input);
var results = std.mem.bytesAsSlice(Result(operation), output);
var count: usize = 0;
var chain: ?usize = null;
var chain_broken = false;
for (events) |event, index| {
if (event.flags.linked and chain == null) {
chain = index;
assert(chain_broken == false);
}
const result = if (chain_broken) .linked_event_failed else switch (operation) {
.create_accounts => self.create_account(event),
.create_transfers => self.create_transfer(event),
.commit_transfers => self.commit_transfer(event),
else => unreachable,
};
log.debug("{s} {}/{}: {}: {}", .{
@tagName(operation),
index + 1,
events.len,
result,
event,
});
if (result != .ok) {
if (chain) |chain_start_index| {
if (!chain_broken) {
chain_broken = true;
// Rollback events in LIFO order, excluding this event that broke the chain:
self.rollback(operation, input, chain_start_index, index);
// Add errors for rolled back events in FIFO order:
var chain_index = chain_start_index;
while (chain_index < index) : (chain_index += 1) {
results[count] = .{
.index = @intCast(u32, chain_index),
.result = .linked_event_failed,
};
count += 1;
}
} else {
assert(result == .linked_event_failed);
}
}
results[count] = .{ .index = @intCast(u32, index), .result = result };
count += 1;
}
if (!event.flags.linked and chain != null) {
chain = null;
chain_broken = false;
}
}
// TODO client.zig: Validate that batch chains are always well-formed and closed.
// This is programming error and we should raise an exception for this in the client ASAP.
assert(chain == null);
assert(chain_broken == false);
return @sizeOf(Result(operation)) * count;
}
fn rollback(
self: *StateMachine,
comptime operation: Operation,
input: []const u8,
chain_start_index: usize,
chain_error_index: usize,
) void {
const events = std.mem.bytesAsSlice(Event(operation), input);
// We commit events in FIFO order.
// We must therefore rollback events in LIFO order with a reverse loop.
// We do not rollback `self.commit_timestamp` to ensure that subsequent events are
// timestamped correctly.
var index = chain_error_index;
while (index > chain_start_index) {
index -= 1;
assert(index >= chain_start_index);
assert(index < chain_error_index);
const event = events[index];
assert(event.timestamp <= self.commit_timestamp);
switch (operation) {
.create_accounts => self.create_account_rollback(event),
.create_transfers => self.create_transfer_rollback(event),
.commit_transfers => self.commit_transfer_rollback(event),
else => unreachable,
}
log.debug("{s} {}/{}: rollback(): {}", .{
@tagName(operation),
index + 1,
events.len,
event,
});
}
assert(index == chain_start_index);
}
fn execute_lookup_accounts(self: *StateMachine, input: []const u8, output: []u8) usize {
const batch = std.mem.bytesAsSlice(u128, input);
var output_len = @divFloor(output.len, @sizeOf(Account)) * @sizeOf(Account);
var results = std.mem.bytesAsSlice(Account, output[0..output_len]);
var results_count: usize = 0;
for (batch) |id, index| {
if (self.get_account(id)) |result| {
results[results_count] = result.*;
results_count += 1;
}
}
return results_count * @sizeOf(Account);
}
fn create_account(self: *StateMachine, a: Account) CreateAccountResult {
assert(a.timestamp > self.commit_timestamp);
if (!zeroed_48_bytes(a.reserved)) return .reserved_field;
if (a.flags.padding != 0) return .reserved_flag_padding;
// Opening balances may never exceed limits:
if (a.debits_exceed_credits(0)) return .exceeds_credits;
if (a.credits_exceed_debits(0)) return .exceeds_debits;
var insert = self.accounts.getOrPutAssumeCapacity(a.id);
if (insert.found_existing) {
const exists = insert.value_ptr.*;
if (exists.unit != a.unit) return .exists_with_different_unit;
if (exists.code != a.code) return .exists_with_different_code;
if (@bitCast(u32, exists.flags) != @bitCast(u32, a.flags)) {
return .exists_with_different_flags;
}
if (exists.user_data != a.user_data) return .exists_with_different_user_data;
if (!equal_48_bytes(exists.reserved, a.reserved)) {
return .exists_with_different_reserved_field;
}
return .exists;
} else {
insert.value_ptr.* = a;
self.commit_timestamp = a.timestamp;
return .ok;
}
}
fn create_account_rollback(self: *StateMachine, a: Account) void {
assert(self.accounts.remove(a.id));
}
fn create_transfer(self: *StateMachine, t: Transfer) CreateTransferResult {
assert(t.timestamp > self.commit_timestamp);
if (t.flags.padding != 0) return .reserved_flag_padding;
if (t.flags.two_phase_commit) {
// Otherwise reserved amounts may never be released:
if (t.timeout == 0) return .two_phase_commit_must_timeout;
} else if (t.timeout != 0) {
return .timeout_reserved_for_two_phase_commit;
}
if (!t.flags.condition and !zeroed_32_bytes(t.reserved)) return .reserved_field;
if (t.amount == 0) return .amount_is_zero;
if (t.debit_account_id == t.credit_account_id) return .accounts_are_the_same;
// The etymology of the DR and CR abbreviations for debit and credit is interesting, either:
// 1. derived from the Latin past participles of debitum and creditum, debere and credere,
// 2. standing for debit record and credit record, or
// 3. relating to debtor and creditor.
// We use them to distinguish between `cr` (credit account), and `c` (commit).
var dr = self.get_account(t.debit_account_id) orelse return .debit_account_not_found;
var cr = self.get_account(t.credit_account_id) orelse return .credit_account_not_found;
assert(t.timestamp > dr.timestamp);
assert(t.timestamp > cr.timestamp);
if (dr.unit != cr.unit) return .accounts_have_different_units;
// TODO We need a lookup before inserting in case transfer exists and would overflow limits.
// If the transfer exists, then we should rather return .exists as an error.
if (dr.debits_exceed_credits(t.amount)) return .exceeds_credits;
if (cr.credits_exceed_debits(t.amount)) return .exceeds_debits;
var insert = self.transfers.getOrPutAssumeCapacity(t.id);
if (insert.found_existing) {
const exists = insert.value_ptr.*;
if (exists.debit_account_id != t.debit_account_id) {
return .exists_with_different_debit_account_id;
} else if (exists.credit_account_id != t.credit_account_id) {
return .exists_with_different_credit_account_id;
}
if (exists.amount != t.amount) return .exists_with_different_amount;
if (@bitCast(u32, exists.flags) != @bitCast(u32, t.flags)) {
return .exists_with_different_flags;
}
if (exists.user_data != t.user_data) return .exists_with_different_user_data;
if (!equal_32_bytes(exists.reserved, t.reserved)) {
return .exists_with_different_reserved_field;
}
if (exists.timeout != t.timeout) return .exists_with_different_timeout;
return .exists;
} else {
insert.value_ptr.* = t;
if (t.flags.two_phase_commit) {
dr.debits_reserved += t.amount;
cr.credits_reserved += t.amount;
} else {
dr.debits_accepted += t.amount;
cr.credits_accepted += t.amount;
}
self.commit_timestamp = t.timestamp;
return .ok;
}
}
fn create_transfer_rollback(self: *StateMachine, t: Transfer) void {
var dr = self.get_account(t.debit_account_id).?;
var cr = self.get_account(t.credit_account_id).?;
if (t.flags.two_phase_commit) {
dr.debits_reserved -= t.amount;
cr.credits_reserved -= t.amount;
} else {
dr.debits_accepted -= t.amount;
cr.credits_accepted -= t.amount;
}
assert(self.transfers.remove(t.id));
}
fn commit_transfer(self: *StateMachine, c: Commit) CommitTransferResult {
assert(c.timestamp > self.commit_timestamp);
if (!c.flags.preimage and !zeroed_32_bytes(c.reserved)) return .reserved_field;
if (c.flags.padding != 0) return .reserved_flag_padding;
var t = self.get_transfer(c.id) orelse return .transfer_not_found;
assert(c.timestamp > t.timestamp);
if (!t.flags.two_phase_commit) return .transfer_not_two_phase_commit;
if (self.get_commit(c.id)) |exists| {
if (!exists.flags.reject and c.flags.reject) return .already_committed_but_accepted;
if (exists.flags.reject and !c.flags.reject) return .already_committed_but_rejected;
return .already_committed;
}
if (t.timeout > 0 and t.timestamp + t.timeout <= c.timestamp) return .transfer_expired;
if (t.flags.condition) {
if (!c.flags.preimage) return .condition_requires_preimage;
if (!valid_preimage(t.reserved, c.reserved)) return .preimage_invalid;
} else if (c.flags.preimage) {
return .preimage_requires_condition;
}
var dr = self.get_account(t.debit_account_id) orelse return .debit_account_not_found;
var cr = self.get_account(t.credit_account_id) orelse return .credit_account_not_found;
assert(t.timestamp > dr.timestamp);
assert(t.timestamp > cr.timestamp);
assert(t.flags.two_phase_commit);
if (dr.debits_reserved < t.amount) return .debit_amount_was_not_reserved;
if (cr.credits_reserved < t.amount) return .credit_amount_was_not_reserved;
// Once reserved, the amount can be moved from reserved to accepted without breaking limits:
assert(!dr.debits_exceed_credits(0));
assert(!cr.credits_exceed_debits(0));
// TODO We can combine this lookup with the previous lookup if we return `error!void`:
var insert = self.commits.getOrPutAssumeCapacity(c.id);
if (insert.found_existing) {
unreachable;
} else {
insert.value_ptr.* = c;
dr.debits_reserved -= t.amount;
cr.credits_reserved -= t.amount;
if (!c.flags.reject) {
dr.debits_accepted += t.amount;
cr.credits_accepted += t.amount;
}
self.commit_timestamp = c.timestamp;
return .ok;
}
}
fn commit_transfer_rollback(self: *StateMachine, c: Commit) void {
assert(self.get_commit(c.id) != null);
var t = self.get_transfer(c.id).?;
var dr = self.get_account(t.debit_account_id).?;
var cr = self.get_account(t.credit_account_id).?;
dr.debits_reserved += t.amount;
cr.credits_reserved += t.amount;
if (!c.flags.reject) {
dr.debits_accepted -= t.amount;
cr.credits_accepted -= t.amount;
}
assert(self.commits.remove(c.id));
}
/// This is our core private method for changing balances.
/// Returns a live pointer to an Account in the accounts hash map.
/// This is intended to lookup an Account and modify balances directly by reference.
/// This pointer is invalidated if the hash map is resized by another insert, e.g. if we get a
/// pointer, insert another account without capacity, and then modify this pointer... BOOM!
/// This is a sharp tool but replaces a lookup, copy and update with a single lookup.
fn get_account(self: *StateMachine, id: u128) ?*Account {
return self.accounts.getPtr(id);
}
/// See the comment for get_account().
fn get_transfer(self: *StateMachine, id: u128) ?*Transfer {
return self.transfers.getPtr(id);
}
/// See the comment for get_account().
fn get_commit(self: *StateMachine, id: u128) ?*Commit {
return self.commits.getPtr(id);
}
};
// TODO Optimize this by precomputing hashes outside and before committing to the state machine.
// If we see that a batch of commits contains commits with preimages, then we will:
// Divide the batch into subsets, dispatch these to multiple threads, store the result in a bitset.
// Then we can simply provide the result bitset to the state machine when committing.
// This will improve crypto performance significantly by a factor of 8x.
fn valid_preimage(condition: [32]u8, preimage: [32]u8) bool {
var target: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(&preimage, &target, .{});
return std.crypto.utils.timingSafeEql([32]u8, target, condition);
}
/// Optimizes for the common case, where the array is zeroed. Completely branchless.
fn zeroed_32_bytes(a: [32]u8) bool {
const x = @bitCast([4]u64, a);
return (x[0] | x[1] | x[2] | x[3]) == 0;
}
fn zeroed_48_bytes(a: [48]u8) bool {
const x = @bitCast([6]u64, a);
return (x[0] | x[1] | x[2] | x[3] | x[4] | x[5]) == 0;
}
/// Optimizes for the common case, where the arrays are equal. Completely branchless.
fn equal_32_bytes(a: [32]u8, b: [32]u8) bool {
const x = @bitCast([4]u64, a);
const y = @bitCast([4]u64, b);
const c = (x[0] ^ y[0]) | (x[1] ^ y[1]);
const d = (x[2] ^ y[2]) | (x[3] ^ y[3]);
return (c | d) == 0;
}
fn equal_48_bytes(a: [48]u8, b: [48]u8) bool {
const x = @bitCast([6]u64, a);
const y = @bitCast([6]u64, b);
const c = (x[0] ^ y[0]) | (x[1] ^ y[1]);
const d = (x[2] ^ y[2]) | (x[3] ^ y[3]);
const e = (x[4] ^ y[4]) | (x[5] ^ y[5]);
return (c | d | e) == 0;
}
const testing = std.testing;
test "create/lookup accounts" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
const Vector = struct { result: CreateAccountResult, object: Account };
const vectors = [_]Vector{
Vector{
.result = .reserved_flag_padding,
.object = std.mem.zeroInit(Account, .{
.id = 1,
.timestamp = 1,
.flags = .{ .padding = 1 },
}),
},
Vector{
.result = .reserved_field,
.object = std.mem.zeroInit(Account, .{
.id = 2,
.timestamp = 1,
.reserved = [_]u8{1} ** 48,
}),
},
Vector{
.result = .exceeds_credits,
.object = std.mem.zeroInit(Account, .{
.id = 3,
.timestamp = 1,
.debits_reserved = 10,
.flags = .{ .debits_must_not_exceed_credits = true },
}),
},
Vector{
.result = .exceeds_credits,
.object = std.mem.zeroInit(Account, .{
.id = 4,
.timestamp = 1,
.debits_accepted = 10,
.flags = .{ .debits_must_not_exceed_credits = true },
}),
},
Vector{
.result = .exceeds_debits,
.object = std.mem.zeroInit(Account, .{
.id = 5,
.timestamp = 1,
.credits_reserved = 10,
.flags = .{ .credits_must_not_exceed_debits = true },
}),
},
Vector{
.result = .exceeds_debits,
.object = std.mem.zeroInit(Account, .{
.id = 6,
.timestamp = 1,
.credits_accepted = 10,
.flags = .{ .credits_must_not_exceed_debits = true },
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Account, .{
.id = 7,
.timestamp = 1,
}),
},
Vector{
.result = .exists,
.object = std.mem.zeroInit(Account, .{
.id = 7,
.timestamp = 2,
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Account, .{
.id = 8,
.timestamp = 2,
.user_data = 'U',
.unit = 9,
}),
},
Vector{
.result = .exists_with_different_unit,
.object = std.mem.zeroInit(Account, .{
.id = 8,
.timestamp = 3,
.user_data = 'U',
.unit = 10,
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Account, .{
.id = 9,
.timestamp = 3,
.code = 9,
.user_data = 'U',
}),
},
Vector{
.result = .exists_with_different_code,
.object = std.mem.zeroInit(Account, .{
.id = 9,
.timestamp = 4,
.code = 10,
.user_data = 'D',
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Account, .{
.id = 10,
.timestamp = 4,
.flags = .{ .credits_must_not_exceed_debits = true },
}),
},
Vector{
.result = .exists_with_different_flags,
.object = std.mem.zeroInit(Account, .{
.id = 10,
.timestamp = 5,
.flags = .{ .debits_must_not_exceed_credits = true },
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Account, .{
.id = 11,
.timestamp = 5,
.user_data = 'U',
}),
},
Vector{
.result = .exists_with_different_user_data,
.object = std.mem.zeroInit(Account, .{
.id = 11,
.timestamp = 6,
.user_data = 'D',
}),
},
};
var state_machine = try StateMachine.init(allocator, vectors.len, 0, 0);
defer state_machine.deinit();
for (vectors) |vector| {
try testing.expectEqual(vector.result, state_machine.create_account(vector.object));
if (vector.result == .ok) {
try testing.expectEqual(vector.object, state_machine.get_account(vector.object.id).?.*);
}
}
}
test "linked accounts" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
const accounts_max = 5;
const transfers_max = 0;
const commits_max = 0;
var accounts = [_]Account{
// An individual event (successful):
std.mem.zeroInit(Account, .{ .id = 7, .code = 200 }),
// A chain of 4 events (the last event in the chain closes the chain with linked=false):
// Commit/rollback:
std.mem.zeroInit(Account, .{ .id = 0, .flags = .{ .linked = true } }),
// Commit/rollback:
std.mem.zeroInit(Account, .{ .id = 1, .flags = .{ .linked = true } }),
// Fail with .exists:
std.mem.zeroInit(Account, .{ .id = 0, .flags = .{ .linked = true } }),
// Fail without committing.
std.mem.zeroInit(Account, .{ .id = 2 }),
// An individual event (successful):
// This should not see any effect from the failed chain above:
std.mem.zeroInit(Account, .{ .id = 0, .code = 200 }),
// A chain of 2 events (the first event fails the chain):
std.mem.zeroInit(Account, .{ .id = 0, .flags = .{ .linked = true } }),
std.mem.zeroInit(Account, .{ .id = 1 }),
// An individual event (successful):
std.mem.zeroInit(Account, .{ .id = 1, .code = 200 }),
// A chain of 2 events (the last event fails the chain):
std.mem.zeroInit(Account, .{ .id = 2, .flags = .{ .linked = true } }),
std.mem.zeroInit(Account, .{ .id = 0 }),
// A chain of 2 events (successful):
std.mem.zeroInit(Account, .{ .id = 2, .flags = .{ .linked = true } }),
std.mem.zeroInit(Account, .{ .id = 3 }),
};
var state_machine = try StateMachine.init(allocator, accounts.len, transfers_max, commits_max);
defer state_machine.deinit();
const input = std.mem.asBytes(&accounts);
const output = try allocator.alloc(u8, 4096);
state_machine.prepare(0, .create_accounts, input);
const size = state_machine.commit(0, .create_accounts, input, output);
const results = std.mem.bytesAsSlice(CreateAccountsResult, output[0..size]);
try testing.expectEqualSlices(
CreateAccountsResult,
&[_]CreateAccountsResult{
CreateAccountsResult{ .index = 1, .result = .linked_event_failed },
CreateAccountsResult{ .index = 2, .result = .linked_event_failed },
CreateAccountsResult{ .index = 3, .result = .exists },
CreateAccountsResult{ .index = 4, .result = .linked_event_failed },
CreateAccountsResult{ .index = 6, .result = .exists_with_different_code },
CreateAccountsResult{ .index = 7, .result = .linked_event_failed },
CreateAccountsResult{ .index = 9, .result = .linked_event_failed },
CreateAccountsResult{ .index = 10, .result = .exists_with_different_code },
},
results,
);
try testing.expectEqual(accounts[0], state_machine.get_account(accounts[0].id).?.*);
try testing.expectEqual(accounts[5], state_machine.get_account(accounts[5].id).?.*);
try testing.expectEqual(accounts[8], state_machine.get_account(accounts[8].id).?.*);
try testing.expectEqual(accounts[11], state_machine.get_account(accounts[11].id).?.*);
try testing.expectEqual(accounts[12], state_machine.get_account(accounts[12].id).?.*);
try testing.expectEqual(@as(u32, 5), state_machine.accounts.count());
// TODO How can we test that events were in fact rolled back in LIFO order?
// All our rollback handlers appear to be commutative.
}
test "create/lookup/rollback transfers" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var accounts = [_]Account{
std.mem.zeroInit(Account, .{ .id = 1 }),
std.mem.zeroInit(Account, .{ .id = 2 }),
std.mem.zeroInit(Account, .{ .id = 3, .unit = 1 }),
std.mem.zeroInit(Account, .{ .id = 4, .unit = 2 }),
std.mem.zeroInit(Account, .{ .id = 5, .flags = .{ .debits_must_not_exceed_credits = true } }),
std.mem.zeroInit(Account, .{ .id = 6, .flags = .{ .credits_must_not_exceed_debits = true } }),
std.mem.zeroInit(Account, .{ .id = 7 }),
std.mem.zeroInit(Account, .{ .id = 8 }),
};
var state_machine = try StateMachine.init(allocator, accounts.len, 1, 0);
defer state_machine.deinit();
const input = std.mem.asBytes(&accounts);
const output = try allocator.alloc(u8, 4096);
state_machine.prepare(0, .create_accounts, input);
const size = state_machine.commit(0, .create_accounts, input, output);
const results = std.mem.bytesAsSlice(CreateAccountsResult, output[0..size]);
for (accounts) |account, i| {
try testing.expectEqual(accounts[i], state_machine.get_account(accounts[i].id).?.*);
}
const Vector = struct { result: CreateTransferResult, object: Transfer };
const timestamp: u64 = (state_machine.commit_timestamp + 1);
const vectors = [_]Vector{
Vector{
.result = .amount_is_zero,
.object = std.mem.zeroInit(Transfer, .{
.id = 1,
.timestamp = timestamp,
}),
},
Vector{
.result = .reserved_flag_padding,
.object = std.mem.zeroInit(Transfer, .{
.id = 2,
.timestamp = timestamp,
.flags = .{ .padding = 1 },
}),
},
Vector{
.result = .two_phase_commit_must_timeout,
.object = std.mem.zeroInit(Transfer, .{
.id = 3,
.timestamp = timestamp,
.flags = .{ .two_phase_commit = true },
}),
},
Vector{
.result = .timeout_reserved_for_two_phase_commit,
.object = std.mem.zeroInit(Transfer, .{
.id = 4,
.timestamp = timestamp,
.timeout = 1,
}),
},
Vector{
.result = .reserved_field,
.object = std.mem.zeroInit(Transfer, .{
.id = 5,
.timestamp = timestamp,
.flags = .{ .condition = false },
.reserved = [_]u8{1} ** 32,
}),
},
Vector{
.result = .accounts_are_the_same,
.object = std.mem.zeroInit(Transfer, .{
.id = 6,
.timestamp = timestamp,
.amount = 10,
.debit_account_id = 1,
.credit_account_id = 1,
}),
},
Vector{
.result = .debit_account_not_found,
.object = std.mem.zeroInit(Transfer, .{
.id = 7,
.timestamp = timestamp,
.amount = 10,
.debit_account_id = 100,
.credit_account_id = 1,
}),
},
Vector{
.result = .credit_account_not_found,
.object = std.mem.zeroInit(Transfer, .{
.id = 8,
.timestamp = timestamp,
.amount = 10,
.debit_account_id = 1,
.credit_account_id = 100,
}),
},
Vector{
.result = .accounts_have_different_units,
.object = std.mem.zeroInit(Transfer, .{
.id = 9,
.timestamp = timestamp,
.amount = 10,
.debit_account_id = 3,
.credit_account_id = 4,
}),
},
Vector{
.result = .exceeds_credits,
.object = std.mem.zeroInit(Transfer, .{
.id = 10,
.timestamp = timestamp,
.amount = 1000,
.debit_account_id = 5,
.credit_account_id = 1,
}),
},
Vector{
.result = .exceeds_debits,
.object = std.mem.zeroInit(Transfer, .{
.id = 11,
.timestamp = timestamp,
.amount = 1000,
.debit_account_id = 1,
.credit_account_id = 6,
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Transfer, .{
.id = 12,
.timestamp = timestamp,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
}),
},
Vector{
.result = .exists,
.object = std.mem.zeroInit(Transfer, .{
.id = 12,
.timestamp = timestamp + 1,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
}),
},
Vector{
.result = .exists_with_different_debit_account_id,
.object = std.mem.zeroInit(Transfer, .{
.id = 12,
.timestamp = timestamp + 1,
.amount = 10,
.debit_account_id = 8,
.credit_account_id = 7,
}),
},
Vector{
.result = .exists_with_different_credit_account_id,
.object = std.mem.zeroInit(Transfer, .{
.id = 12,
.timestamp = timestamp + 1,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 1,
}),
},
Vector{
.result = .exists_with_different_amount,
.object = std.mem.zeroInit(Transfer, .{
.id = 12,
.timestamp = timestamp + 1,
.amount = 11,
.debit_account_id = 7,
.credit_account_id = 8,
}),
},
Vector{
.result = .exists_with_different_flags,
.object = std.mem.zeroInit(Transfer, .{
.id = 12,
.timestamp = timestamp + 1,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
.flags = .{ .condition = true },
}),
},
Vector{
.result = .exists_with_different_user_data,
.object = std.mem.zeroInit(Transfer, .{
.id = 12,
.timestamp = timestamp + 1,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
.user_data = 'A',
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Transfer, .{
.id = 13,
.timestamp = timestamp + 1,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
.flags = .{ .condition = true },
.reserved = [_]u8{1} ** 32,
}),
},
Vector{
.result = .exists_with_different_reserved_field,
.object = std.mem.zeroInit(Transfer, .{
.id = 13,
.timestamp = timestamp + 2,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
.flags = .{ .condition = true },
.reserved = [_]u8{2} ** 32,
}),
},
Vector{
.result = .timeout_reserved_for_two_phase_commit,
.object = std.mem.zeroInit(Transfer, .{
.id = 13,
.timestamp = timestamp + 2,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
.flags = .{ .condition = true },
.reserved = [_]u8{1} ** 32,
.timeout = 10,
}),
},
Vector{
.result = .two_phase_commit_must_timeout,
.object = std.mem.zeroInit(Transfer, .{
.id = 14,
.timestamp = timestamp + 2,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
.flags = .{ .two_phase_commit = true },
.timeout = 0,
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Transfer, .{
.id = 15,
.timestamp = timestamp + 2,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
.flags = .{ .two_phase_commit = true },
.timeout = 20,
}),
},
Vector{
.result = .exists_with_different_timeout,
.object = std.mem.zeroInit(Transfer, .{
.id = 15,
.timestamp = timestamp + 3,
.amount = 10,
.debit_account_id = 7,
.credit_account_id = 8,
.flags = .{ .two_phase_commit = true },
.timeout = 25,
}),
},
};
for (vectors) |vector| {
try testing.expectEqual(vector.result, state_machine.create_transfer(vector.object));
if (vector.result == .ok) {
try testing.expectEqual(vector.object, state_machine.get_transfer(vector.object.id).?.*);
}
}
// 2 phase commit [reserved]:
try testing.expectEqual(@as(u64, 10), state_machine.get_account(7).?.*.debits_reserved);
try testing.expectEqual(@as(u64, 0), state_machine.get_account(7).?.*.credits_reserved);
try testing.expectEqual(@as(u64, 10), state_machine.get_account(8).?.*.credits_reserved);
try testing.expectEqual(@as(u64, 0), state_machine.get_account(8).?.*.debits_reserved);
// 1 phase commit [accepted]:
try testing.expectEqual(@as(u64, 20), state_machine.get_account(7).?.*.debits_accepted);
try testing.expectEqual(@as(u64, 0), state_machine.get_account(7).?.*.credits_accepted);
try testing.expectEqual(@as(u64, 20), state_machine.get_account(8).?.*.credits_accepted);
try testing.expectEqual(@as(u64, 0), state_machine.get_account(8).?.*.debits_accepted);
// Rollback transfer with id [12], amount of 10:
state_machine.create_transfer_rollback(state_machine.get_transfer(vectors[11].object.id).?.*);
try testing.expectEqual(@as(u64, 10), state_machine.get_account(7).?.*.debits_accepted);
try testing.expectEqual(@as(u64, 0), state_machine.get_account(7).?.*.credits_accepted);
try testing.expectEqual(@as(u64, 10), state_machine.get_account(8).?.*.credits_accepted);
try testing.expectEqual(@as(u64, 0), state_machine.get_account(8).?.*.debits_accepted);
try testing.expect(state_machine.get_transfer(vectors[11].object.id) == null);
// Rollback transfer with id [15], amount of 10:
state_machine.create_transfer_rollback(state_machine.get_transfer(vectors[22].object.id).?.*);
try testing.expectEqual(@as(u64, 0), state_machine.get_account(7).?.*.debits_reserved);
try testing.expectEqual(@as(u64, 0), state_machine.get_account(8).?.*.credits_reserved);
try testing.expect(state_machine.get_transfer(vectors[22].object.id) == null);
}
test "create/lookup/rollback commits" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
const Vector = struct { result: CommitTransferResult, object: Commit };
var accounts = [_]Account{
std.mem.zeroInit(Account, .{ .id = 1 }),
std.mem.zeroInit(Account, .{ .id = 2 }),
std.mem.zeroInit(Account, .{ .id = 3 }),
std.mem.zeroInit(Account, .{ .id = 4 }),
};
var transfers = [_]Transfer{
std.mem.zeroInit(Transfer, .{
.id = 1,
.amount = 15,
.debit_account_id = 1,
.credit_account_id = 2,
}),
std.mem.zeroInit(Transfer, .{
.id = 2,
.amount = 15,
.debit_account_id = 1,
.credit_account_id = 2,
.flags = .{ .two_phase_commit = true },
.timeout = 25,
}),
std.mem.zeroInit(Transfer, .{
.id = 3,
.amount = 15,
.debit_account_id = 1,
.credit_account_id = 2,
.flags = .{ .two_phase_commit = true },
.timeout = 25,
}),
std.mem.zeroInit(Transfer, .{
.id = 4,
.amount = 15,
.debit_account_id = 1,
.credit_account_id = 2,
.flags = .{ .two_phase_commit = true },
.timeout = 1,
}),
std.mem.zeroInit(Transfer, .{
.id = 5,
.amount = 15,
.debit_account_id = 1,
.credit_account_id = 2,
.flags = .{
.two_phase_commit = true,
.condition = true,
},
.timeout = 25,
}),
std.mem.zeroInit(Transfer, .{
.id = 6,
.amount = 15,
.debit_account_id = 1,
.credit_account_id = 2,
.flags = .{
.two_phase_commit = true,
.condition = false,
},
.timeout = 25,
}),
std.mem.zeroInit(Transfer, .{
.id = 7,
.amount = 15,
.debit_account_id = 3,
.credit_account_id = 4,
.flags = .{ .two_phase_commit = true },
.timeout = 25,
}),
};
var state_machine = try StateMachine.init(allocator, accounts.len, transfers.len, 1);
defer state_machine.deinit();
const input = std.mem.asBytes(&accounts);
const output = try allocator.alloc(u8, 4096);
// Accounts:
state_machine.prepare(0, .create_accounts, input);
const size = state_machine.commit(0, .create_accounts, input, output);
const results = std.mem.bytesAsSlice(CreateAccountsResult, output[0..size]);
for (accounts) |account, i| {
try testing.expectEqual(accounts[i], state_machine.get_account(accounts[i].id).?.*);
}
// Transfers:
const object_transfers = std.mem.asBytes(&transfers);
const output_transfers = try allocator.alloc(u8, 4096);
state_machine.prepare(0, .create_transfers, object_transfers);
const size_transfers = state_machine.commit(0, .create_transfers, object_transfers, output_transfers);
const results_transfers = std.mem.bytesAsSlice(CreateTransfersResult, output_transfers[0..size_transfers]);
for (transfers) |transfer, i| {
try testing.expectEqual(transfers[i], state_machine.get_transfer(transfers[i].id).?.*);
}
// Commits:
const timestamp: u64 = (state_machine.commit_timestamp + 1);
const vectors = [_]Vector{
Vector{
.result = .reserved_field,
.object = std.mem.zeroInit(Commit, .{
.id = 1,
.timestamp = timestamp,
.reserved = [_]u8{1} ** 32,
}),
},
Vector{
.result = .reserved_flag_padding,
.object = std.mem.zeroInit(Commit, .{
.id = 1,
.timestamp = timestamp,
.flags = .{ .padding = 1 },
}),
},
Vector{
.result = .transfer_not_found,
.object = std.mem.zeroInit(Commit, .{
.id = 777,
.timestamp = timestamp,
}),
},
Vector{
.result = .transfer_not_two_phase_commit,
.object = std.mem.zeroInit(Commit, .{
.id = 1,
.timestamp = timestamp,
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Commit, .{
.id = 2,
.timestamp = timestamp,
}),
},
Vector{
.result = .already_committed_but_accepted,
.object = std.mem.zeroInit(Commit, .{
.id = 2,
.timestamp = timestamp + 1,
.flags = .{ .reject = true },
}),
},
Vector{
.result = .already_committed,
.object = std.mem.zeroInit(Commit, .{
.id = 2,
.timestamp = timestamp + 1,
}),
},
Vector{
.result = .ok,
.object = std.mem.zeroInit(Commit, .{
.id = 3,
.timestamp = timestamp + 1,
.flags = .{ .reject = true },
}),
},
Vector{
.result = .already_committed_but_rejected,
.object = std.mem.zeroInit(Commit, .{
.id = 3,
.timestamp = timestamp + 2,
}),
},
Vector{
.result = .transfer_expired,
.object = std.mem.zeroInit(Commit, .{
.id = 4,
.timestamp = timestamp + 2,
}),
},
Vector{
.result = .condition_requires_preimage,
.object = std.mem.zeroInit(Commit, .{
.id = 5,
.timestamp = timestamp + 2,
}),
},
Vector{
.result = .preimage_invalid,
.object = std.mem.zeroInit(Commit, .{
.id = 5,
.timestamp = timestamp + 2,
.flags = .{ .preimage = true },
.reserved = [_]u8{1} ** 32,
}),
},
Vector{
.result = .preimage_requires_condition,
.object = std.mem.zeroInit(Commit, .{
.id = 6,
.timestamp = timestamp + 2,
.flags = .{ .preimage = true },
}),
},
};
// Test balances BEFORE commit
// Account 1:
const account_1_before = state_machine.get_account(1).?.*;
try testing.expectEqual(@as(u64, 15), account_1_before.debits_accepted);
try testing.expectEqual(@as(u64, 75), account_1_before.debits_reserved);
try testing.expectEqual(@as(u64, 0), account_1_before.credits_accepted);
try testing.expectEqual(@as(u64, 0), account_1_before.credits_reserved);
// Account 2:
const account_2_before = state_machine.get_account(2).?.*;
try testing.expectEqual(@as(u64, 0), account_2_before.debits_accepted);
try testing.expectEqual(@as(u64, 0), account_2_before.debits_reserved);
try testing.expectEqual(@as(u64, 15), account_2_before.credits_accepted);
try testing.expectEqual(@as(u64, 75), account_2_before.credits_reserved);
for (vectors) |vector| {
try testing.expectEqual(vector.result, state_machine.commit_transfer(vector.object));
if (vector.result == .ok) {
try testing.expectEqual(vector.object, state_machine.get_commit(vector.object.id).?.*);
}
}
// Test balances AFTER commit
// Account 1:
const account_1_after = state_machine.get_account(1).?.*;
try testing.expectEqual(@as(u64, 30), account_1_after.debits_accepted);
// +15 (acceptance applied):
try testing.expectEqual(@as(u64, 45), account_1_after.debits_reserved);
// -15 (reserved moved):
try testing.expectEqual(@as(u64, 0), account_1_after.credits_accepted);
try testing.expectEqual(@as(u64, 0), account_1_after.credits_reserved);
// Account 2:
const account_2_after = state_machine.get_account(2).?.*;
try testing.expectEqual(@as(u64, 0), account_2_after.debits_accepted);
try testing.expectEqual(@as(u64, 0), account_2_after.debits_reserved);
// +15 (acceptance applied):
try testing.expectEqual(@as(u64, 30), account_2_after.credits_accepted);
// -15 (reserved moved):
try testing.expectEqual(@as(u64, 45), account_2_after.credits_reserved);
// Test COMMIT with invalid debit/credit accounts
state_machine.create_account_rollback(accounts[3]);
try testing.expect(state_machine.get_account(accounts[3].id) == null);
try testing.expectEqual(
state_machine.commit_transfer(std.mem.zeroInit(Commit, .{
.id = 7,
.timestamp = timestamp + 2,
})),
.credit_account_not_found,
);
state_machine.create_account_rollback(accounts[2]);
try testing.expect(state_machine.get_account(accounts[2].id) == null);
try testing.expectEqual(
state_machine.commit_transfer(std.mem.zeroInit(Commit, .{
.id = 7,
.timestamp = timestamp + 2,
})),
.debit_account_not_found,
);
// Rollback [id=2] not rejected:
state_machine.commit_transfer_rollback(vectors[4].object);
// Account 1:
const account_1_rollback = state_machine.get_account(1).?.*;
// -15 (rollback):
try testing.expectEqual(@as(u64, 15), account_1_rollback.debits_accepted);
try testing.expectEqual(@as(u64, 60), account_1_rollback.debits_reserved);
try testing.expectEqual(@as(u64, 0), account_1_rollback.credits_accepted);
try testing.expectEqual(@as(u64, 0), account_1_rollback.credits_reserved);
// Account 2:
const account_2_rollback = state_machine.get_account(2).?.*;
try testing.expectEqual(@as(u64, 0), account_2_rollback.debits_accepted);
try testing.expectEqual(@as(u64, 0), account_2_rollback.debits_reserved);
// -15 (rollback):
try testing.expectEqual(@as(u64, 15), account_2_rollback.credits_accepted);
try testing.expectEqual(@as(u64, 60), account_2_rollback.credits_reserved);
// Rollback [id=3] rejected:
state_machine.commit_transfer_rollback(vectors[7].object);
// Account 1:
const account_1_rollback_reject = state_machine.get_account(1).?.*;
try testing.expectEqual(@as(u64, 15), account_1_rollback_reject.debits_accepted);
// Remains unchanged:
try testing.expectEqual(@as(u64, 75), account_1_rollback_reject.debits_reserved);
// +15 rolled back:
try testing.expectEqual(@as(u64, 0), account_1_rollback_reject.credits_accepted);
try testing.expectEqual(@as(u64, 0), account_1_rollback_reject.credits_reserved);
// Account 2:
const account_2_rollback_reject = state_machine.get_account(2).?.*;
try testing.expectEqual(@as(u64, 0), account_2_rollback_reject.debits_accepted);
try testing.expectEqual(@as(u64, 0), account_2_rollback_reject.debits_reserved);
try testing.expectEqual(@as(u64, 15), account_2_rollback_reject.credits_accepted);
// +15 rolled back"
try testing.expectEqual(@as(u64, 75), account_2_rollback_reject.credits_reserved);
}
fn test_routine_zeroed(comptime len: usize) !void {
const routine = switch (len) {
32 => zeroed_32_bytes,
48 => zeroed_48_bytes,
else => unreachable,
};
var a = [_]u8{0} ** len;
var i: usize = 0;
while (i < a.len) : (i += 1) {
a[i] = 1;
try testing.expectEqual(false, routine(a));
a[i] = 0;
}
try testing.expectEqual(true, routine(a));
}
fn test_routine_equal(comptime len: usize) !void {
const routine = switch (len) {
32 => equal_32_bytes,
48 => equal_48_bytes,
else => unreachable,
};
var a = [_]u8{0} ** len;
var b = [_]u8{0} ** len;
var i: usize = 0;
while (i < a.len) : (i += 1) {
a[i] = 1;
try testing.expectEqual(false, routine(a, b));
a[i] = 0;
b[i] = 1;
try testing.expectEqual(false, routine(a, b));
b[i] = 0;
}
try testing.expectEqual(true, routine(a, b));
}
test "zeroed_32_bytes" {
try test_routine_zeroed(32);
}
test "zeroed_48_bytes" {
try test_routine_zeroed(48);
}
test "equal_32_bytes" {
try test_routine_equal(32);
}
test "equal_48_bytes" {
try test_routine_equal(48);
}
|
src/state_machine.zig
|
const std = @import("std");
const io = std.io;
const ArrayList = std.ArrayList;
const expect = std.testing.expect;
const Allocator = std.mem.Allocator;
const test_allocator = std.testing.allocator;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = gpa.deinit();
}
var allocator = &gpa.allocator;
var map = try Map.init(allocator, "input.txt");
defer map.deinit();
const stdout = std.io.getStdOut().writer();
try stdout.print("Part 1: {d}\n", .{map.countTrees(3, 1)});
try stdout.print("Part 2: {d}\n", .{map.multTrees()});
}
const Map = struct {
width: u32,
height: u32,
data: []bool,
allocator: *Allocator,
pub fn init(allocator: *Allocator, path: []const u8) !Map {
var file = try std.fs.cwd().openFile(path, .{});
defer file.close();
var list = ArrayList(bool).init(allocator);
defer list.deinit();
var height: u32 = 0;
var width: u64 = 0;
var buf_reader = io.bufferedReader(file.reader());
var in_stream = buf_reader.reader();
var buf: [1024]u8 = undefined;
while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
if (0 == width) {
width = line.len;
}
for (line) |t| {
try list.append('#' == t);
}
height += 1;
}
return Map{ .width = @intCast(u32, width), .height = height, .data = list.toOwnedSlice(), .allocator = allocator };
}
pub fn deinit(self: *const Map) void {
self.allocator.free(self.data);
}
pub fn at(self: *const Map, x: u32, y: u32) ?bool {
const offset = (y * self.width) + (x % self.width);
if (offset >= self.data.len) {
return null;
} else {
return self.data[offset];
}
}
pub fn countTrees(self: *const Map, right: u32, down: u32) u32 {
var x: u32 = 0;
var y: u32 = 0;
var count: u32 = 0;
while (self.at(x, y)) |t| {
if (t) {
count += 1;
}
x = x + right;
y = y + down;
}
return count;
}
pub fn multTrees(self: *const Map) u32 {
const r1 = self.countTrees(1, 1);
const r2 = self.countTrees(3, 1);
const r3 = self.countTrees(5, 1);
const r4 = self.countTrees(7, 1);
const r5 = self.countTrees(1, 2);
return r1 * r2 * r3 * r4 * r5;
}
};
test "part1" {
var map = try Map.init(test_allocator, "test.txt");
defer map.deinit();
try expect(map.height == 11);
try expect(map.width == 11);
try expect(false == map.at(0, 0));
try expect(true == map.at(0, 1));
try expect(false == map.at(1, 0));
try expect(true == map.at(10, 10));
try expect(false == map.at(3, 1));
var trees = map.countTrees(3, 1);
try expect(trees == 7);
var mult = map.multTrees();
try expect(mult == 336);
}
|
day03/src/main.zig
|
const std = @import("std");
const tools = @import("tools");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
fn regIndex(name: []const u8) u32 {
var num: u32 = 0;
for (name) |c| {
num = (num * 27) + c - 'a';
}
return num;
}
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const limit = 1 * 1024 * 1024 * 1024;
const text = try std.fs.cwd().readFileAlloc(allocator, "day8.txt", limit);
defer allocator.free(text);
var registers = [1]i64{0} ** (27 * 27 * 27);
var highest = registers[0];
{
var it = std.mem.split(u8, text, "\n");
while (it.next()) |line0| {
var dest: ?u32 = null;
var delta: i64 = undefined;
var cond_txt: []const u8 = "";
if (tools.match_pattern("{} inc {} if {}", line0)) |vals| {
dest = regIndex(vals[0].name);
cond_txt = vals[2].name;
delta = vals[1].imm;
} else if (tools.match_pattern("{} dec {} if {}", line0)) |vals| {
dest = regIndex(vals[0].name);
cond_txt = vals[2].name;
delta = -vals[1].imm;
} else {
unreachable;
}
var cond_reg: ?u32 = null;
var cond_val: i64 = undefined;
var cond: enum {
eq,
ne,
gt,
lt,
ge,
le,
} = undefined;
if (tools.match_pattern("{} > {}", cond_txt)) |vals| {
cond_reg = regIndex(vals[0].name);
cond = .gt;
cond_val = vals[1].imm;
} else if (tools.match_pattern("{} < {}", cond_txt)) |vals| {
cond_reg = regIndex(vals[0].name);
cond = .lt;
cond_val = vals[1].imm;
} else if (tools.match_pattern("{} >= {}", cond_txt)) |vals| {
cond_reg = regIndex(vals[0].name);
cond = .ge;
cond_val = vals[1].imm;
} else if (tools.match_pattern("{} <= {}", cond_txt)) |vals| {
cond_reg = regIndex(vals[0].name);
cond = .le;
cond_val = vals[1].imm;
} else if (tools.match_pattern("{} == {}", cond_txt)) |vals| {
cond_reg = regIndex(vals[0].name);
cond = .eq;
cond_val = vals[1].imm;
} else if (tools.match_pattern("{} != {}", cond_txt)) |vals| {
cond_reg = regIndex(vals[0].name);
cond = .ne;
cond_val = vals[1].imm;
} else {
unreachable;
}
switch (cond) {
.eq => {
if (registers[cond_reg.?] == cond_val) registers[dest.?] += delta;
},
.ne => {
if (registers[cond_reg.?] != cond_val) registers[dest.?] += delta;
},
.gt => {
if (registers[cond_reg.?] > cond_val) registers[dest.?] += delta;
},
.lt => {
if (registers[cond_reg.?] < cond_val) registers[dest.?] += delta;
},
.ge => {
if (registers[cond_reg.?] >= cond_val) registers[dest.?] += delta;
},
.le => {
if (registers[cond_reg.?] <= cond_val) registers[dest.?] += delta;
},
}
if (registers[dest.?] > highest) highest = registers[dest.?];
}
}
var largest = registers[0];
for (registers) |r| {
if (r > largest) largest = r;
}
try stdout.print("largest={}, highest={}\n", .{ largest, highest });
}
|
2017/day8.zig
|
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const assert = std.debug.assert;
pub const main = tools.defaultMain("2021/day19.txt", run);
pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 {
var arena_alloc = std.heap.ArenaAllocator.init(gpa);
defer arena_alloc.deinit();
const arena = arena_alloc.allocator();
const DistIdx = struct {
dist: u32,
idx1: u16,
idx2: u16,
pub fn lessThan(context: void, a: @This(), b: @This()) bool {
_ = context;
return a.dist < b.dist;
}
};
const Scan = struct {
points: []const Vec3,
pair_dists: []const DistIdx = undefined, // distance entre les paires de points du scan. -> plus de calculs (n.n+1)/2 mais permet d'avoir l'index du point de ref sans tout scanner.
positionned: bool = false,
rotation: Mat3 = undefined,
translation: Vec3 = undefined,
};
const scans = blk: {
var scans = std.ArrayList(Scan).init(arena);
var points: std.ArrayList(Vec3) = undefined;
var it = std.mem.tokenize(u8, input, "\n");
while (it.next()) |line| {
if (tools.match_pattern("--- scanner {} ---", line)) |val| {
if (val[0].imm != 0)
try scans.append(Scan{ .points = points.items });
assert(scans.items.len == val[0].imm);
points = std.ArrayList(Vec3).init(arena);
} else if (tools.match_pattern("{},{},{}", line)) |val| {
const v = Vec3{
@intCast(i32, val[0].imm),
@intCast(i32, val[1].imm),
@intCast(i32, val[2].imm),
};
try points.append(v);
} else {
trace("skipping '{s}'\n", .{line});
}
}
try scans.append(Scan{ .points = points.items });
for (scans.items) |*scan| {
var dists = std.ArrayList(DistIdx).init(arena);
for (scan.points) |p0, idx0| {
for (scan.points[idx0 + 1 ..]) |p1, offset| {
const d = norm1(p1 - p0);
try dists.append(.{ .dist = d, .idx1 = @intCast(u16, idx0), .idx2 = @intCast(u16, idx0 + 1 + offset) });
}
}
std.sort.sort(DistIdx, dists.items, {}, DistIdx.lessThan);
scan.pair_dists = dists.items;
}
trace("read {} scans.\n", .{scans.items.len});
break :blk scans.items;
};
const ans1 = ans: {
const refscan = &scans[0];
refscan.rotation = identity;
refscan.translation = Vec3{ 0, 0, 0 };
refscan.positionned = true;
var point_set = std.AutoArrayHashMap(Vec3, void).init(gpa);
defer point_set.deinit();
try point_set.ensureUnusedCapacity(refscan.points.len * scans.len);
for (refscan.points) |p| {
try point_set.put(p, {});
}
var nb_positionned_scans: u32 = 1;
var pass_num: u32 = 0;
while (true) : (pass_num += 1) {
nextscan: for (scans) |*scan, scan_idx| {
if (scan.positionned) continue;
trace("try to match scan{}...\n", .{scan_idx});
// on regarde si on a un scan qui matche parmis ceux déjà positionnés
var maybe_ref_point_idx: u32 = 0;
var maybe_ref_point_positionned: [2]Vec3 = undefined;
var maybe_match = maybe_match: {
for (scans) |s, other_idx| {
if (!s.positionned) continue;
var i: u32 = 0;
var j: u32 = 0;
var nb_matches: u32 = 0;
while (i < scan.pair_dists.len and j < s.pair_dists.len) {
const d1 = scan.pair_dists[i].dist;
const d2 = s.pair_dists[j].dist;
if (d1 == d2) {
nb_matches += 1;
if (nb_matches >= (13 * 12) / 2) {
trace("maybe match with {}...\n", .{other_idx});
maybe_ref_point_idx = scan.pair_dists[i].idx1;
maybe_ref_point_positionned[0] = mul(s.rotation, s.points[s.pair_dists[j].idx1]) + s.translation;
maybe_ref_point_positionned[1] = mul(s.rotation, s.points[s.pair_dists[j].idx2]) + s.translation;
assert(point_set.get(maybe_ref_point_positionned[0]) != null);
assert(point_set.get(maybe_ref_point_positionned[1]) != null);
break :maybe_match true;
}
i += 1;
j += 1;
} else if (d1 < d2) {
i += 1;
} else {
j += 1;
}
}
} else break :maybe_match false;
};
if (!maybe_match)
continue :nextscan;
const match_pos: ?struct { r: Mat3, t: Vec3 } = cur_match: {
// get lucky with pair dist heuristic:
// (peut être une distance égale par hasard, et on essaye qu'un deux indexes possibles pour la paire)
for (rotations) |r| {
const p0 = mul(r, scan.points[maybe_ref_point_idx]);
for (maybe_ref_point_positionned) |ref| {
const t = ref - p0;
var match_count: u32 = 0;
for (scan.points) |orig| {
const p = mul(r, orig) + t;
match_count += @boolToInt(point_set.get(p) != null);
if (match_count >= 12) {
trace("Found lucky match for scan{}: t={}, r={any} with {} positionned points\n", .{ scan_idx, t, r, point_set.count() });
break :cur_match .{ .r = r, .t = t };
}
}
assert(match_count > 0); // il y a au moins p0
}
}
trace("no luck, fallback to exhaustive search for ref point\n", .{});
for (rotations) |r| {
const p0 = mul(r, scan.points[pass_num % scan.points.len]);
var it = point_set.iterator();
while (it.next()) |ref_point| {
const ref = ref_point.key_ptr.*;
const t = ref - p0;
var match_count: u32 = 0;
for (scan.points) |orig| {
const p = mul(r, orig) + t;
match_count += @boolToInt(point_set.get(p) != null);
if (match_count >= 12) {
trace("Found match for scan{}: t={}, r={any} with {} positionned points\n", .{ scan_idx, t, r, point_set.count() });
break :cur_match .{ .r = r, .t = t };
}
}
assert(match_count > 0); // il y a au moins p0
}
}
break :cur_match null;
};
if (match_pos) |match| {
scan.rotation = match.r;
scan.translation = match.t;
scan.positionned = true;
for (scan.points) |orig| {
try point_set.put(mul(match.r, orig) + match.t, {});
}
nb_positionned_scans += 1;
if (nb_positionned_scans == scans.len) break :ans point_set.count();
continue :nextscan;
} else {
trace("no match for scan{} so far, with {} positionned points\n", .{ scan_idx, point_set.count() });
}
}
}
unreachable;
};
const ans2 = ans: {
var max_dist: i32 = 0;
for (scans) |scan1| {
for (scans) |scan2| {
const signed_dist = (scan1.translation - scan2.translation);
const dist = @maximum(signed_dist, -signed_dist);
max_dist = @maximum(max_dist, @reduce(.Add, dist));
}
}
break :ans max_dist;
};
return [_][]const u8{
try std.fmt.allocPrint(gpa, "{}", .{ans1}),
try std.fmt.allocPrint(gpa, "{}", .{ans2}),
};
}
// -----------------------------------------------------
// matrix math
// -----------------------------------------------------
const Vec3 = @Vector(3, i32);
const Mat3 = [3]Vec3;
fn cross(a: Vec3, b: Vec3) Vec3 {
return Vec3{
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
};
}
fn dot(a: Vec3, b: Vec3) i32 {
return @reduce(.Add, a * b);
}
fn norm1(a: Vec3) u32 {
return @intCast(u32, @reduce(.Add, @maximum(a, -a)));
}
fn mul(m: Mat3, v: Vec3) Vec3 {
return Vec3{
@reduce(.Add, m[0] * v),
@reduce(.Add, m[1] * v),
@reduce(.Add, m[2] * v),
};
}
fn mat3FromLeftAndUp(left: Vec3, up: Vec3) Mat3 {
const front = cross(left, up);
return Mat3{
Vec3{ left[0], up[0], front[0] },
Vec3{ left[1], up[1], front[1] },
Vec3{ left[2], up[2], front[2] },
};
}
const rotations = blk: {
var rots: [6 * 4]Mat3 = undefined;
var len: u32 = 0;
for ([_]Vec3{ .{ 1, 0, 0 }, .{ -1, 0, 0 }, .{ 0, 1, 0 }, .{ 0, -1, 0 }, .{ 0, 0, 1 }, .{ 0, 0, -1 } }) |left| {
for ([_]Vec3{ .{ 1, 0, 0 }, .{ -1, 0, 0 }, .{ 0, 1, 0 }, .{ 0, -1, 0 }, .{ 0, 0, 1 }, .{ 0, 0, -1 } }) |up| {
if (dot(left, up) != 0) continue;
rots[len] = mat3FromLeftAndUp(left, up);
len += 1;
}
}
break :blk rots;
};
const identity = rotations[0];
test "matrix stuff" {
const x = Vec3{ 1, 0, 0 };
const y = Vec3{ 0, 1, 0 };
const z = Vec3{ 0, 0, 1 };
try std.testing.expectEqual(z, cross(x, y));
try std.testing.expectEqual(x, mul(rotations[0], x));
try std.testing.expectEqual(rotations[7][1], cross(rotations[7][2], rotations[7][0]));
}
// -----------------------------------------------------
test {
{
const res = try run(
\\--- scanner 0 ---
\\404,-588,-901
\\528,-643,409
\\-838,591,734
\\390,-675,-793
\\-537,-823,-458
\\-485,-357,347
\\-345,-311,381
\\-661,-816,-575
\\-876,649,763
\\-618,-824,-621
\\553,345,-567
\\474,580,667
\\-447,-329,318
\\-584,868,-557
\\544,-627,-890
\\564,392,-477
\\455,729,728
\\-892,524,684
\\-689,845,-530
\\423,-701,434
\\7,-33,-71
\\630,319,-379
\\443,580,662
\\-789,900,-551
\\459,-707,401
\\
\\--- scanner 1 ---
\\686,422,578
\\605,423,415
\\515,917,-361
\\-336,658,858
\\95,138,22
\\-476,619,847
\\-340,-569,-846
\\567,-361,727
\\-460,603,-452
\\669,-402,600
\\729,430,532
\\-500,-761,534
\\-322,571,750
\\-466,-666,-811
\\-429,-592,574
\\-355,545,-477
\\703,-491,-529
\\-328,-685,520
\\413,935,-424
\\-391,539,-444
\\586,-435,557
\\-364,-763,-893
\\807,-499,-711
\\755,-354,-619
\\553,889,-390
\\
\\--- scanner 2 ---
\\649,640,665
\\682,-795,504
\\-784,533,-524
\\-644,584,-595
\\-588,-843,648
\\-30,6,44
\\-674,560,763
\\500,723,-460
\\609,671,-379
\\-555,-800,653
\\-675,-892,-343
\\697,-426,-610
\\578,704,681
\\493,664,-388
\\-671,-858,530
\\-667,343,800
\\571,-461,-707
\\-138,-166,112
\\-889,563,-600
\\646,-828,498
\\640,759,510
\\-630,509,768
\\-681,-892,-333
\\673,-379,-804
\\-742,-814,-386
\\577,-820,562
\\
\\--- scanner 3 ---
\\-589,542,597
\\605,-692,669
\\-500,565,-823
\\-660,373,557
\\-458,-679,-417
\\-488,449,543
\\-626,468,-788
\\338,-750,-386
\\528,-832,-391
\\562,-778,733
\\-938,-730,414
\\543,643,-506
\\-524,371,-870
\\407,773,750
\\-104,29,83
\\378,-903,-323
\\-778,-728,485
\\426,699,580
\\-438,-605,-362
\\-469,-447,-387
\\509,732,623
\\647,635,-688
\\-868,-804,481
\\614,-800,639
\\595,780,-596
\\
\\--- scanner 4 ---
\\727,592,562
\\-293,-554,779
\\441,611,-461
\\-714,465,-776
\\-743,427,-804
\\-660,-479,-426
\\832,-632,460
\\927,-485,-438
\\408,393,-506
\\466,436,-512
\\110,16,151
\\-258,-428,682
\\-393,719,612
\\-211,-452,876
\\808,-476,-593
\\-575,615,604
\\-485,667,467
\\-680,325,-822
\\-627,-443,-432
\\872,-547,-609
\\833,512,582
\\807,604,487
\\839,-516,451
\\891,-625,532
\\-652,-548,-490
\\30,-46,-14
, std.testing.allocator);
defer std.testing.allocator.free(res[0]);
defer std.testing.allocator.free(res[1]);
try std.testing.expectEqualStrings("79", res[0]);
try std.testing.expectEqualStrings("3621", res[1]);
}
}
|
2021/day19.zig
|
const std = @import("std");
const testing = std.testing;
const Token = @import("zhtml/token").Token;
const Tokenizer = @import("zhtml/tokenizer").Tokenizer;
const ParseError = @import("zhtml/parse_error").ParseError;
//! Test runner for the html5lib-tests tokenizer tests
//! https://github.com/html5lib/html5lib-tests/tree/master/tokenizer
//!
//! Expects to be run via `zig build test-html5lib`
// FIXME: This whole file is rather sloppy with memory
// TODO: Preprocessing the input stream (spec 12.2.3.5)
// TODO: test.doubleEscaped
// TODO: test.lastStartTag
// TODO: If test.doubleEscaped is present and true, then every string within test.output must
// be further unescaped (as described above) before comparing with the tokenizer's output.
// TODO: Run more .test files once the relevant above TODOs are addressed and the tokenizer progresses
test "test1.test" {
try runTestFile("test/html5lib-tests/tokenizer/test1.test");
}
test "test2.test" {
try runTestFile("test/html5lib-tests/tokenizer/test2.test");
}
test "test3.test" {
try runTestFile("test/html5lib-tests/tokenizer/test3.test");
}
test "test4.test" {
try runTestFile("test/html5lib-tests/tokenizer/test4.test");
}
fn runTestFile(file_path: []const u8) !void {
var allocator = std.heap.page_allocator;
var contents = try std.fs.cwd().readFileAlloc(allocator, file_path, std.math.maxInt(usize));
defer allocator.free(contents);
var parser = std.json.Parser.init(allocator, true);
defer parser.deinit();
var tree = try parser.parse(contents);
defer tree.deinit();
var tests = tree.root.Object.get("tests").?.Array;
for (tests.items) |test_obj, i| {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const description = test_obj.Object.get("description").?.String;
const input = test_obj.Object.get("input").?.String;
std.debug.print("\n===================\n{}: {}\n", .{ i, description });
std.debug.print("\n{}\n", .{input});
const expected_tokens = try parseOutput(&arena.allocator, test_obj.Object.get("output").?.Array);
defer expected_tokens.deinit();
const expected_errors = blk: {
if (test_obj.Object.get("errors")) |errors_obj| {
break :blk try parseErrors(&arena.allocator, test_obj.Object.get("errors").?.Array);
} else {
break :blk std.ArrayList(ErrorInfo).init(&arena.allocator);
}
};
defer expected_errors.deinit();
if (expected_errors.items.len > 0) {
std.debug.print("\nexpected errors:\n", .{});
for (expected_errors.items) |expected_error| {
std.debug.print(" {}\n", .{expected_error});
}
}
std.debug.print("===================\n", .{});
if (test_obj.Object.get("initialStates")) |initial_states_obj| {
const initial_states = test_obj.Object.get("initialStates").?.Array;
for (initial_states.items) |initial_state_val| {
std.debug.print("------------------\nwith initial state: {}\n------------------\n", .{initial_state_val.String});
try runTest(&arena.allocator, input, expected_tokens.items, expected_errors.items, parseInitialState(initial_state_val.String).?);
}
} else {
try runTest(&arena.allocator, input, expected_tokens.items, expected_errors.items, null);
}
}
}
fn runTest(allocator: *std.mem.Allocator, input: []const u8, expected_tokens: []Token, expected_errors: []ErrorInfo, initial_state: ?Tokenizer.State) !void {
var tokenizer = try Tokenizer.initWithString(allocator, input);
if (initial_state) |_initial_state| {
tokenizer.state = _initial_state;
}
var num_tokens: usize = 0;
var num_errors: usize = 0;
while (true) {
var token = tokenizer.nextToken() catch |err| {
std.log.err(.main, "{} at line: {}, column: {}\n", .{ err, tokenizer.line, tokenizer.column });
testing.expect(expected_errors.len > 0);
var error_found = false;
const id = ErrorInfo.errorToSpecId(err);
for (expected_errors) |expected_error| {
// TODO: Compare line number and column number; the html5lib tests don't seem to be consistent
// with their expected line/col for errors, so this is disabled for now.
if (std.mem.eql(u8, expected_error.id, id)) {
error_found = true;
break;
}
}
testing.expect(error_found);
num_errors += 1;
continue;
};
if (token == Token.EndOfFile)
break;
const expected_token = expected_tokens[num_tokens];
std.debug.print("expected: {}\nactual: {}\n\n", .{ expected_token, token });
expectEqualTokens(expected_token, token);
num_tokens += 1;
}
testing.expectEqual(expected_tokens.len, num_tokens);
testing.expectEqual(expected_errors.len, num_errors);
}
fn parseOutput(allocator: *std.mem.Allocator, outputs: var) !std.ArrayList(Token) {
var tokens = try std.ArrayList(Token).initCapacity(allocator, outputs.items.len);
for (outputs.items) |output_obj| {
const output_array = output_obj.Array.items;
const token_type_str = output_array[0].String;
if (std.mem.eql(u8, token_type_str, "DOCTYPE")) {
// ["DOCTYPE", name, public_id, system_id, correctness]
try tokens.append(Token{
.DOCTYPE = .{
.name = if (output_array[1] == .Null) null else output_array[1].String,
// public_id and system_id are either strings or null.
.publicIdentifier = if (output_array[2] == .Null) null else output_array[2].String,
.systemIdentifier = if (output_array[3] == .Null) null else output_array[3].String,
// correctness is either true or false; true corresponds to the force-quirks flag being false, and vice-versa.
.forceQuirks = !output_array[4].Bool,
},
});
} else if (std.mem.eql(u8, token_type_str, "StartTag")) {
// ["StartTag", name, {attributes}*, true*]
// ["StartTag", name, {attributes}]
const attributes_obj = output_array[2].Object;
var token = Token{
.StartTag = .{
.name = output_array[1].String,
// When the self-closing flag is set, the StartTag array has true as its fourth entry.
// When the flag is not set, the array has only three entries for backwards compatibility.
.selfClosing = if (output_array.len == 3) false else output_array[3].Bool,
.attributes = std.StringHashMap([]const u8).init(allocator),
},
};
for (attributes_obj.items()) |attribute_entry| {
try token.StartTag.attributes.put(attribute_entry.key, attribute_entry.value.String);
}
try tokens.append(token);
} else if (std.mem.eql(u8, token_type_str, "EndTag")) {
// ["EndTag", name]
try tokens.append(Token{
.EndTag = .{
.name = output_array[1].String,
.attributes = std.StringHashMap([]const u8).init(allocator),
},
});
} else if (std.mem.eql(u8, token_type_str, "Comment")) {
// ["Comment", data]
try tokens.append(Token{
.Comment = .{ .data = output_array[1].String },
});
} else if (std.mem.eql(u8, token_type_str, "Character")) {
// ["Character", data]
// All adjacent character tokens are coalesced into a single ["Character", data] token.
var chars_utf8 = try std.unicode.Utf8View.init(output_array[1].String);
var chars_iterator = chars_utf8.iterator();
while (chars_iterator.nextCodepoint()) |codepoint| {
try tokens.append(Token{
.Character = .{ .data = codepoint },
});
}
}
}
return tokens;
}
pub fn parseErrors(allocator: *std.mem.Allocator, errors: var) !std.ArrayList(ErrorInfo) {
var error_infos = try std.ArrayList(ErrorInfo).initCapacity(allocator, errors.items.len);
for (errors.items) |error_obj| {
const code = error_obj.Object.get("code").?.String;
// skip these for now
// TODO: Errors from preprocessing the input stream
if (std.mem.eql(u8, code, "control-character-in-input-stream")
or std.mem.eql(u8, code, "noncharacter-in-input-stream")) {
continue;
}
const line = @intCast(usize, error_obj.Object.get("line").?.Integer);
const col = @intCast(usize, error_obj.Object.get("col").?.Integer);
error_infos.appendAssumeCapacity(ErrorInfo{
.id = code,
.line = line,
.column = col,
});
}
return error_infos;
}
fn parseInitialState(str: []const u8) ?Tokenizer.State {
const map = std.ComptimeStringMap(Tokenizer.State, .{
.{ "Data state", Tokenizer.State.Data },
.{ "PLAINTEXT state", Tokenizer.State.PLAINTEXT },
.{ "RCDATA state", Tokenizer.State.RCDATA },
.{ "RAWTEXT state", Tokenizer.State.RAWTEXT },
.{ "Script data state", Tokenizer.State.ScriptData },
.{ "CDATA section state", Tokenizer.State.CDATASection },
});
return map.get(str);
}
fn expectEqualAttributes(expected: std.StringHashMap([]const u8), actual: std.StringHashMap([]const u8)) void {
testing.expectEqual(expected.items().len, actual.items().len);
for (expected.items()) |expected_entry| {
const actual_value = actual.get(expected_entry.key);
testing.expect(actual_value != null);
testing.expectEqualSlices(u8, expected_entry.value, actual_value.?);
}
}
fn expectEqualNullableSlices(comptime T: type, expected: ?[]const T, actual: ?[]const T) void {
if (expected) |_| {
testing.expectEqualSlices(T, expected.?, actual.?);
} else {
testing.expectEqual(expected, actual);
}
}
fn expectEqualTokens(expected: Token, actual: Token) void {
const TokenTag = @TagType(Token);
testing.expect(@as(TokenTag, actual) == @as(TokenTag, expected));
switch (expected) {
.DOCTYPE => {
expectEqualNullableSlices(u8, expected.DOCTYPE.name, actual.DOCTYPE.name);
expectEqualNullableSlices(u8, expected.DOCTYPE.publicIdentifier, actual.DOCTYPE.publicIdentifier);
expectEqualNullableSlices(u8, expected.DOCTYPE.systemIdentifier, actual.DOCTYPE.systemIdentifier);
testing.expectEqual(expected.DOCTYPE.forceQuirks, actual.DOCTYPE.forceQuirks);
},
.StartTag => {
expectEqualNullableSlices(u8, expected.StartTag.name, actual.StartTag.name);
testing.expectEqual(expected.StartTag.selfClosing, actual.StartTag.selfClosing);
expectEqualAttributes(expected.StartTag.attributes, actual.StartTag.attributes);
},
.EndTag => {
expectEqualNullableSlices(u8, expected.EndTag.name, actual.EndTag.name);
// Don't compare selfClosing or attributes. From the spec:
// An end tag that has a / right before the closing > is treated as a regular end tag.
// Attributes in end tags are completely ignored and do not make their way into the DOM.
},
.Comment => {
expectEqualNullableSlices(u8, expected.Comment.data, actual.Comment.data);
},
.Character => {
testing.expectEqual(expected.Character.data, actual.Character.data);
},
.EndOfFile => unreachable,
}
}
const ErrorInfo = struct {
id: []const u8,
line: usize,
column: usize,
pub fn errorToSpecId(err: ParseError) []const u8 {
// there might be a cleverer way to do this but oh well
return switch (err) {
ParseError.Default => unreachable,
ParseError.AbruptClosingOfEmptyComment => "abrupt-closing-of-empty-comment",
ParseError.AbruptDoctypePublicIdentifier => "abrupt-doctype-public-identifier",
ParseError.AbruptDoctypeSystemIdentifier => "abrupt-doctype-system-identifier",
ParseError.AbsenceOfDigitsInNumericCharacterReference => "absence-of-digits-in-numeric-character-reference",
ParseError.CDATAInHtmlContent => "cdata-in-html-content",
ParseError.CharacterReferenceOutsideUnicodeRange => "character-reference-outside-unicode-range",
ParseError.ControlCharacterInInputStream => "control-character-in-input-stream",
ParseError.ControlCharacterReference => "control-character-reference",
ParseError.EndTagWithAttributes => "end-tag-with-attributes",
ParseError.DuplicateAttribute => "duplicate-attribute",
ParseError.EndTagWithTrailingSolidus => "end-tag-with-trailing-solidus",
ParseError.EofBeforeTagName => "eof-before-tag-name",
ParseError.EofInCDATA => "eof-in-cdata",
ParseError.EofInComment => "eof-in-comment",
ParseError.EofInDOCTYPE => "eof-in-doctype",
ParseError.EofInScriptHTMLCommentLikeText => "eof-in-script-html-comment-like-text",
ParseError.EofInTag => "eof-in-tag",
ParseError.IncorrectlyClosedComment => "incorrectly-closed-comment",
ParseError.IncorrectlyOpenedComment => "incorrectly-opened-comment",
ParseError.InvalidCharacterSequenceAfterDoctypeName => "invalid-character-sequence-after-doctype-name",
ParseError.InvalidFirstCharacterOfTagName => "invalid-first-character-of-tag-name",
ParseError.MissingAttributeValue => "missing-attribute-value",
ParseError.MissingDoctypeName => "missing-doctype-name",
ParseError.MissingDoctypePublicIdentifier => "missing-doctype-public-identifier",
ParseError.MissingDoctypeSystemIdentifier => "missing-doctype-system-identifier",
ParseError.MissingEndTagName => "missing-end-tag-name",
ParseError.MissingQuoteBeforeDoctypePublicIdentifier => "missing-quote-before-doctype-public-identifier",
ParseError.MissingQuoteBeforeDoctypeSystemIdentifier => "missing-quote-before-doctype-system-identifier",
ParseError.MissingSemicolonAfterCharacterReference => "missing-semicolon-after-character-reference",
ParseError.MissingWhitespaceAfterDoctypePublicKeyword => "missing-whitespace-after-doctype-public-keyword",
ParseError.MissingWhitespaceAfterDoctypeSystemKeyword => "missing-whitespace-after-doctype-system-keyword",
ParseError.MissingWhitespaceBeforeDoctypeName => "missing-whitespace-before-doctype-name",
ParseError.MissingWhitespaceBetweenAttributes => "missing-whitespace-between-attributes",
ParseError.MissingWhitespaceBetweenDoctypePublicAndSystemIdentifiers => "missing-whitespace-between-doctype-public-and-system-identifiers",
ParseError.NestedComment => "nested-comment",
ParseError.NoncharacterCharacterReference => "noncharacter-character-reference",
ParseError.NoncharacterInInputStream => "noncharacter-in-input-stream",
ParseError.NonVoidHTMLElementStartTagWithTrailingSolidus => "non-void-html-element-start-tag-with-trailing-solidus",
ParseError.NullCharacterReference => "null-character-reference",
ParseError.SurrogateCharacterReference => "surrogate-character-reference",
ParseError.SurrogateInInputStream => "surrogate-in-input-stream",
ParseError.UnexpectedCharacterAfterDoctypeSystemIdentifier => "unexpected-character-after-doctype-system-identifier",
ParseError.UnexpectedCharacterInAttributeName => "unexpected-character-in-attribute-name",
ParseError.UnexpectedCharacterInUnquotedAttributeValue => "unexpected-character-in-unquoted-attribute-value",
ParseError.UnexpectedEqualsSignBeforeAttributeName => "unexpected-equals-sign-before-attribute-name",
ParseError.UnexpectedNullCharacter => "unexpected-null-character",
ParseError.UnexpectedQuestionMarkInsteadOfTagName => "unexpected-question-mark-instead-of-tag-name",
ParseError.UnexpectedSolidusInTag => "unexpected-solidus-in-tag",
ParseError.UnknownNamedCharacterReference => "unknown-named-character-reference",
};
}
};
test "ErrorInfo.errorToSpecId" {
testing.expectEqualSlices(u8, "eof-in-doctype", ErrorInfo.errorToSpecId(ParseError.EofInDOCTYPE));
}
|
test/tokenizer-html5lib.zig
|
const std = @import("../std.zig");
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
const native_abi = builtin.abi;
const native_arch = builtin.cpu.arch;
const linux = std.os.linux;
const iovec = std.os.iovec;
const iovec_const = std.os.iovec_const;
const FILE = std.c.FILE;
pub const AF = linux.AF;
pub const ARCH = linux.ARCH;
pub const AT = linux.AT;
pub const CLOCK = linux.CLOCK;
pub const CPU_COUNT = linux.CPU_COUNT;
pub const E = linux.E;
pub const Elf_Symndx = linux.Elf_Symndx;
pub const F = linux.F;
pub const FD_CLOEXEC = linux.FD_CLOEXEC;
pub const F_OK = linux.F_OK;
pub const Flock = linux.Flock;
pub const HOST_NAME_MAX = linux.HOST_NAME_MAX;
pub const IFNAMESIZE = linux.IFNAMESIZE;
pub const IOV_MAX = linux.IOV_MAX;
pub const IPPROTO = linux.IPPROTO;
pub const LOCK = linux.LOCK;
pub const MADV = linux.MADV;
pub const MAP = struct {
pub usingnamespace linux.MAP;
/// Only used by libc to communicate failure.
pub const FAILED = @intToPtr(*c_void, maxInt(usize));
};
pub const MMAP2_UNIT = linux.MMAP2_UNIT;
pub const MSG = linux.MSG;
pub const NAME_MAX = linux.NAME_MAX;
pub const O = linux.O;
pub const PATH_MAX = linux.PATH_MAX;
pub const POLL = linux.POLL;
pub const PROT = linux.PROT;
pub const REG = linux.REG;
pub const RLIM = linux.RLIM;
pub const R_OK = linux.R_OK;
pub const S = linux.S;
pub const SA = linux.SA;
pub const SC = linux.SC;
pub const SEEK = linux.SEEK;
pub const SHUT = linux.SHUT;
pub const SIG = linux.SIG;
pub const SIOCGIFINDEX = linux.SIOCGIFINDEX;
pub const SO = linux.SO;
pub const SOCK = linux.SOCK;
pub const SOL = linux.SOL;
pub const STDERR_FILENO = linux.STDERR_FILENO;
pub const STDIN_FILENO = linux.STDIN_FILENO;
pub const STDOUT_FILENO = linux.STDOUT_FILENO;
pub const SYS = linux.SYS;
pub const Sigaction = linux.Sigaction;
pub const TCP = linux.TCP;
pub const VDSO = linux.VDSO;
pub const W = linux.W;
pub const W_OK = linux.W_OK;
pub const X_OK = linux.X_OK;
pub const addrinfo = linux.addrinfo;
pub const blkcnt_t = linux.blkcnt_t;
pub const blksize_t = linux.blksize_t;
pub const clock_t = linux.clock_t;
pub const cpu_set_t = linux.cpu_set_t;
pub const dev_t = linux.dev_t;
pub const dl_phdr_info = linux.dl_phdr_info;
pub const empty_sigset = linux.empty_sigset;
pub const epoll_event = linux.epoll_event;
pub const fd_t = linux.fd_t;
pub const gid_t = linux.gid_t;
pub const ifreq = linux.ifreq;
pub const ino_t = linux.ino_t;
pub const mcontext_t = linux.mcontext_t;
pub const mode_t = linux.mode_t;
pub const msghdr = linux.msghdr;
pub const msghdr_const = linux.msghdr_const;
pub const nfds_t = linux.nfds_t;
pub const nlink_t = linux.nlink_t;
pub const off_t = linux.off_t;
pub const pid_t = linux.pid_t;
pub const pollfd = linux.pollfd;
pub const rlim_t = linux.rlim_t;
pub const rlimit = linux.rlimit;
pub const rlimit_resource = linux.rlimit_resource;
pub const siginfo_t = linux.siginfo_t;
pub const sigset_t = linux.sigset_t;
pub const sockaddr = linux.sockaddr;
pub const socklen_t = linux.socklen_t;
pub const stack_t = linux.stack_t;
pub const termios = linux.termios;
pub const time_t = linux.time_t;
pub const timespec = linux.timespec;
pub const timeval = linux.timeval;
pub const timezone = linux.timezone;
pub const ucontext_t = linux.ucontext_t;
pub const uid_t = linux.uid_t;
pub const user_desc = linux.user_desc;
pub const utsname = linux.utsname;
pub const PR = linux.PR;
pub const _errno = switch (native_abi) {
.android => struct {
extern "c" var __errno: c_int;
fn getErrno() *c_int {
return &__errno;
}
}.getErrno,
else => struct {
extern "c" fn __errno_location() *c_int;
}.__errno_location,
};
pub const Stat = switch (native_arch) {
.sparcv9 => extern struct {
dev: u64,
ino: ino_t,
mode: u32,
nlink: usize,
uid: u32,
gid: u32,
rdev: u64,
__pad0: u32,
size: off_t,
blksize: isize,
blocks: i64,
atim: timespec,
mtim: timespec,
ctim: timespec,
__unused: [2]isize,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
},
.mips, .mipsel => extern struct {
dev: dev_t,
__pad0: [2]u32,
ino: ino_t,
mode: mode_t,
nlink: nlink_t,
uid: uid_t,
gid: gid_t,
rdev: dev_t,
__pad1: [2]u32,
size: off_t,
atim: timespec,
mtim: timespec,
ctim: timespec,
blksize: blksize_t,
__pad3: u32,
blocks: blkcnt_t,
__pad4: [14]u32,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
},
else => std.os.linux.Stat, // libc stat is the same as kernel stat.
};
pub const AI = struct {
pub const PASSIVE = 0x01;
pub const CANONNAME = 0x02;
pub const NUMERICHOST = 0x04;
pub const V4MAPPED = 0x08;
pub const ALL = 0x10;
pub const ADDRCONFIG = 0x20;
pub const NUMERICSERV = 0x400;
};
pub const NI = struct {
pub const NUMERICHOST = 0x01;
pub const NUMERICSERV = 0x02;
pub const NOFQDN = 0x04;
pub const NAMEREQD = 0x08;
pub const DGRAM = 0x10;
pub const NUMERICSCOPE = 0x100;
};
pub const EAI = enum(c_int) {
BADFLAGS = -1,
NONAME = -2,
AGAIN = -3,
FAIL = -4,
FAMILY = -6,
SOCKTYPE = -7,
SERVICE = -8,
MEMORY = -10,
SYSTEM = -11,
OVERFLOW = -12,
NODATA = -5,
ADDRFAMILY = -9,
INPROGRESS = -100,
CANCELED = -101,
NOTCANCELED = -102,
ALLDONE = -103,
INTR = -104,
IDN_ENCODE = -105,
_,
};
pub extern "c" fn fallocate64(fd: fd_t, mode: c_int, offset: off_t, len: off_t) c_int;
pub extern "c" fn fopen64(noalias filename: [*:0]const u8, noalias modes: [*:0]const u8) ?*FILE;
pub extern "c" fn fstat64(fd: fd_t, buf: *Stat) c_int;
pub extern "c" fn fstatat64(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, flags: u32) c_int;
pub extern "c" fn ftruncate64(fd: c_int, length: off_t) c_int;
pub extern "c" fn getrlimit64(resource: rlimit_resource, rlim: *rlimit) c_int;
pub extern "c" fn lseek64(fd: fd_t, offset: i64, whence: c_int) i64;
pub extern "c" fn mmap64(addr: ?*align(std.mem.page_size) c_void, len: usize, prot: c_uint, flags: c_uint, fd: fd_t, offset: i64) *c_void;
pub extern "c" fn open64(path: [*:0]const u8, oflag: c_uint, ...) c_int;
pub extern "c" fn openat64(fd: c_int, path: [*:0]const u8, oflag: c_uint, ...) c_int;
pub extern "c" fn pread64(fd: fd_t, buf: [*]u8, nbyte: usize, offset: i64) isize;
pub extern "c" fn preadv64(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: i64) isize;
pub extern "c" fn pwrite64(fd: fd_t, buf: [*]const u8, nbyte: usize, offset: i64) isize;
pub extern "c" fn pwritev64(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: i64) isize;
pub extern "c" fn sendfile64(out_fd: fd_t, in_fd: fd_t, offset: ?*i64, count: usize) isize;
pub extern "c" fn setrlimit64(resource: rlimit_resource, rlim: *const rlimit) c_int;
pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) isize;
pub extern "c" fn sched_getaffinity(pid: c_int, size: usize, set: *cpu_set_t) c_int;
pub extern "c" fn eventfd(initval: c_uint, flags: c_uint) c_int;
pub extern "c" fn epoll_ctl(epfd: fd_t, op: c_uint, fd: fd_t, event: ?*epoll_event) c_int;
pub extern "c" fn epoll_create1(flags: c_uint) c_int;
pub extern "c" fn epoll_wait(epfd: fd_t, events: [*]epoll_event, maxevents: c_uint, timeout: c_int) c_int;
pub extern "c" fn epoll_pwait(
epfd: fd_t,
events: [*]epoll_event,
maxevents: c_int,
timeout: c_int,
sigmask: *const sigset_t,
) c_int;
pub extern "c" fn inotify_init1(flags: c_uint) c_int;
pub extern "c" fn inotify_add_watch(fd: fd_t, pathname: [*:0]const u8, mask: u32) c_int;
pub extern "c" fn inotify_rm_watch(fd: fd_t, wd: c_int) c_int;
/// See std.elf for constants for this
pub extern "c" fn getauxval(__type: c_ulong) c_ulong;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*c_void) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub extern "c" fn memfd_create(name: [*:0]const u8, flags: c_uint) c_int;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub extern "c" fn fallocate(fd: fd_t, mode: c_int, offset: off_t, len: off_t) c_int;
pub extern "c" fn sendfile(
out_fd: fd_t,
in_fd: fd_t,
offset: ?*off_t,
count: usize,
) isize;
pub extern "c" fn copy_file_range(fd_in: fd_t, off_in: ?*i64, fd_out: fd_t, off_out: ?*i64, len: usize, flags: c_uint) isize;
pub extern "c" fn signalfd(fd: fd_t, mask: *const sigset_t, flags: c_uint) c_int;
pub extern "c" fn prlimit(pid: pid_t, resource: rlimit_resource, new_limit: *const rlimit, old_limit: *rlimit) c_int;
pub extern "c" fn posix_memalign(memptr: *?*c_void, alignment: usize, size: usize) c_int;
pub extern "c" fn malloc_usable_size(?*const c_void) usize;
pub extern "c" fn madvise(
addr: *align(std.mem.page_size) c_void,
length: usize,
advice: c_uint,
) c_int;
pub const pthread_attr_t = extern struct {
__size: [56]u8,
__align: c_long,
};
pub const pthread_mutex_t = extern struct {
size: [__SIZEOF_PTHREAD_MUTEX_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_MUTEX_T,
};
pub const pthread_cond_t = extern struct {
size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
};
pub const pthread_rwlock_t = switch (native_abi) {
.android => switch (@sizeOf(usize)) {
4 => extern struct {
lock: std.c.pthread_mutex_t = std.c.PTHREAD_MUTEX_INITIALIZER,
cond: std.c.pthread_cond_t = std.c.PTHREAD_COND_INITIALIZER,
numLocks: c_int = 0,
writerThreadId: c_int = 0,
pendingReaders: c_int = 0,
pendingWriters: c_int = 0,
attr: i32 = 0,
__reserved: [12]u8 = [_]u8{0} ** 2,
},
8 => extern struct {
numLocks: c_int = 0,
writerThreadId: c_int = 0,
pendingReaders: c_int = 0,
pendingWriters: c_int = 0,
attr: i32 = 0,
__reserved: [36]u8 = [_]u8{0} ** 36,
},
else => @compileError("impossible pointer size"),
},
else => extern struct {
size: [56]u8 align(@alignOf(usize)) = [_]u8{0} ** 56,
},
};
pub const sem_t = extern struct {
__size: [__SIZEOF_SEM_T]u8 align(@alignOf(usize)),
};
const __SIZEOF_PTHREAD_COND_T = 48;
const __SIZEOF_PTHREAD_MUTEX_T = switch (native_abi) {
.musl, .musleabi, .musleabihf => if (@sizeOf(usize) == 8) 40 else 24,
.gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (native_arch) {
.aarch64 => 48,
.x86_64 => if (native_abi == .gnux32) 40 else 32,
.mips64, .powerpc64, .powerpc64le, .sparcv9 => 40,
else => if (@sizeOf(usize) == 8) 40 else 24,
},
.android => if (@sizeOf(usize) == 8) 40 else 4,
else => @compileError("unsupported ABI"),
};
const __SIZEOF_SEM_T = 4 * @sizeOf(usize);
pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8) E;
pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
pub const RTLD = struct {
pub const LAZY = 1;
pub const NOW = 2;
pub const NOLOAD = 4;
pub const NODELETE = 4096;
pub const GLOBAL = 256;
pub const LOCAL = 0;
};
|
lib/std/c/linux.zig
|
const std = @import("std");
const print = std.debug.print;
var alloc_buffer: [64 * 1024 * 1024]u8 = undefined;
pub fn main() anyerror!void {
var fixed_alloc = std.heap.FixedBufferAllocator.init(alloc_buffer[0..]);
const allocator = fixed_alloc.allocator();
var timer = try std.time.Timer.start();
var times = std.ArrayList(u64).init(allocator);
print("\nDay 01\n", .{});
try @import("./day01.zig").main();
try times.append(timer.lap());
print("\nDay 02\n", .{});
try @import("./day02.zig").main();
try times.append(timer.lap());
print("\nDay 03\n", .{});
try @import("./day03.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 04\n", .{});
try @import("./day04.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 05\n", .{});
try @import("./day05.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 06\n", .{});
try @import("./day06.zig").main();
try times.append(timer.lap());
print("\nDay 07\n", .{});
try @import("./day07.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 08\n", .{});
try @import("./day08.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 09\n", .{});
try @import("./day09.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 10\n", .{});
try @import("./day10.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 11\n", .{});
try @import("./day11.zig").main();
try times.append(timer.lap());
print("\nDay 12\n", .{});
try @import("./day12.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 13\n", .{});
try @import("./day13.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 14\n", .{});
try @import("./day14.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 15\n", .{});
try @import("./day15.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 16\n", .{});
try @import("./day16.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 17\n", .{});
try @import("./day17.zig").main();
try times.append(timer.lap());
print("\nDay 18\n", .{});
try @import("./day18.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 19\n", .{});
try @import("./day19.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 20\n", .{});
try @import("./day20.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 21\n", .{});
try @import("./day21.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nDay 22\n", .{});
try @import("./day22.zig").main_with_allocator(allocator);
try times.append(timer.lap());
print("\nTimes:\n", .{});
var total_time: u64 = 0;
for (times.items) |time, i| {
total_time += time;
const t: f64 = @intToFloat(f64, time) / 1_000_000; // nano to milli
print(" day {d:0>2}: {d: >6.3}ms\n", .{ i + 1, t });
}
const total: f64 = @intToFloat(f64, total_time) / 1_000_000; // nano to milli
print(" total: {d: >6.3}ms\n", .{total});
}
|
src/main.zig
|
const sabaton = @import("root").sabaton;
const regs = @import("regs.zig");
pub fn init() void {
var slice: [35]u32 align(16) = undefined;
var mbox = @intToPtr([*]volatile u32, @ptrToInt(&slice));
mbox[0] = 35 * 4; // size
mbox[1] = 0; // req
mbox[2] = 0x48004; // virtual width (ideally for scrolling and double buffering)
mbox[3] = 8; // buffer size
mbox[4] = 8; // req/resp code
mbox[5] = sabaton.fb_width; // base
mbox[6] = sabaton.fb_height; // size
mbox[7] = 0x48009; // virtual offset
mbox[8] = 8; // buffer size
mbox[9] = 8; // req/resp code
mbox[10] = 0; // x
mbox[11] = 0; // y
mbox[12] = 0x48003; // physical width
mbox[13] = 8; // buffer size
mbox[14] = 8; // req/resp code
mbox[15] = sabaton.fb_width; // base
mbox[16] = sabaton.fb_height; // size
mbox[17] = 0x48005; // set bpp
mbox[18] = 4; // buffer size
mbox[19] = 4; // req/resp code
mbox[20] = 32; // the only good bit depth
mbox[21] = 0x48006; // pixel format
mbox[22] = 4; // buffer size
mbox[23] = 4; // req/resp code
mbox[24] = 0;
mbox[25] = 0x40001; // fb addr
mbox[26] = 8; // buffer size
mbox[27] = 8; // req/resp code
mbox[28] = 4096; // req: alignment, resp: addr
mbox[29] = 0; // size
mbox[30] = 0x40008; // fb pitch
mbox[31] = 4; // buffer size
mbox[32] = 4; // req/resp code
mbox[33] = 0; // pitch
mbox[34] = 0; // terminator
regs.mbox_call(8, @ptrToInt(mbox));
sabaton.fb.pitch = @truncate(u16, mbox[33]);
sabaton.fb.width = @truncate(u16, mbox[15]);
sabaton.fb.height = @truncate(u16, mbox[16]);
sabaton.fb.red_mask_size = 8;
sabaton.fb.green_mask_size = 8;
sabaton.fb.blue_mask_size = 8;
sabaton.fb.bpp = 32;
sabaton.fb.red_mask_shift = 16;
sabaton.fb.green_mask_shift = 8;
sabaton.fb.blue_mask_shift = 0;
const bus_addr = mbox[28];
const arm_addr = bus_addr & 0x3FFFFFFF;
sabaton.add_framebuffer(arm_addr);
}
|
src/platform/pi3_aarch64/display.zig
|
const std = @import("std");
const builtin = std.builtin;
const Builder = std.build.Builder;
const Tcc1Info = struct {
const Extension = enum { c, S };
const Compile = struct {
path: []const u8,
base: []const u8,
ext: Extension = .c,
};
global_incs: ?[]const []const u8 = null,
extra_incs: ?[]const []const u8 = null,
objs: []const Compile,
libs: ?[]const []const u8 = null,
fn setupRun(b: *Builder, run: *std.build.RunStep, cmdline: []const []const u8, comptime format: []const u8, args: anytype) *std.build.Step {
run.step.dependOn(&b.addLog(format ++ "\n", args).step);
run.addArgs(cmdline);
return &run.step;
}
fn build(self: @This(), b: *Builder, tcc: *std.build.LibExeObjStep, r: *std.build.Step, tgt: std.Target) !void {
const resolve = std.fs.path.resolve;
const lib_path = try resolve(b.allocator, &[_][]const u8{
b.zig_exe,
"../lib/zig",
});
const tripletinc = try std.fmt.allocPrint(b.allocator, "libc/include/{s}", .{tgt.linuxTriple(b.allocator)});
for (self.objs) |obj| {
var args = std.ArrayList([]const u8).init(b.allocator);
try args.append("-o");
try args.append(try std.fmt.allocPrint(b.allocator, "tmp/o/{s}.o", .{obj.base}));
try args.append("-c");
try args.append(try std.fmt.allocPrint(b.allocator, "vendor/tinycc/{s}/{s}.{s}", .{ obj.path, obj.base, std.meta.tagName(obj.ext) }));
try args.append("-I");
try args.append("vendor/tinycc/include");
try args.append("-I");
try args.append("tmp");
if (tgt.os.tag != .windows) {
try args.append("-I");
try args.append(try resolve(b.allocator, &[_][]const u8{
lib_path,
"libc/include/generic-musl",
}));
try args.append("-I");
try args.append(try resolve(b.allocator, &[_][]const u8{
lib_path,
tripletinc,
}));
}
if (self.global_incs) |list| for (list) |inc| {
try args.append("-I");
try args.append(try std.fmt.allocPrint(b.allocator, "vendor/tinycc/{s}", .{inc}));
};
if (self.extra_incs) |list| for (list) |inc| {
try args.append("-I");
try args.append(try std.fmt.allocPrint(b.allocator, "vendor/tinycc/{s}", .{inc}));
};
r.dependOn(setupRun(b, tcc.run(), args.toOwnedSlice(), "CC {s}/{s}", .{ obj.path, obj.base }));
}
{
var args = std.ArrayList([]const u8).init(b.allocator);
try args.append("-ar");
try args.append("tmp/lib/libtcc1.a");
for (self.objs) |obj| {
try args.append(try std.fmt.allocPrint(b.allocator, "tmp/o/{s}.o", .{obj.base}));
}
r.dependOn(setupRun(b, tcc.run(), args.toOwnedSlice(), "LD libtcc1.a", .{}));
}
if (self.libs) |list| for (list) |lib| {
var args = std.ArrayList([]const u8).init(b.allocator);
try args.append("-impdef");
try args.append(try std.fmt.allocPrint(b.allocator, "{s}.dll", .{lib}));
try args.append("-o");
try args.append(try std.fmt.allocPrint(b.allocator, "tmp/lib/{s}.def", .{lib}));
r.dependOn(setupRun(b, tcc.run(), args.toOwnedSlice(), "IMPDEF {s}", .{lib}));
};
r.dependOn(&b.addInstallDirectory(.{
.source_dir = "tmp/lib",
.install_dir = .Bin,
.install_subdir = "lib",
}).step);
r.dependOn(&b.addInstallDirectory(.{
.source_dir = "vendor/tinycc/include",
.install_dir = .Bin,
.install_subdir = "include",
}).step);
r.dependOn(&b.addInstallBinFile("src/tjs.h", "include/tjs.h").step);
if (self.global_incs) |list| for (list) |inc| {
r.dependOn(&b.addInstallDirectory(.{
.source_dir = try std.fmt.allocPrint(b.allocator, "vendor/tinycc/{s}", .{inc}),
.install_dir = .Bin,
.install_subdir = "include",
}).step);
};
}
};
fn getArchStr(comptime suffix: []const u8, arch: std.Target.Cpu.Arch) ![]const u8 {
return switch (arch) {
.x86_64 => "alloca86_64" ++ suffix,
.i386 => "alloca86" ++ suffix,
else => error.Unsupported,
};
}
fn bootstrap(b: *Builder, tcc: *std.build.LibExeObjStep, target: std.zig.CrossTarget, extra: bool) !*std.build.Step {
const native = try std.zig.system.NativeTargetInfo.detect(b.allocator, target);
const ret = b.step("bootstrap", "generate libtcc1 and include");
const info: Tcc1Info = switch (native.target.os.tag) {
.windows => Tcc1Info{
.global_incs = &[_][]const u8{"win32/include"},
.extra_incs = &[_][]const u8{"win32/include/winapi"},
.objs = &[_]Tcc1Info.Compile{
.{ .path = "lib", .base = "libtcc1" },
.{ .path = "win32/lib", .base = "crt1" },
.{ .path = "win32/lib", .base = "crt1w" },
.{ .path = "win32/lib", .base = "wincrt1" },
.{ .path = "win32/lib", .base = "wincrt1w" },
.{ .path = "win32/lib", .base = "dllcrt1" },
.{ .path = "win32/lib", .base = "dllmain" },
.{ .path = "win32/lib", .base = "chkstk", .ext = .S },
.{ .path = "lib", .base = try getArchStr("", native.target.cpu.arch), .ext = .S },
.{ .path = "lib", .base = try getArchStr("-bt", native.target.cpu.arch), .ext = .S },
},
.libs = &[_][]const u8{
"ntdll",
"advapi32",
"bcrypt",
"comdlg32",
"crypt32",
"cryptnet",
"gdi32",
"imm32",
"kernel32",
"lz32",
"mpr",
"msvcrt",
"mswsock",
"ncrypt",
"netapi32",
"ole32",
"oleaut32",
"psapi",
"rpcns4",
"rpcrt4",
"scarddlg",
"shell32",
"shlwapi",
"urlmon",
"user32",
"version",
"winmm",
"winscard",
"ws2_32",
"setupapi",
"wintrust",
},
},
.linux => switch (native.target.cpu.arch) {
.x86_64 => Tcc1Info{
.objs = &[_]Tcc1Info.Compile{
.{ .path = "lib", .base = "libtcc1" },
.{ .path = "lib", .base = "bt-exe" },
.{ .path = "lib", .base = "bt-log" },
.{ .path = "lib", .base = "va_list" },
.{ .path = "lib", .base = "dsohandle" },
.{ .path = "lib", .base = "alloca86_64", .ext = .S },
.{ .path = "lib", .base = "alloca86_64-bt", .ext = .S },
},
},
.i386 => Tcc1Info{
.objs = &[_]Tcc1Info.Compile{
.{ .path = "lib", .base = "libtcc1" },
.{ .path = "lib", .base = "bt-exe" },
.{ .path = "lib", .base = "bt-log" },
.{ .path = "lib", .base = "dsohandle" },
.{ .path = "lib", .base = "alloca86", .ext = .S },
.{ .path = "lib", .base = "alloca86-bt", .ext = .S },
},
},
.aarch64 => Tcc1Info{
.objs = &[_]Tcc1Info.Compile{
.{ .path = "lib", .base = "lib-arm64" },
.{ .path = "lib", .base = "fetch_and_add_arm64", .ext = .S },
.{ .path = "lib", .base = "bt-exe" },
.{ .path = "lib", .base = "bt-log" },
.{ .path = "lib", .base = "dsohandle" },
},
},
else => return error.TODO,
},
else => return error.TODO,
};
try info.build(b, tcc, ret, native.target);
if (native.target.os.tag == .windows and extra) {
ret.dependOn(&b.addInstallDirectory(.{
.source_dir = "extra/win32",
.install_dir = .Bin,
.install_subdir = "",
}).step);
}
return ret;
}
pub fn build(b: *Builder) !void {
const target = b.standardTargetOptions(.{});
const native = try std.zig.system.NativeTargetInfo.detect(b.allocator, target);
const mode = b.option(std.builtin.Mode, "mode", "Build mode") orelse .ReleaseSmall;
const strip = b.option(bool, "strip", "Enable strip") orelse (mode == .ReleaseSmall);
const extra = b.option(bool, "extra", "Enable extra library (windows only)") orelse true;
const dump_free = b.option(bool, "dump-free", "For GC debug") orelse false;
if (mode == .Debug and strip) {
@panic("Disable strip for debug");
}
const tccobj = b.addStaticLibrary("tccobj", null);
tccobj.disable_sanitize_c = true;
tccobj.disable_stack_probing = true;
tccobj.linkLibC();
tccobj.addIncludeDir("tmp");
if (native.target.os.tag == .windows) {
tccobj.defineCMacro("TCC_TARGET_PE=1");
tccobj.linkSystemLibrary("ntdll");
tccobj.addCSourceFile("extra/utf8fix/fix.c", &[_][]const u8{});
}
tccobj.addCSourceFile("vendor/tinycc/libtcc.c", &[_][]const u8{"-Wno-everything"});
tccobj.setTarget(target);
tccobj.setBuildMode(mode);
const tcc = b.addExecutable("tcc", null);
tcc.disable_sanitize_c = true;
tcc.disable_stack_probing = true;
tcc.linkLibC();
tcc.defineCMacro("ONE_SOURCE=0");
tcc.linkLibrary(tccobj);
tcc.addIncludeDir("tmp");
tcc.addCSourceFile("vendor/tinycc/tcc.c", &[_][]const u8{"-Wno-everything"});
tcc.setTarget(target);
tcc.setBuildMode(mode);
tcc.install();
const quickjs = b.addStaticLibrary("quickjs", null);
quickjs.disable_sanitize_c = true;
quickjs.disable_stack_probing = true;
quickjs.linkLibC();
if (dump_free) quickjs.defineCMacro("DUMP_FREE");
quickjs.defineCMacro("EMSCRIPTEN");
quickjs.defineCMacro("CONFIG_BIGNUM");
quickjs.defineCMacro("CONFIG_VERSION=\"unknown\"");
quickjs.addCSourceFile("vendor/quickjs/quickjs.c", &[_][]const u8{"-Wno-everything"});
quickjs.addCSourceFile("vendor/quickjs/libregexp.c", &[_][]const u8{"-Wno-everything"});
quickjs.addCSourceFile("vendor/quickjs/libunicode.c", &[_][]const u8{"-Wno-everything"});
quickjs.addCSourceFile("vendor/quickjs/cutils.c", &[_][]const u8{"-Wno-everything"});
quickjs.addCSourceFile("vendor/quickjs/libbf.c", &[_][]const u8{"-Wno-everything"});
quickjs.setTarget(target);
quickjs.setBuildMode(mode);
const exe = b.addExecutable("tjs", "src/main.zig");
exe.disable_sanitize_c = true;
exe.disable_stack_probing = true;
exe.strip = strip;
exe.linkLibrary(quickjs);
exe.linkLibrary(tccobj);
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
if (native.target.os.tag == .windows) {
const rcedit = b.addSystemCommand(&[_][]const u8{"rcedit"});
rcedit.addArtifactArg(exe.install_step.?.artifact);
rcedit.addArgs(&[_][]const u8{
"--application-manifest",
"src/app.manifest",
"--set-icon",
"src/tjs.ico",
});
exe.install_step.?.step.dependOn(&rcedit.step);
if (extra) {
exe.install_step.?.step.dependOn(&b.addInstallDirectory(.{
.source_dir = "extra/inf",
.install_dir = .Bin,
.install_subdir = "",
}).step);
}
}
const tcc1 = try bootstrap(b, tcc, target, extra);
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
|
build.zig
|
const std = @import("std");
const ray = @import("ray.zig");
const config = @import("config.zig");
const vector = @import("vector.zig");
const Vec3 = config.Vec3;
pub const MaterialType = enum {
DIFFUSE,
GLOSSY,
MIRROR,
};
pub const Material = struct {
material_type: MaterialType = MaterialType.DIFFUSE,
specular_exponent: f64 = 0.0,
diffuse: Vec3 = config.ZERO_VECTOR,
emissive: Vec3 = config.ZERO_VECTOR,
specular: Vec3 = config.ZERO_VECTOR,
};
pub fn sampleHemisphereDiffuse(x_sphere_sample: f64, y_sphere_sample: f64) Vec3 {
const r = @sqrt(y_sphere_sample);
const phi = 2.0 * std.math.pi * x_sphere_sample;
return .{ @cos(phi) * r, @sin(phi) * r, @sqrt(1.0 - r * r) };
}
pub fn sampleHemisphereSpecular(x_sphere_sample: f64, y_sphere_sample: f64, specular_exponent: f64) Vec3 {
const phi = 2.0 * std.math.pi * x_sphere_sample;
const cos_theta = std.math.pow(f64, 1.0 - y_sphere_sample, 1.0 / (specular_exponent + 1.0));
const sin_theta = @sqrt(1.0 - cos_theta * cos_theta);
return .{ @cos(phi) * sin_theta, @sin(phi) * sin_theta, cos_theta };
}
pub fn interreflectDiffuse(normal: Vec3, hit_point: Vec3, x_sphere_sample: f64, y_sphere_sample: f64) ray.Ray {
const basis = vector.buildBasis(normal);
const sampled_direction = sampleHemisphereDiffuse(x_sphere_sample, y_sphere_sample);
return .{ .origin = hit_point, .direction = vector.transformIntoBasis(sampled_direction, basis.axis_2, basis.axis_3, normal) };
}
pub fn interreflectSpecular(normal: Vec3, hit_point: Vec3, x_sphere_sample: f64, y_sphere_sample: f64, specular_exponent: f64, cur_ray: ray.Ray) ray.Ray {
const view_direction = -cur_ray.direction;
const reflected_direction = vector.normalize(vector.reflect(view_direction, normal));
const basis = vector.buildBasis(reflected_direction);
const sampled_direction = sampleHemisphereSpecular(x_sphere_sample, y_sphere_sample, specular_exponent);
return .{ .origin = hit_point, .direction = vector.transformIntoBasis(sampled_direction, basis.axis_2, basis.axis_3, reflected_direction) };
}
|
src/material.zig
|
const std = @import("std");
const sys = std.os.system;
const tcgetattr = std.os.tcgetattr;
const tcsetattr = std.os.tcsetattr;
const stdin = std.os.STDERR_FILENO;
const stdout = std.os.STDOUT_FILENO;
const echo = sys.ECHO;
const icanon = sys.ICANON;
var originalTermios: ?std.os.termios = null;
pub fn enableRawMode() anyerror!void {
originalTermios = try tcgetattr(stdin);
var raw = originalTermios.?;
raw.lflag &= ~(@intCast(sys.tcflag_t, echo) | @intCast(sys.tcflag_t, icanon));
try tcsetattr(stdin, sys.TCSA.FLUSH, raw);
}
pub fn disableRawMode() anyerror!void {
if (originalTermios) |termios| {
try tcsetattr(stdin, sys.TCSA.FLUSH, termios);
originalTermios = null;
}
}
pub fn disableRawModeUnsafe() void {
if (originalTermios) |termios| {
tcsetattr(stdin, sys.TCSA.FLUSH, termios) catch unreachable;
originalTermios = null;
}
}
pub const TermKeyEventType = enum {
Char,
Esc,
Enter,
Left,
Right,
Up,
Down,
Other,
};
pub const TermKeyEvent = struct {
type: TermKeyEventType,
char: u8 = undefined,
};
pub fn readKey() !?TermKeyEvent {
var buf: [3]u8 = undefined;
var result: ?TermKeyEvent = null;
var n = try std.os.read(stdin, &buf);
if (n == 0) {
result = null;
} else if (n == 1) {
var char = buf[0];
result = switch (char) {
27 => TermKeyEvent{ .type = .Esc },
10 => TermKeyEvent{ .type = .Enter },
else => TermKeyEvent{ .type = .Char, .char = char },
};
} else if (n == 3) {
if (buf[0] == 27 and buf[1] == 91) {
return switch (buf[2]) {
65 => TermKeyEvent{ .type = .Up },
66 => TermKeyEvent{ .type = .Down },
67 => TermKeyEvent{ .type = .Right },
68 => TermKeyEvent{ .type = .Left },
else => TermKeyEvent{ .type = .Other },
};
}
} else {
result = TermKeyEvent{ .type = .Other };
}
return result;
}
// On windows:
// [using <termio.h> in windows](https://comp.programming.narkive.com/F6D2mhYF/using-termio-h-in-windows) ([archive](https://web.archive.org/web/20211204001943/https://comp.programming.narkive.com/F6D2mhYF/using-termio-h-in-windows))
// Old-ass forum post
// pub fn main() !void {
// // var buf: [3]u8 = undefined;
// try enableRawMode();
// defer disableRawModeUnsafe();
// _ = num(12);
// while (try readKey()) |key| {
// switch (key.type) {
// .Char => {
// _ = try std.os.write(stdout, &[_]u8{key.char});
// },
// .Enter => {
// _ = try std.os.write(stdout, &[_]u8{'\n'});
// },
// .Esc => {
// break;
// },
// else => {},
// }
// }
// var n: usize = 0;
// while (true) {
// n = try std.os.read(stdin, &buf);
// if (n == 0) break;
// if (n == 1) {
// if (buf[0] == 27) {
// break;
// }
// // if (buf[0] == 10) {
// // try disableRawMode();
// // std.log.info("newline!", .{});
// // }
// _ = try std.os.write(stdout, buf[0..1]);
// }
// if (n == 3) {
// std.log.info("{any}", .{buf[0..n]});
// }
// }
// try disableRawMode();
// }
|
src/term/posix.zig
|
const clap = @import("clap");
const format = @import("format");
const std = @import("std");
const ston = @import("ston");
const util = @import("util");
const ascii = std.ascii;
const debug = std.debug;
const fmt = std.fmt;
const fs = std.fs;
const heap = std.heap;
const io = std.io;
const math = std.math;
const mem = std.mem;
const os = std.os;
const rand = std.rand;
const testing = std.testing;
const escape = util.escape;
const Program = @This();
allocator: mem.Allocator,
options: struct {
seed: u64,
include_tms_hms: bool,
include_key_items: bool,
excluded_items: []const []const u8,
},
pokeballs: Pokeballs = Pokeballs{},
items: Items = Items{},
pub const main = util.generateMain(Program);
pub const version = "0.0.0";
pub const description =
\\Randomizes items found on the ground in pokeballs..
\\
;
pub const params = &[_]clap.Param(clap.Help){
clap.parseParam(
"-h, --help " ++
"Display this help text and exit.",
) catch unreachable,
clap.parseParam(
"-t, --include-tms-hms " ++
"Allow for tms/hms to be randomized (This might make the game impossible to " ++
"complete).",
) catch unreachable,
clap.parseParam(
"-k, --include-key-items " ++
"Allow for key items to be randomized (This might make the game impossible to " ++
"complete).",
) catch unreachable,
clap.parseParam(
"-s, --seed <INT> " ++
"The seed to use for random numbers. A random seed will be picked if this is not " ++
"specified.",
) catch unreachable,
clap.parseParam(
"-e, --exclude <STRING>... " ++
"List of items to never pick. Case insensitive. Supports wildcards like '*mail'.",
) catch unreachable,
clap.parseParam(
"-v, --version " ++
"Output version information and exit.",
) catch unreachable,
};
pub fn init(allocator: mem.Allocator, args: anytype) !Program {
const excluded_items_arg = args.options("--exclude");
var excluded_items = try std.ArrayList([]const u8).initCapacity(
allocator,
excluded_items_arg.len,
);
for (excluded_items_arg) |exclude|
excluded_items.appendAssumeCapacity(try ascii.allocLowerString(allocator, exclude));
return Program{
.allocator = allocator,
.options = .{
.seed = try util.getSeed(args),
.include_tms_hms = args.flag("--include-tms-hms"),
.include_key_items = args.flag("--include-key-items"),
.excluded_items = excluded_items.toOwnedSlice(),
},
};
}
pub fn run(
program: *Program,
comptime Reader: type,
comptime Writer: type,
stdio: util.CustomStdIoStreams(Reader, Writer),
) !void {
try format.io(program.allocator, stdio.in, stdio.out, program, useGame);
try program.randomize();
try program.output(stdio.out);
}
fn output(program: *Program, writer: anytype) !void {
try ston.serialize(writer, .{ .pokeball_items = program.pokeballs });
}
fn useGame(program: *Program, parsed: format.Game) !void {
const allocator = program.allocator;
switch (parsed) {
.pokeball_items => |items| switch (items.value) {
.item => |item| {
_ = try program.pokeballs.put(allocator, items.index, .{ .item = item });
return;
},
.amount => return error.DidNotConsumeData,
},
.items => |items| {
const item = (try program.items.getOrPutValue(allocator, items.index, .{})).value_ptr;
switch (items.value) {
.pocket => |pocket| item.pocket = pocket,
.price => |price| item.price = price,
.name => |name| {
item.name = try escape.default.unescapeAlloc(allocator, name);
for (item.name) |*c|
c.* = ascii.toLower(c.*);
},
.description,
.battle_effect,
=> return error.DidNotConsumeData,
}
return error.DidNotConsumeData;
},
.version,
.game_title,
.gamecode,
.instant_text,
.starters,
.text_delays,
.trainers,
.moves,
.pokemons,
.abilities,
.types,
.tms,
.hms,
.pokedex,
.maps,
.wild_pokemons,
.static_pokemons,
.given_pokemons,
.hidden_hollows,
.text,
=> return error.DidNotConsumeData,
}
unreachable;
}
fn randomize(program: *Program) !void {
const allocator = program.allocator;
const random = rand.DefaultPrng.init(program.options.seed).random();
var z: usize = 0;
var excluded_pockets_buffer: [2]format.Pocket = undefined;
var excluded_pockets = std.ArrayListUnmanaged(format.Pocket){
.items = excluded_pockets_buffer[z..z],
.capacity = excluded_pockets_buffer.len,
};
if (!program.options.include_tms_hms)
excluded_pockets.appendAssumeCapacity(.tms_hms);
if (!program.options.include_key_items)
excluded_pockets.appendAssumeCapacity(.key_items);
const pick_from = try getItems(
allocator,
program.items,
excluded_pockets.items,
program.options.excluded_items,
);
outer: for (program.pokeballs.values()) |*ball, i| {
const ball_key = program.pokeballs.keys()[i];
const item = program.items.get(ball_key) orelse continue;
for (excluded_pockets.items) |excluded_pocket| {
if (item.pocket == excluded_pocket)
continue :outer;
}
ball.item = util.random.item(random, pick_from.keys()).?.*;
}
}
const Items = std.AutoArrayHashMapUnmanaged(u16, Item);
const Pokeballs = std.AutoArrayHashMapUnmanaged(u16, Pokeball);
const Set = std.AutoArrayHashMapUnmanaged(u16, void);
fn getItems(
allocator: mem.Allocator,
items: Items,
excluded_pockets: []const format.Pocket,
excluded_items: []const []const u8,
) !Set {
var res = Set{};
errdefer res.deinit(allocator);
outer: for (items.values()) |item, i| {
const item_key = items.keys()[i];
// Assume that items in the 'items' pocket with price 0 are useless or invalid items.
if (item.price == 0 and item.pocket == .items)
continue;
for (excluded_pockets) |pocket| {
if (item.pocket == pocket)
continue :outer;
}
for (excluded_items) |glob| {
if (util.glob.match(glob, item.name))
continue :outer;
}
_ = try res.put(allocator, item_key, {});
}
return res;
}
const Item = struct {
pocket: format.Pocket = .none,
price: usize = 1,
name: []u8 = "",
};
const Pokeball = struct {
item: u16,
};
test "tm35-rand-pokeball-items" {
const H = struct {
fn item(
comptime id: []const u8,
comptime pocket: []const u8,
comptime name: []const u8,
) []const u8 {
return ".items[" ++ id ++ "].pocket=" ++ pocket ++ "\n" ++
".items[" ++ id ++ "].name=" ++ name ++ "\n";
}
fn pokeball(comptime id: []const u8, comptime it: []const u8) []const u8 {
return ".pokeball_items[" ++ id ++ "].item=" ++ it ++ "\n";
}
};
const items = H.item("0", "key_items", "item 0") ++
H.item("1", "items", "item 1") ++
H.item("2", "tms_hms", "item 2") ++
H.item("3", "berries", "item 3");
const result_prefix = items;
const test_string = comptime result_prefix ++
H.pokeball("0", "0") ++
H.pokeball("1", "1") ++
H.pokeball("2", "2") ++
H.pokeball("3", "3");
try util.testing.testProgram(Program, &[_][]const u8{
"--seed=3",
}, test_string, result_prefix ++
\\.pokeball_items[0].item=0
\\.pokeball_items[1].item=1
\\.pokeball_items[2].item=2
\\.pokeball_items[3].item=3
\\
);
try util.testing.testProgram(Program, &[_][]const u8{
"--seed=2",
"--include-key-items",
}, test_string, result_prefix ++
\\.pokeball_items[0].item=3
\\.pokeball_items[1].item=1
\\.pokeball_items[2].item=2
\\.pokeball_items[3].item=1
\\
);
try util.testing.testProgram(Program, &[_][]const u8{
"--seed=2",
"--include-tms-hms",
}, test_string, result_prefix ++
\\.pokeball_items[0].item=0
\\.pokeball_items[1].item=3
\\.pokeball_items[2].item=2
\\.pokeball_items[3].item=2
\\
);
try util.testing.testProgram(Program, &[_][]const u8{
"--seed=1",
"--include-tms-hms",
"--include-key-items",
}, test_string, result_prefix ++
\\.pokeball_items[0].item=3
\\.pokeball_items[1].item=2
\\.pokeball_items[2].item=0
\\.pokeball_items[3].item=2
\\
);
// Test excluding system by running 100 seeds and checking that none of them pick the
// excluded pokemons
var seed: u8 = 0;
while (seed < 100) : (seed += 1) {
var buf: [100]u8 = undefined;
const seed_arg = try fmt.bufPrint(&buf, "--seed={}", .{seed});
const out = try util.testing.runProgram(Program, .{ .args = &[_][]const u8{
"--exclude=item 1",
seed_arg,
}, .in = test_string });
defer testing.allocator.free(out);
try testing.expect(mem.indexOf(u8, out, ".item=1") == null);
}
}
|
src/randomizers/tm35-rand-pokeball-items.zig
|
const std = @import("../std.zig");
const builtin = @import("builtin");
const Loop = std.event.Loop;
/// A WaitGroup keeps track and waits for a group of async tasks to finish.
/// Call `begin` when creating new tasks, and have tasks call `finish` when done.
/// You can provide a count for both operations to perform them in bulk.
/// Call `wait` to suspend until all tasks are completed.
/// Multiple waiters are supported.
///
/// WaitGroup is an instance of WaitGroupGeneric, which takes in a bitsize
/// for the internal counter. WaitGroup defaults to a `usize` counter.
/// It's also possible to define a max value for the counter so that
/// `begin` will return error.Overflow when the limit is reached, even
/// if the integer type has not has not overflowed.
/// By default `max_value` is set to std.math.maxInt(CounterType).
pub const WaitGroup = WaitGroupGeneric(std.meta.bitCount(usize));
pub fn WaitGroupGeneric(comptime counter_size: u16) type {
const CounterType = std.meta.Int(.unsigned, counter_size);
const global_event_loop = Loop.instance orelse
@compileError("std.event.WaitGroup currently only works with event-based I/O");
return struct {
counter: CounterType = 0,
max_counter: CounterType = std.math.maxInt(CounterType),
mutex: std.Thread.Mutex = .{},
waiters: ?*Waiter = null,
const Waiter = struct {
next: ?*Waiter,
tail: *Waiter,
node: Loop.NextTickNode,
};
const Self = @This();
pub fn begin(self: *Self, count: CounterType) error{Overflow}!void {
const held = self.mutex.acquire();
defer held.release();
const new_counter = try std.math.add(CounterType, self.counter, count);
if (new_counter > self.max_counter) return error.Overflow;
self.counter = new_counter;
}
pub fn finish(self: *Self, count: CounterType) void {
var waiters = blk: {
const held = self.mutex.acquire();
defer held.release();
self.counter = std.math.sub(CounterType, self.counter, count) catch unreachable;
if (self.counter == 0) {
const temp = self.waiters;
self.waiters = null;
break :blk temp;
}
break :blk null;
};
// We don't need to hold the lock to reschedule any potential waiter.
while (waiters) |w| {
const temp_w = w;
waiters = w.next;
global_event_loop.onNextTick(&temp_w.node);
}
}
pub fn wait(self: *Self) void {
const held = self.mutex.acquire();
if (self.counter == 0) {
held.release();
return;
}
var self_waiter: Waiter = undefined;
self_waiter.node.data = @frame();
if (self.waiters) |head| {
head.tail.next = &self_waiter;
head.tail = &self_waiter;
} else {
self.waiters = &self_waiter;
self_waiter.tail = &self_waiter;
self_waiter.next = null;
}
suspend {
held.release();
}
}
};
}
test "basic WaitGroup usage" {
if (!std.io.is_async) return error.SkipZigTest;
// TODO https://github.com/ziglang/zig/issues/1908
if (builtin.single_threaded) return error.SkipZigTest;
// TODO https://github.com/ziglang/zig/issues/3251
if (builtin.os.tag == .freebsd) return error.SkipZigTest;
var initial_wg = WaitGroup{};
var final_wg = WaitGroup{};
try initial_wg.begin(1);
try final_wg.begin(1);
var task_frame = async task(&initial_wg, &final_wg);
initial_wg.finish(1);
final_wg.wait();
await task_frame;
}
fn task(wg_i: *WaitGroup, wg_f: *WaitGroup) void {
wg_i.wait();
wg_f.finish(1);
}
|
lib/std/event/wait_group.zig
|
const std = @import("std");
pub const Alignment = enum { left, right, center };
pub const Button = struct {
command: []const u8,
button: ?u8,
};
pub const Monitor = union(enum) {
next,
previous,
first,
last,
nth: u8,
};
pub const AttrModifier = struct {
pub const Attribute = enum { overline, underline };
pub const Modifier = enum { set, unset, toggle };
attribute: Attribute,
modifier: Modifier,
};
pub const Color = @import("Color.zig");
pub const Property = union(enum) {
swap: void,
alignment: Alignment,
offset: u16,
background: ?Color,
foreground: ?Color,
font: ?u8,
underline: ?Color,
click: ?Button,
monitor: Monitor,
attrmod: AttrModifier,
pub fn close(prop: Property) ?Property {
return switch (prop) {
.swap => .swap,
.background => .{ .background = null },
.foreground => .{ .foreground = null },
.font => .{ .font = null },
.underline => .{ .underline = null },
.click => .{ .click = null },
.attrmod => |l| .{ .attrmod = AttrModifier{ .attribute = l.attribute, .modifier = .unset } },
else => null,
};
}
pub fn toString(this: Property, allocator: *std.mem.Allocator) ![]const u8 {
var str = std.ArrayList(u8).init(allocator);
_ = try this.write(str.writer());
return str.toOwnedSlice();
}
pub fn write(this: Property, writer: anytype) !void {
_ = try writer.write("%{");
switch (this) {
.swap => {
_ = try writer.write("R");
},
.alignment => |align_value| {
_ = try writer.write(switch (align_value) {
.left => "l",
.right => "r",
.center => "c",
});
},
.offset => |offset_value| {
_ = try writer.print("O{}", .{offset_value});
},
.background => |bg_color| {
_ = try writer.write("B");
if (bg_color) |color| {
_ = try color.write(&writer);
} else {
_ = try writer.write("-");
}
},
.foreground => |fg_color| {
_ = try writer.write("F");
if (fg_color) |color| {
_ = try color.write(&writer);
} else {
_ = try writer.write("-");
}
},
.font => |font_index| {
if (font_index) |idx| {
_ = try writer.print("T{}", .{font_index});
} else {
_ = try writer.write("T-");
}
},
.underline => |ul_color| {
_ = try writer.write("U");
if (ul_color) |color| {
_ = try color.write(&writer);
} else {
_ = try writer.write("-");
}
},
.click => |btn_struct| {
if (btn_struct) |btn| {
if (btn.button) |button| {
_ = try writer.print("A{}:{s}:", .{ button, btn.command });
} else {
_ = try writer.print("A:{s}:", .{btn.command});
}
}
},
.monitor => |monitor_value| {
_ = try writer.write("S");
switch (monitor_value) {
.next => {
_ = try writer.write("+");
},
.previous => {
_ = try writer.write("-");
},
.first => {
_ = try writer.write("f");
},
.last => {
_ = try writer.write("l");
},
.nth => |monitor_index| {
_ = try writer.print("{}", .{monitor_index});
},
}
},
.attrmod => |attr_struct| {
_ = try writer.write(switch (attr_struct.modifier) {
.set => "+",
.unset => "-",
.toggle => "!",
});
_ = try writer.write(switch (attr_struct.attribute) {
.overline => "o",
.underline => "u",
});
},
}
_ = try writer.write("}");
}
};
// TESTS //
fn expectProperty(expected: []const u8, prop: Property) void {
var str = prop.toString(std.testing.allocator) catch unreachable;
defer std.testing.allocator.free(str);
std.testing.expectEqualStrings(expected, str);
}
test "property to string" {
expectProperty("%{R}", .swap);
expectProperty("%{l}", .{ .alignment = .left });
expectProperty("%{c}", .{ .alignment = .center });
expectProperty("%{r}", .{ .alignment = .right });
expectProperty("%{O16}", .{ .offset = 16 });
expectProperty("%{B#deadbeef}", .{ .background = comptime try Color.fromString("#deadbeef") });
expectProperty("%{B-}", .{ .background = null });
expectProperty("%{F#deadbeef}", .{ .foreground = comptime try Color.fromString("#deadbeef") });
expectProperty("%{F-}", .{ .foreground = null });
expectProperty("%{T1}", .{ .font = 1 });
expectProperty("%{T-}", .{ .font = null });
expectProperty("%{U#deadbeef}", .{ .underline = comptime try Color.fromString("#deadbeef") });
expectProperty("%{U-}", .{ .underline = null });
expectProperty("%{A:reboot:}", .{ .click = .{ .button = null, .command = "reboot" } });
expectProperty("%{A3:halt:}", .{ .click = .{ .button = 3, .command = "halt" } });
expectProperty("%{S+}", .{ .monitor = .next });
expectProperty("%{S-}", .{ .monitor = .previous });
expectProperty("%{Sf}", .{ .monitor = .first });
expectProperty("%{Sl}", .{ .monitor = .last });
expectProperty("%{S5}", .{ .monitor = .{ .nth = 5 } });
expectProperty("%{+o}", .{ .attrmod = .{ .attribute = .overline, .modifier = .set } });
expectProperty("%{-o}", .{ .attrmod = .{ .attribute = .overline, .modifier = .unset } });
expectProperty("%{!o}", .{ .attrmod = .{ .attribute = .overline, .modifier = .toggle } });
expectProperty("%{+u}", .{ .attrmod = .{ .attribute = .underline, .modifier = .set } });
expectProperty("%{-u}", .{ .attrmod = .{ .attribute = .underline, .modifier = .unset } });
expectProperty("%{!u}", .{ .attrmod = .{ .attribute = .underline, .modifier = .toggle } });
}
|
src/Formatter/property.zig
|
const std = @import("std");
const aoc = @import("aoc-lib.zig");
fn readBits(comptime T: type, bits: []const u1, i: *usize) T {
const bit_count = @typeInfo(T).Int.bits;
var j: usize = 0;
var v: T = 0;
if (bit_count == 1) {
v = @as(T, bits[i.*]);
i.* += 1;
return v;
}
while (j < bit_count) : (j += 1) {
v = (v << 1) | @as(T, bits[i.*]);
i.* += 1;
}
return v;
}
pub fn readPacket(alloc: std.mem.Allocator, bits: []const u1, i: *usize) anyerror![2]usize {
var ver: u3 = readBits(u3, bits, i);
var kind: u3 = readBits(u3, bits, i);
if (kind == 4) {
var n: usize = 0;
while (true) {
var a = readBits(u5, bits, i);
n = (n << 4) + @as(usize, a & 0xf);
if (a <= 0xf) {
break;
}
}
return [2]usize{ ver, n };
}
var vs = @as(usize, ver);
var argsL = std.ArrayList(usize).init(alloc);
defer argsL.deinit();
var lti = readBits(u1, bits, i);
if (lti == 0) { // 15-bit
var l = readBits(u15, bits, i);
var end = i.* + l;
while (i.* < end) {
var sub = try readPacket(alloc, bits, i);
vs += sub[0];
try argsL.append(sub[1]);
}
} else {
var l = readBits(u11, bits, i);
var j: usize = 0;
while (j < l) : (j += 1) {
var sub = try readPacket(alloc, bits, i);
vs += sub[0];
try argsL.append(sub[1]);
}
}
var args = argsL.items;
var res: usize = 0;
switch (kind) {
0 => {
var k: usize = 0;
while (k < args.len) : (k += 1) {
res += args[k];
}
},
1 => {
res = 1;
var k: usize = 0;
while (k < args.len) : (k += 1) {
res *= args[k];
}
},
2 => {
res = args[0];
var k: usize = 1;
while (k < args.len) : (k += 1) {
if (res > args[k]) {
res = args[k];
}
}
},
3 => {
res = args[0];
var k: usize = 1;
while (k < args.len) : (k += 1) {
if (res < args[k]) {
res = args[k];
}
}
},
5 => {
if (args[0] > args[1]) {
res = 1;
} else {
res = 0;
}
},
6 => {
if (args[0] < args[1]) {
res = 1;
} else {
res = 0;
}
},
7 => {
if (args[0] == args[1]) {
res = 1;
} else {
res = 0;
}
},
else => {
unreachable;
},
}
return [2]usize{ vs, res };
}
pub fn parts(alloc: std.mem.Allocator, inp: []const u8) ![2]usize {
var bits = try alloc.alloc(u1, inp.len * 4);
std.mem.set(u1, bits[0..], 0);
defer alloc.free(bits);
var i: usize = 0;
while (i < (inp.len - 1)) : (i += 1) {
var v = inp[i] - '0';
if (v > 9) {
v -= 7;
}
if ((v & 0b0001) != 0) bits[i * 4 + 3] = 1;
if ((v & 0b0010) != 0) bits[i * 4 + 2] = 1;
if ((v & 0b0100) != 0) bits[i * 4 + 1] = 1;
if ((v & 0b1000) != 0) bits[i * 4 + 0] = 1;
}
i = 0;
return readPacket(alloc, bits, &i);
}
test "part1" {
var t1a = try parts(aoc.talloc, test1afile);
try aoc.assertEq(@as(usize, 6), t1a[0]);
var t1b = try parts(aoc.talloc, test1bfile);
try aoc.assertEq(@as(usize, 9), t1b[0]);
var t1c = try parts(aoc.talloc, test1cfile);
try aoc.assertEq(@as(usize, 14), t1c[0]);
var t1d = try parts(aoc.talloc, test1dfile);
try aoc.assertEq(@as(usize, 16), t1d[0]);
var t1e = try parts(aoc.talloc, test1efile);
try aoc.assertEq(@as(usize, 12), t1e[0]);
var t1f = try parts(aoc.talloc, test1ffile);
try aoc.assertEq(@as(usize, 23), t1f[0]);
var t1g = try parts(aoc.talloc, test1gfile);
try aoc.assertEq(@as(usize, 31), t1g[0]);
var t2a = try parts(aoc.talloc, test2afile);
try aoc.assertEq(@as(usize, 14), t2a[0]);
var t2b = try parts(aoc.talloc, test2bfile);
try aoc.assertEq(@as(usize, 8), t2b[0]);
var t2c = try parts(aoc.talloc, test2cfile);
try aoc.assertEq(@as(usize, 15), t2c[0]);
var t2d = try parts(aoc.talloc, test2dfile);
try aoc.assertEq(@as(usize, 11), t2d[0]);
var t2e = try parts(aoc.talloc, test2efile);
try aoc.assertEq(@as(usize, 13), t2e[0]);
var t2f = try parts(aoc.talloc, test2ffile);
try aoc.assertEq(@as(usize, 19), t2f[0]);
var t2g = try parts(aoc.talloc, test2gfile);
try aoc.assertEq(@as(usize, 16), t2g[0]);
var t2h = try parts(aoc.talloc, test2hfile);
try aoc.assertEq(@as(usize, 20), t2h[0]);
var r = try parts(aoc.talloc, aoc.inputfile);
try aoc.assertEq(@as(usize, 951), r[0]);
}
test "part2" {
var t1a = try parts(aoc.talloc, "D2FE28\n");
try aoc.assertEq(@as(usize, 2021), t1a[1]);
var t1b = try parts(aoc.talloc, "38006F45291200\n");
try aoc.assertEq(@as(usize, 1), t1b[1]);
var t1c = try parts(aoc.talloc, "EE00D40C823060\n");
try aoc.assertEq(@as(usize, 3), t1c[1]);
var t1d = try parts(aoc.talloc, "8A004A801A8002F478\n");
try aoc.assertEq(@as(usize, 15), t1d[1]);
var t1e = try parts(aoc.talloc, "620080001611562C8802118E34\n");
try aoc.assertEq(@as(usize, 46), t1e[1]);
var t1f = try parts(aoc.talloc, "C0015000016115A2E0802F182340\n");
try aoc.assertEq(@as(usize, 46), t1f[1]);
var t1g = try parts(aoc.talloc, "A0016C880162017C3686B18A3D4780\n");
try aoc.assertEq(@as(usize, 54), t1g[1]);
var t2a = try parts(aoc.talloc, "C200B40A82\n");
try aoc.assertEq(@as(usize, 3), t2a[1]);
var t2b = try parts(aoc.talloc, "04005AC33890\n");
try aoc.assertEq(@as(usize, 54), t2b[1]);
var t2c = try parts(aoc.talloc, "880086C3E88112\n");
try aoc.assertEq(@as(usize, 7), t2c[1]);
var t2d = try parts(aoc.talloc, "CE00C43D881120\n");
try aoc.assertEq(@as(usize, 9), t2d[1]);
var t2e = try parts(aoc.talloc, "D8005AC2A8F0\n");
try aoc.assertEq(@as(usize, 1), t2e[1]);
var t2f = try parts(aoc.talloc, "F600BC2D8F\n");
try aoc.assertEq(@as(usize, 0), t2f[1]);
var t2g = try parts(aoc.talloc, "9C005AC2F8F0\n");
try aoc.assertEq(@as(usize, 0), t2g[1]);
var t2h = try parts(aoc.talloc, "9C0141080250320F1802104A08\n");
try aoc.assertEq(@as(usize, 1), t2h[1]);
var r = try parts(aoc.talloc, aoc.inputfile);
try aoc.assertEq(@as(usize, 902198718880), r[1]);
}
fn day(inp: []const u8, bench: bool) anyerror!void {
var p = try parts(aoc.halloc, inp);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p[0], p[1] });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day);
}
pub const test1afile = @embedFile("test1a.txt");
pub const test1bfile = @embedFile("test1b.txt");
pub const test1cfile = @embedFile("test1c.txt");
pub const test1dfile = @embedFile("test1d.txt");
pub const test1efile = @embedFile("test1e.txt");
pub const test1ffile = @embedFile("test1f.txt");
pub const test1gfile = @embedFile("test1g.txt");
pub const test2afile = @embedFile("test2a.txt");
pub const test2bfile = @embedFile("test2b.txt");
pub const test2cfile = @embedFile("test2c.txt");
pub const test2dfile = @embedFile("test2d.txt");
pub const test2efile = @embedFile("test2e.txt");
pub const test2ffile = @embedFile("test2f.txt");
pub const test2gfile = @embedFile("test2g.txt");
pub const test2hfile = @embedFile("test2h.txt");
|
2021/16/aoc.zig
|
const std = @import("std");
const tvg = @import("tvg");
const args = @import("args");
fn printUsage(stream: anytype) !void {
try stream.writeAll(
\\tvg-render [-o <file.tga>] [-g <geometry>] [-a] [-s <scale>] <input>
\\
\\Renders a TinyVG vector graphic into a TGA file.
\\
\\Options:
\\ -h, --help Prints this text.
\\ -o, --output <file> The TGA file that should be written. Default is <input> with .tga extension.
\\ -g, --geometry Specifies the output geometry of the image. Has the format <width>x<height>.
\\ -s, --super-sampling Sets the super-sampling size for the image. Use 1 for no super sampling and 16 for very high quality.
\\ -a, --anti-alias Sets the super-sampling size to 4. This is usually decent enough for most images.
\\
);
}
const CliOptions = struct {
help: bool = false,
output: ?[]const u8 = null,
geometry: ?Geometry = null,
@"anti-alias": bool = false,
@"super-sampling": ?u32 = null,
pub const shorthands = .{
.o = "output",
.g = "geometry",
.h = "help",
.a = "anti-alias",
.s = "super-sampling",
};
};
pub fn main() !u8 {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const cli = args.parseForCurrentProcess(CliOptions, allocator, .print) catch return 1;
defer cli.deinit();
// const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
const stderr = std.io.getStdErr().writer();
if (cli.options.help) {
try printUsage(stdout);
return 0;
}
if (cli.positionals.len != 1) {
try stderr.writeAll("Expected exactly one positional argument!\n");
try printUsage(stderr);
return 1;
}
const read_stdin = std.mem.eql(u8, cli.positionals[0], "-");
const write_stdout = if (cli.options.output) |o|
std.mem.eql(u8, o, "-")
else
false;
if (read_stdin and cli.options.output == null) {
try stderr.writeAll("Requires --output file name set when reading from stdin!\n");
try printUsage(stderr);
return 1;
}
var source_file: std.fs.File = if (read_stdin)
std.io.getStdIn()
else
try std.fs.cwd().openFile(cli.positionals[0], .{});
defer if (!read_stdin)
source_file.close();
var super_scale: u32 = 1;
if (cli.options.@"anti-alias") {
super_scale = 4;
}
if (cli.options.@"super-sampling") |scaling| {
if (scaling == 0 or scaling > 32) {
try stderr.writeAll("Superscaling is only allowed for scales between 1 and 32.\n");
return 1;
}
super_scale = scaling;
}
// TODO: Render here
var image = try tvg.rendering.renderStream(
allocator,
allocator,
if (cli.options.geometry) |geom|
tvg.rendering.SizeHint{ .size = tvg.rendering.Size{ .width = geom.width, .height = geom.height } }
else
.inherit,
@intToEnum(tvg.rendering.AntiAliasing, super_scale),
source_file.reader(),
);
defer image.deinit(allocator);
for (image.pixels) |*c| {
std.mem.swap(u8, &c.r, &c.b);
}
{
const width = try std.math.cast(u16, image.width);
const height = try std.math.cast(u16, image.height);
var dest_file: std.fs.File = if (write_stdout)
std.io.getStdIn()
else blk: {
var out_name = cli.options.output orelse try std.mem.concat(allocator, u8, &[_][]const u8{
cli.positionals[0][0..(cli.positionals[0].len - std.fs.path.extension(cli.positionals[0]).len)],
".tga",
});
break :blk try std.fs.cwd().createFile(out_name, .{});
};
defer if (!read_stdin)
dest_file.close();
var writer = dest_file.writer();
try dumpTga(writer, width, height, image.pixels);
}
return 0;
}
fn dumpTga(src_writer: anytype, width: u16, height: u16, pixels: []const tvg.rendering.Color8) !void {
var buffered_writer = std.io.bufferedWriter(src_writer);
var writer = buffered_writer.writer();
std.debug.assert(pixels.len == @as(u32, width) * height);
const image_id = "Hello, TGA!";
try writer.writeIntLittle(u8, @intCast(u8, image_id.len));
try writer.writeIntLittle(u8, 0); // color map type = no color map
try writer.writeIntLittle(u8, 2); // image type = uncompressed true-color image
// color map spec
try writer.writeIntLittle(u16, 0); // first index
try writer.writeIntLittle(u16, 0); // length
try writer.writeIntLittle(u8, 0); // number of bits per pixel
// image spec
try writer.writeIntLittle(u16, 0); // x origin
try writer.writeIntLittle(u16, 0); // y origin
try writer.writeIntLittle(u16, width); // width
try writer.writeIntLittle(u16, height); // height
try writer.writeIntLittle(u8, 32); // bits per pixel
try writer.writeIntLittle(u8, 8 | 0x20); // 0…3 => alpha channel depth = 8, 4…7 => direction=top left
try writer.writeAll(image_id);
try writer.writeAll(""); // color map data \o/
try writer.writeAll(std.mem.sliceAsBytes(pixels));
try buffered_writer.flush();
}
const Geometry = struct {
const Self = @This();
width: u32,
height: u32,
pub fn parse(str: []const u8) !Self {
if (std.mem.indexOfScalar(u8, str, 'x')) |index| {
return Geometry{
.width = try std.fmt.parseInt(u32, str[0..index], 10),
.height = try std.fmt.parseInt(u32, str[index + 1 ..], 10),
};
} else {
const v = try std.fmt.parseInt(u32, str, 10);
return Geometry{
.width = v,
.height = v,
};
}
}
};
|
src/tools/render.zig
|
const builtin = @import("builtin");
const std = @import("std");
const assert = std.debug.assert;
const segfault = true;
pub const JournalHeader = packed struct {
hash_chain_root: u128 = undefined,
prev_hash_chain_root: u128,
checksum: u128 = undefined,
magic: u64,
command: u32,
size: u32,
pub fn calculate_checksum(self: *const JournalHeader, entry: []const u8) u128 {
assert(entry.len >= @sizeOf(JournalHeader));
assert(entry.len == self.size);
const checksum_offset = @offsetOf(JournalHeader, "checksum");
const checksum_size = @sizeOf(@TypeOf(self.checksum));
assert(checksum_offset == 0 + 16 + 16);
assert(checksum_size == 16);
var target: [32]u8 = undefined;
std.crypto.hash.Blake3.hash(entry[checksum_offset + checksum_size ..], target[0..], .{});
return @bitCast(u128, target[0..checksum_size].*);
}
pub fn calculate_hash_chain_root(self: *const JournalHeader) u128 {
const hash_chain_root_size = @sizeOf(@TypeOf(self.hash_chain_root));
assert(hash_chain_root_size == 16);
const prev_hash_chain_root_offset = @offsetOf(JournalHeader, "prev_hash_chain_root");
const prev_hash_chain_root_size = @sizeOf(@TypeOf(self.prev_hash_chain_root));
assert(prev_hash_chain_root_offset == 0 + 16);
assert(prev_hash_chain_root_size == 16);
const checksum_offset = @offsetOf(JournalHeader, "checksum");
const checksum_size = @sizeOf(@TypeOf(self.checksum));
assert(checksum_offset == 0 + 16 + 16);
assert(checksum_size == 16);
assert(prev_hash_chain_root_offset + prev_hash_chain_root_size == checksum_offset);
const header = @bitCast([@sizeOf(JournalHeader)]u8, self.*);
const source = header[prev_hash_chain_root_offset .. checksum_offset + checksum_size];
assert(source.len == prev_hash_chain_root_size + checksum_size);
var target: [32]u8 = undefined;
std.crypto.hash.Blake3.hash(source, target[0..], .{});
if (segfault) {
return @bitCast(u128, target[0..hash_chain_root_size].*);
} else {
var array = target[0..hash_chain_root_size].*;
return @bitCast(u128, array);
}
}
pub fn set_checksum_and_hash_chain_root(self: *JournalHeader, entry: []const u8) void {
self.checksum = self.calculate_checksum(entry);
self.hash_chain_root = self.calculate_hash_chain_root();
}
};
test "fixed" {
if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
var buffer align(@alignOf(JournalHeader)) = [_]u8{0} ** 65536;
var entry = std.mem.bytesAsValue(JournalHeader, buffer[0..@sizeOf(JournalHeader)]);
entry.* = .{
.prev_hash_chain_root = 0,
.magic = 0,
.command = 0,
.size = 64 + 128,
};
entry.set_checksum_and_hash_chain_root(buffer[0..entry.size]);
try std.io.null_writer.print("{}\n", .{entry});
}
|
test/behavior/bugs/6781.zig
|
const std = @import("std");
const Image = @import("image.zig").Image;
const Allocator = std.mem.Allocator;
const BmpError = error {
InvalidHeader,
InvalidCompression,
UnsupportedFormat
};
pub fn read(allocator: *Allocator, path: []const u8) !Image {
const file = try std.fs.cwd().openFile(path, .{ .read = true });
const reader = file.reader();
var signature = try reader.readBytesNoEof(2);
if (!std.mem.eql(u8, &signature, "BM")) {
return BmpError.UnsupportedFormat;
}
var size = reader.readIntLittle(u32);
_ = try reader.readBytesNoEof(4); // skip the reserved bytes
var offset = try reader.readIntLittle(u32);
var dibSize = try reader.readIntLittle(u32);
if (dibSize == 108) { // BITMAPV4HEADER
var width = try reader.readIntLittle(i32);
var height = try reader.readIntLittle(i32);
var colorPlanes = try reader.readIntLittle(u16);
var bpp = try reader.readIntLittle(u16);
var compression = try reader.readIntLittle(u32);
var imageSize = try reader.readIntLittle(u32);
var horzRes = try reader.readIntLittle(i32);
var vertRes = try reader.readIntLittle(i32);
var colorsNum = try reader.readIntLittle(u32);
var importantColors = try reader.readIntLittle(u32);
try file.seekTo(offset);
const imgReader = (std.io.BufferedReader(16*1024, @TypeOf(reader)) {
.unbuffered_reader = reader
}).reader(); // the input is only buffered now as when seeking the file, the buffer isn't emptied
const bytesPerPixel = @intCast(i32, bpp/8);
var data = try allocator.alloc(u8, @intCast(usize, width*height*3)); // data is always in RGB format
var i: i32 = height-1;
var j: i32 = 0;
const bytesPerLine = width * bytesPerPixel;
if (bytesPerPixel == 1) {
while (i >= 0) {
j = 0;
while (j < width) {
const pos = @intCast(usize, j + i*bytesPerLine);
const gray = try imgReader.readByte();
data[pos] = gray;
data[pos+1] = gray;
data[pos+2] = gray;
j += 3;
}
const skipAhead: usize = @intCast(usize, @mod(width, 4));
try imgReader.skipBytes(skipAhead, .{});
i -= 1;
}
return Image {
.allocator = allocator,
.data = data,
.width = @intCast(usize, width),
.height = @intCast(usize, height),
.format = .RGB24
};
} else if (bytesPerPixel == 3) {
var pixel: [3]u8 = undefined; // BGR pixel
while (i >= 0) {
j = 0;
while (j < bytesPerLine) {
const pos = @intCast(usize, j + i*bytesPerLine);
_ = try imgReader.readAll(&pixel);
data[pos] = pixel[2];
data[pos+1] = pixel[1];
data[pos+2] = pixel[0];
j += 3; // 3 bytes per pixel
}
const skipAhead: usize = @intCast(usize, @mod(width, 4));
try imgReader.skipBytes(skipAhead, .{});
i -= 1;
}
return Image {
.allocator = allocator,
.data = data,
.width = @intCast(usize, width),
.height = @intCast(usize, height),
.format = .RGB24
};
} else {
return BmpError.UnsupportedFormat;
}
} else {
return BmpError.InvalidHeader;
}
}
|
didot-image/bmp.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const HashMap = std.AutoHashMap;
pub fn Grid(comptime T: type) type {
return struct {
m: usize,
n: usize,
data: []T,
allocator: Allocator,
const Self = @This();
pub fn init(alloc: Allocator, m: usize, n: usize) !Self {
var data = try alloc.alloc(T, m * n);
return Self{
.m = m,
.n = n,
.data = data,
.allocator = alloc,
};
}
pub fn deinit(self: Self) void {
self.allocator.free(self.data);
}
pub fn get(self: Self, i: usize, j: usize) T {
return self.data[self.getIdx(i, j)];
}
pub fn set(self: Self, i: usize, j: usize, elem: T) void {
self.data[self.getIdx(i, j)] = elem;
}
pub fn getIdx(self: Self, i: usize, j: usize) usize {
return i * self.n + j;
}
};
}
pub fn BinaryHeap(comptime T: type) type {
return struct {
heap: []*Node,
len: usize,
allocator: Allocator,
const Self = @This();
pub fn init(alloc: Allocator, nodes: []Node) !Self {
var heap = try alloc.alloc(*Node, nodes.len);
var instance = Self{ .heap = heap, .len = nodes.len, .allocator = alloc };
for (nodes) |*node, i| {
heap[i] = node;
node.idx = i;
}
instance.heapify();
return instance;
}
pub fn changePriority(self: Self, idx: usize, new_priority: i32) void {
const heap = self.heap;
heap[idx].priority = new_priority;
const prt = parent(idx);
if (heap[idx].priority < heap[prt].priority) {
self.bubbleUp(idx);
} else {
self.bubbleDown(idx);
}
}
pub fn pop(self: *Self) *const Node {
if (self.len == 0) unreachable;
var node = self.heap[0];
self.swap(0, self.len - 1);
node.idx = null;
self.len -= 1;
self.bubbleDown(0);
return node;
}
pub fn deinit(self: Self) void {
self.allocator.free(self.heap);
}
pub const Node = struct {
data: T,
priority: i32,
idx: ?usize = null,
};
fn heapify(self: *Self) void {
const len = self.len;
var i: usize = 0;
while (i < len) : (i += 1) {
const idx = len - i - 1;
self.bubbleDown(idx);
}
}
fn bubbleUp(self: Self, idx_: usize) void {
var idx = idx_;
const heap = self.heap;
while (idx != 0) {
const prt = parent(idx);
if (heap[prt].priority > heap[idx].priority) {
self.swap(idx, prt);
idx = prt;
} else break;
}
}
fn bubbleDown(self: Self, idx_: usize) void {
var idx = idx_;
const heap = self.heap;
const len = self.len;
while (idx < len) {
const lft = left(idx);
const rgt = right(idx);
if (lft >= len) break;
const p = heap[idx].priority;
const pl = heap[lft].priority;
if (rgt >= len) {
if (pl <= p) {
self.swap(lft, idx);
idx = lft;
} else break;
} else {
const pr = heap[rgt].priority;
if (pl <= pr and pl <= p) {
self.swap(lft, idx);
idx = lft;
} else if (pr <= pl and pr <= p) {
self.swap(rgt, idx);
idx = rgt;
} else break;
}
}
}
fn swap(self: Self, i: usize, j: usize) void {
const nodei = self.heap[i];
const nodej = self.heap[j];
nodei.idx = j;
nodej.idx = i;
self.heap[i] = nodej;
self.heap[j] = nodei;
}
fn left(idx: usize) usize {
return 2 * idx + 1;
}
fn right(idx: usize) usize {
return 2 * idx + 2;
}
fn parent(idx: usize) usize {
return (idx - 1) / 2;
}
};
}
/// Data must be unique!
pub fn BinaryHashHeap(comptime T: type) type {
return struct {
heap: ArrayList(Node),
idxmap: HashMap(T, usize),
const Self = @This();
pub fn init(alloc: Allocator) Self {
return .{
.heap = ArrayList(Node).init(alloc),
.idxmap = HashMap(T, usize).init(alloc),
};
}
pub fn add(self: *Self, item: T, priority: i32) !void {
const idx = self.heap.items.len;
try self.heap.append(.{
.data = item,
.priority = priority,
});
try self.idxmap.put(item, idx);
self.bubbleUp(idx);
}
pub fn getPriority(self: *Self, item: T) ?i32 {
const idx = self.idxmap.get(item) orelse return null;
return self.heap.items[idx].priority;
}
pub fn changePriority(self: *Self, item: T, new_priority: i32) void {
const heap = self.heap.items;
const idx = self.idxmap.get(item).?;
heap[idx].priority = new_priority;
const prt = parent(idx);
if (heap[idx].priority < heap[prt].priority) {
self.bubbleUp(idx);
} else {
self.bubbleDown(idx);
}
}
pub fn pop(self: *Self) Node {
const heap = self.heap.items;
if (heap.len == 0) unreachable;
var node = heap[0];
self.swap(0, heap.len - 1);
_ = self.idxmap.remove(node.data);
self.heap.shrinkRetainingCapacity(heap.len - 1);
self.bubbleDown(0);
return node;
}
pub fn deinit(self: *Self) void {
self.heap.deinit();
self.idxmap.deinit();
}
pub const Node = struct {
data: T,
priority: i32,
};
fn heapify(self: *Self) void {
const len = self.heap.items.len;
var i: usize = 0;
while (i < len) : (i += 1) {
const idx = len - i - 1;
self.bubbleDown(idx);
}
}
fn bubbleUp(self: *Self, idx_: usize) void {
var idx = idx_;
const heap = self.heap.items;
while (idx != 0) {
const prt = parent(idx);
if (heap[prt].priority > heap[idx].priority) {
self.swap(idx, prt);
idx = prt;
} else break;
}
}
fn bubbleDown(self: *Self, idx_: usize) void {
var idx = idx_;
const heap = self.heap.items;
const len = heap.len;
while (idx < len) {
const lft = left(idx);
const rgt = right(idx);
if (lft >= len) break;
const p = heap[idx].priority;
const pl = heap[lft].priority;
if (rgt >= len) {
if (pl <= p) {
self.swap(lft, idx);
idx = lft;
} else break;
} else {
const pr = heap[rgt].priority;
if (pl <= pr and pl <= p) {
self.swap(lft, idx);
idx = lft;
} else if (pr <= pl and pr <= p) {
self.swap(rgt, idx);
idx = rgt;
} else break;
}
}
}
fn swap(self: *Self, i: usize, j: usize) void {
const nodei = self.heap.items[i];
const nodej = self.heap.items[j];
self.idxmap.putAssumeCapacity(nodei.data, j);
self.idxmap.putAssumeCapacity(nodej.data, i);
self.heap.items[i] = nodej;
self.heap.items[j] = nodei;
}
fn left(idx: usize) usize {
return 2 * idx + 1;
}
fn right(idx: usize) usize {
return 2 * idx + 2;
}
fn parent(idx: usize) usize {
return (idx - 1) / 2;
}
};
}
pub fn sum(comptime T: type, slice: []const T) T {
var s: T = 0;
for (slice) |elem| {
s = s + elem;
}
return s;
}
pub fn getlines(buffer: []const u8) std.mem.TokenIterator(u8) {
return std.mem.tokenize(u8, buffer, "\r\n");
}
pub fn abs(x: anytype) @TypeOf(x) {
return std.math.absInt(x) catch unreachable;
}
test "BinaryHeap: add and remove min heap" {
const expectEqual = std.testing.expectEqual;
const alloc = std.testing.allocator;
var nodes = try alloc.alloc(BinaryHeap(i32).Node, 8);
defer alloc.free(nodes);
const items: [8]i32 = .{ 54, 12, 7, 23, 25, 13, 0, 0 };
for (items) |item, i| {
nodes[i] = BinaryHeap(i32).Node{ .data = item, .priority = item };
}
var queue = try BinaryHeap(i32).init(std.testing.allocator, nodes);
defer queue.deinit();
try expectEqual(@as(i32, 0), queue.pop().data);
try expectEqual(@as(i32, 0), queue.pop().data);
try expectEqual(@as(i32, 7), queue.pop().data);
try expectEqual(@as(i32, 12), queue.pop().data);
try expectEqual(@as(i32, 13), queue.pop().data);
try expectEqual(@as(i32, 23), queue.pop().data);
try expectEqual(@as(i32, 25), queue.pop().data);
try expectEqual(@as(i32, 54), queue.pop().data);
}
|
src/helper.zig
|
const std = @import("std");
usingnamespace @import("common.zig");
usingnamespace @import("lexer.zig");
usingnamespace @import("ast.zig");
usingnamespace @import("parser.zig");
usingnamespace @import("error_handler.zig");
usingnamespace @import("code_formatter.zig");
pub const TypeFlags = packed struct {
ready: bool = false,
size_set: bool = false,
generic: bool = false,
generic_set: bool = false,
};
pub const UnknownType: *const Type = &Type{ .kind = .Unknown };
pub const StructMember = struct {
name: String,
typ: *const Type,
};
pub const TypeKind = union(enum) {
Unknown: void,
Error: void,
Type: void,
Void: void,
Unreachable: void,
Bool: void,
Float: void,
Int: struct {
signed: bool,
},
Pointer: struct {
child: *const Type,
},
Slice: struct {
child: *const Type,
},
Array: struct {
child: *const Type,
len: TypeSize,
},
Struct: struct {
members: List(StructMember),
},
Function: struct {
params: List(*const Type),
returnType: *const Type,
},
};
pub const TypeSize = union(enum) {
Known: u64,
Unknown: void,
Generic: String,
pub fn is(self: *Self, tag: std.meta.Tag(@This())) bool {
return @as(std.meta.Tag(@This()), self.*) == tag;
}
};
pub const Type = struct {
flags: TypeFlags = TypeFlags{},
size: usize = 0,
alignment: usize = 0,
kind: TypeKind,
const Self = @This();
pub fn isGeneric(self: *Self) !bool {
switch (self.kind) {
.Pointer => |*typ| {
self.flags.generic = typ.child.isGeneric();
self.flags.generic_set = true;
return self.flags.generic;
},
.Slice => |*typ| {
self.flags.generic = typ.child.isGeneric();
self.flags.generic_set = true;
return self.flags.generic;
},
.Array => |*typ| {
const childIsGeneric = typ.child.isGeneric();
const lenIsGeneric = typ.len.is(.Generic);
self.flags.generic = childIsGeneric or lenIsGeneric;
self.flags.generic_set = true;
return self.flags.generic;
},
else => {
self.flags.generic = false;
self.flags.generic_set = true;
return false;
},
}
}
pub fn is(self: *const Self, tag: std.meta.Tag(TypeKind)) bool {
return @as(std.meta.Tag(TypeKind), self.kind) == tag;
}
pub fn format(
self: *const Self,
fmt: String,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
switch (self.kind) {
.Error => try writer.writeAll("<Error>"),
.Unknown => try writer.writeAll("<Unknown>"),
.Type => try writer.writeAll("type"),
.Void => try writer.writeAll("void"),
.Unreachable => try writer.writeAll("unreachable"),
.Bool => try std.fmt.format(writer, "b{}", .{self.size * 8}),
.Float => try std.fmt.format(writer, "f{}", .{self.size * 8}),
.Int => |*int| try std.fmt.format(writer, "{s}{}", .{
(if (int.signed) "i" else "u"),
self.size * 8,
}),
.Pointer => |*ptr| {
try std.fmt.format(writer, "^", .{});
try std.fmt.format(writer, "{}", .{ptr.child});
},
.Slice => |*slc| {
try std.fmt.format(writer, "[]", .{});
try std.fmt.format(writer, "{}", .{slc.child});
},
.Array => |*arr| {
switch (arr.len) {
.Known => |len| try std.fmt.format(writer, "[{}]", .{len}),
.Unknown => try std.fmt.format(writer, "[?]", .{}),
.Generic => |name| try std.fmt.format(writer, "[{s}]", .{name}),
}
try std.fmt.format(writer, "{}", .{arr.child});
},
.Struct => |*str| {
try std.fmt.format(writer, "struct", .{});
},
.Function => |*func| {
try writer.writeAll("fn(");
var i: usize = 0;
while (i < func.params.items.len) : (i += 1) {
if (i > 0) {
try writer.writeAll(", ");
}
try std.fmt.format(writer, "{}", .{func.params.items[i]});
}
try std.fmt.format(writer, ") -> {}", .{func.returnType});
},
//else => try writer.writeAll("<Unknown>"),
}
}
};
pub const TypeRegistry = struct {
allocator: std.heap.ArenaAllocator,
errorType: ?*Type = null,
typeType: ?*Type = null,
voidType: ?*Type = null,
boolTypes: [8]?*Type = [_]?*Type{null} ** 8,
const Self = @This();
pub fn init(allocator: *std.mem.Allocator) !Self {
return Self{
.allocator = std.heap.ArenaAllocator.init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.allocator.deinit();
}
pub fn allocTypeArray(self: *Self, size: usize) !List(*const Type) {
return List(*const Type).init(&self.allocator.allocator);
}
pub fn getErrorType(self: *Self) !*const Type {
if (self.errorType == null) {
self.errorType = try self.allocator.allocator.create(Type);
self.errorType.?.* = Type{
.flags = .{
.ready = true,
.size_set = true,
.generic = false,
.generic_set = true,
},
.size = 0,
.alignment = 0,
.kind = .Error,
};
}
return self.errorType.?;
}
pub fn getTypeType(self: *Self) !*const Type {
if (self.typeType == null) {
self.typeType = try self.allocator.allocator.create(Type);
self.typeType.?.* = Type{
.flags = .{
.ready = true,
.size_set = true,
.generic = false,
.generic_set = true,
},
.size = 0,
.alignment = 0,
.kind = .Type,
};
}
return self.typeType.?;
}
pub fn getVoidType(self: *Self) !*const Type {
if (self.voidType == null) {
self.voidType = try self.allocator.allocator.create(Type);
self.voidType.?.* = Type{
.flags = .{
.ready = true,
.size_set = true,
.generic = false,
.generic_set = true,
},
.size = 0,
.alignment = 0,
.kind = .Void,
};
}
return self.voidType.?;
}
pub fn getBoolType(self: *Self, size: usize) !*Type {
std.debug.assert(size > 0);
const index = size - 1;
if (self.boolTypes[index] == null) {
var typ = try self.allocator.allocator.create(Type);
typ.* = Type{
.flags = .{
.ready = true,
.size_set = true,
.generic = false,
.generic_set = true,
},
.size = size,
.alignment = 1,
.kind = .Bool,
};
self.boolTypes[index] = typ;
}
return self.boolTypes[index].?;
}
pub fn getIntType(self: *Self, size: usize, signed: bool, alignment: ?usize) !*Type {
var typ = try self.allocator.allocator.create(Type);
typ.* = Type{
.flags = .{
.ready = true,
.size_set = true,
.generic = false,
.generic_set = true,
},
.size = size,
.alignment = alignment orelse size,
.kind = TypeKind{ .Int = .{
.signed = signed,
} },
};
return typ;
}
pub fn getFunctionType(
self: *Self,
params: List(*const Type),
returnType: *const Type,
) !*const Type {
var typ = try self.allocator.allocator.create(Type);
typ.* = Type{
.flags = .{
.ready = true,
.size_set = true,
.generic = false,
.generic_set = true,
},
.size = 8, // @todo: size of pointer
.alignment = 8,
.kind = .{ .Function = .{
.params = params,
.returnType = returnType,
} },
};
return typ;
}
pub fn createFromNativeType(self: *Self, comptime T: type) !*const Type {
const typeInfo = @typeInfo(T);
var size: usize = 0;
var alignment: usize = 0;
var kind: TypeKind = .Unknown;
switch (typeInfo) {
.Void => return self.getVoidType(),
.Bool => return self.getBoolType(1),
.Int => |*info| return self.getIntType(info.bits / 8, if (info.signedness == .signed) true else false, null),
.Fn => |*info| {
var params = List(*const Type).init(&self.allocator.allocator);
inline for (info.args) |arg, i| {
try params.append(try self.createFromNativeType(arg.arg_type.?));
}
size = 8;
alignment = 8;
kind = .{ .Function = .{
.params = params,
.returnType = if (info.return_type) |typ| try self.createFromNativeType(typ) else try self.getVoidType(),
} };
},
else => @compileError("Not implemented: createFromNativeType(" ++ @typeName(T) ++ ")"),
}
var typ = try self.allocator.allocator.create(Type);
typ.* = Type{
.flags = .{
.ready = true,
.size_set = true,
.generic = false,
.generic_set = true,
},
.size = size,
.alignment = alignment,
.kind = kind,
};
return typ;
}
};
|
src/types.zig
|
pub const TVI_ROOT = @import("../zig.zig").typedConst(HTREEITEM, @as(i32, -65536));
pub const TVI_FIRST = @import("../zig.zig").typedConst(HTREEITEM, @as(i32, -65535));
pub const TVI_LAST = @import("../zig.zig").typedConst(HTREEITEM, @as(i32, -65534));
pub const TVI_SORT = @import("../zig.zig").typedConst(HTREEITEM, @as(i32, -65533));
pub const BCN_FIRST = @as(u32, 4294966046);
pub const EM_SCROLLCARET = @as(u32, 183);
pub const EM_SETLIMITTEXT = @as(u32, 197);
pub const EM_GETLIMITTEXT = @as(u32, 213);
pub const EM_POSFROMCHAR = @as(u32, 214);
pub const EM_CHARFROMPOS = @as(u32, 215);
pub const FILEOPENORD = @as(u32, 1536);
pub const MULTIFILEOPENORD = @as(u32, 1537);
pub const PRINTDLGORD = @as(u32, 1538);
pub const PRNSETUPDLGORD = @as(u32, 1539);
pub const FINDDLGORD = @as(u32, 1540);
pub const REPLACEDLGORD = @as(u32, 1541);
pub const FONTDLGORD = @as(u32, 1542);
pub const FORMATDLGORD31 = @as(u32, 1543);
pub const FORMATDLGORD30 = @as(u32, 1544);
pub const RUNDLGORD = @as(u32, 1545);
pub const PAGESETUPDLGORD = @as(u32, 1546);
pub const NEWFILEOPENORD = @as(u32, 1547);
pub const PRINTDLGEXORD = @as(u32, 1549);
pub const PAGESETUPDLGORDMOTIF = @as(u32, 1550);
pub const COLORMGMTDLGORD = @as(u32, 1551);
pub const NEWFILEOPENV2ORD = @as(u32, 1552);
pub const NEWFILEOPENV3ORD = @as(u32, 1553);
pub const NEWFORMATDLGWITHLINK = @as(u32, 1591);
pub const IDC_MANAGE_LINK = @as(u32, 1592);
pub const WM_CTLCOLOR = @as(u32, 25);
pub const ILDRF_IMAGELOWQUALITY = @as(u32, 1);
pub const ILDRF_OVERLAYLOWQUALITY = @as(u32, 16);
pub const ILR_DEFAULT = @as(u32, 0);
pub const ILR_HORIZONTAL_LEFT = @as(u32, 0);
pub const ILR_HORIZONTAL_CENTER = @as(u32, 1);
pub const ILR_HORIZONTAL_RIGHT = @as(u32, 2);
pub const ILR_VERTICAL_TOP = @as(u32, 0);
pub const ILR_VERTICAL_CENTER = @as(u32, 16);
pub const ILR_VERTICAL_BOTTOM = @as(u32, 32);
pub const ILR_SCALE_CLIP = @as(u32, 0);
pub const ILR_SCALE_ASPECTRATIO = @as(u32, 256);
pub const ILGOS_ALWAYS = @as(u32, 0);
pub const ILGOS_FROMSTANDBY = @as(u32, 1);
pub const ILFIP_ALWAYS = @as(u32, 0);
pub const ILFIP_FROMSTANDBY = @as(u32, 1);
pub const ILDI_PURGE = @as(u32, 1);
pub const ILDI_STANDBY = @as(u32, 2);
pub const ILDI_RESETACCESS = @as(u32, 4);
pub const ILDI_QUERYACCESS = @as(u32, 8);
pub const MAXPROPPAGES = @as(u32, 100);
pub const PSP_DEFAULT = @as(u32, 0);
pub const PSP_DLGINDIRECT = @as(u32, 1);
pub const PSP_USEHICON = @as(u32, 2);
pub const PSP_USEICONID = @as(u32, 4);
pub const PSP_USETITLE = @as(u32, 8);
pub const PSP_RTLREADING = @as(u32, 16);
pub const PSP_HASHELP = @as(u32, 32);
pub const PSP_USEREFPARENT = @as(u32, 64);
pub const PSP_USECALLBACK = @as(u32, 128);
pub const PSP_PREMATURE = @as(u32, 1024);
pub const PSP_HIDEHEADER = @as(u32, 2048);
pub const PSP_USEHEADERTITLE = @as(u32, 4096);
pub const PSP_USEHEADERSUBTITLE = @as(u32, 8192);
pub const PSP_USEFUSIONCONTEXT = @as(u32, 16384);
pub const PSH_DEFAULT = @as(u32, 0);
pub const PSH_PROPTITLE = @as(u32, 1);
pub const PSH_USEHICON = @as(u32, 2);
pub const PSH_USEICONID = @as(u32, 4);
pub const PSH_PROPSHEETPAGE = @as(u32, 8);
pub const PSH_WIZARDHASFINISH = @as(u32, 16);
pub const PSH_WIZARD = @as(u32, 32);
pub const PSH_USEPSTARTPAGE = @as(u32, 64);
pub const PSH_NOAPPLYNOW = @as(u32, 128);
pub const PSH_USECALLBACK = @as(u32, 256);
pub const PSH_HASHELP = @as(u32, 512);
pub const PSH_MODELESS = @as(u32, 1024);
pub const PSH_RTLREADING = @as(u32, 2048);
pub const PSH_WIZARDCONTEXTHELP = @as(u32, 4096);
pub const PSH_WIZARD97 = @as(u32, 8192);
pub const PSH_WATERMARK = @as(u32, 32768);
pub const PSH_USEHBMWATERMARK = @as(u32, 65536);
pub const PSH_USEHPLWATERMARK = @as(u32, 131072);
pub const PSH_STRETCHWATERMARK = @as(u32, 262144);
pub const PSH_HEADER = @as(u32, 524288);
pub const PSH_USEHBMHEADER = @as(u32, 1048576);
pub const PSH_USEPAGELANG = @as(u32, 2097152);
pub const PSH_WIZARD_LITE = @as(u32, 4194304);
pub const PSH_NOCONTEXTHELP = @as(u32, 33554432);
pub const PSH_AEROWIZARD = @as(u32, 16384);
pub const PSH_RESIZABLE = @as(u32, 67108864);
pub const PSH_HEADERBITMAP = @as(u32, 134217728);
pub const PSH_NOMARGIN = @as(u32, 268435456);
pub const PSCB_INITIALIZED = @as(u32, 1);
pub const PSCB_PRECREATE = @as(u32, 2);
pub const PSCB_BUTTONPRESSED = @as(u32, 3);
pub const PSNRET_NOERROR = @as(u32, 0);
pub const PSNRET_INVALID = @as(u32, 1);
pub const PSNRET_INVALID_NOCHANGEPAGE = @as(u32, 2);
pub const PSNRET_MESSAGEHANDLED = @as(u32, 3);
pub const PSM_SETCURSEL = @as(u32, 1125);
pub const PSM_REMOVEPAGE = @as(u32, 1126);
pub const PSM_ADDPAGE = @as(u32, 1127);
pub const PSM_CHANGED = @as(u32, 1128);
pub const PSM_RESTARTWINDOWS = @as(u32, 1129);
pub const PSM_REBOOTSYSTEM = @as(u32, 1130);
pub const PSM_CANCELTOCLOSE = @as(u32, 1131);
pub const PSM_QUERYSIBLINGS = @as(u32, 1132);
pub const PSM_UNCHANGED = @as(u32, 1133);
pub const PSM_APPLY = @as(u32, 1134);
pub const PSM_SETTITLEA = @as(u32, 1135);
pub const PSM_SETTITLEW = @as(u32, 1144);
pub const PSM_SETWIZBUTTONS = @as(u32, 1136);
pub const PSWIZB_BACK = @as(u32, 1);
pub const PSWIZB_NEXT = @as(u32, 2);
pub const PSWIZB_FINISH = @as(u32, 4);
pub const PSWIZB_DISABLEDFINISH = @as(u32, 8);
pub const PSWIZBF_ELEVATIONREQUIRED = @as(u32, 1);
pub const PSWIZB_CANCEL = @as(u32, 16);
pub const PSM_PRESSBUTTON = @as(u32, 1137);
pub const PSBTN_BACK = @as(u32, 0);
pub const PSBTN_NEXT = @as(u32, 1);
pub const PSBTN_FINISH = @as(u32, 2);
pub const PSBTN_OK = @as(u32, 3);
pub const PSBTN_APPLYNOW = @as(u32, 4);
pub const PSBTN_CANCEL = @as(u32, 5);
pub const PSBTN_HELP = @as(u32, 6);
pub const PSBTN_MAX = @as(u32, 6);
pub const PSM_SETCURSELID = @as(u32, 1138);
pub const PSM_SETFINISHTEXTA = @as(u32, 1139);
pub const PSM_SETFINISHTEXTW = @as(u32, 1145);
pub const PSM_GETTABCONTROL = @as(u32, 1140);
pub const PSM_ISDIALOGMESSAGE = @as(u32, 1141);
pub const PSM_GETCURRENTPAGEHWND = @as(u32, 1142);
pub const PSM_INSERTPAGE = @as(u32, 1143);
pub const PSM_SETHEADERTITLEA = @as(u32, 1149);
pub const PSM_SETHEADERTITLEW = @as(u32, 1150);
pub const PSM_SETHEADERSUBTITLEA = @as(u32, 1151);
pub const PSM_SETHEADERSUBTITLEW = @as(u32, 1152);
pub const PSM_HWNDTOINDEX = @as(u32, 1153);
pub const PSM_INDEXTOHWND = @as(u32, 1154);
pub const PSM_PAGETOINDEX = @as(u32, 1155);
pub const PSM_INDEXTOPAGE = @as(u32, 1156);
pub const PSM_IDTOINDEX = @as(u32, 1157);
pub const PSM_INDEXTOID = @as(u32, 1158);
pub const PSM_GETRESULT = @as(u32, 1159);
pub const PSM_RECALCPAGESIZES = @as(u32, 1160);
pub const PSM_SETNEXTTEXTW = @as(u32, 1161);
pub const PSWIZB_SHOW = @as(u32, 0);
pub const PSWIZB_RESTORE = @as(u32, 1);
pub const PSM_SHOWWIZBUTTONS = @as(u32, 1162);
pub const PSM_ENABLEWIZBUTTONS = @as(u32, 1163);
pub const PSM_SETBUTTONTEXTW = @as(u32, 1164);
pub const ID_PSRESTARTWINDOWS = @as(u32, 2);
pub const WIZ_CXDLG = @as(u32, 276);
pub const WIZ_CYDLG = @as(u32, 140);
pub const WIZ_CXBMP = @as(u32, 80);
pub const WIZ_BODYX = @as(u32, 92);
pub const WIZ_BODYCX = @as(u32, 184);
pub const PROP_SM_CXDLG = @as(u32, 212);
pub const PROP_SM_CYDLG = @as(u32, 188);
pub const PROP_MED_CXDLG = @as(u32, 227);
pub const PROP_MED_CYDLG = @as(u32, 215);
pub const PROP_LG_CXDLG = @as(u32, 252);
pub const PROP_LG_CYDLG = @as(u32, 218);
pub const WM_CONTEXTMENU = @as(u32, 123);
pub const WM_UNICHAR = @as(u32, 265);
pub const WM_PRINTCLIENT = @as(u32, 792);
pub const EM_CANPASTE = @as(u32, 1074);
pub const EM_DISPLAYBAND = @as(u32, 1075);
pub const EM_EXGETSEL = @as(u32, 1076);
pub const EM_EXLIMITTEXT = @as(u32, 1077);
pub const EM_EXLINEFROMCHAR = @as(u32, 1078);
pub const EM_EXSETSEL = @as(u32, 1079);
pub const EM_FINDTEXT = @as(u32, 1080);
pub const EM_FORMATRANGE = @as(u32, 1081);
pub const EM_GETCHARFORMAT = @as(u32, 1082);
pub const EM_GETEVENTMASK = @as(u32, 1083);
pub const EM_GETOLEINTERFACE = @as(u32, 1084);
pub const EM_GETPARAFORMAT = @as(u32, 1085);
pub const EM_GETSELTEXT = @as(u32, 1086);
pub const EM_HIDESELECTION = @as(u32, 1087);
pub const EM_PASTESPECIAL = @as(u32, 1088);
pub const EM_REQUESTRESIZE = @as(u32, 1089);
pub const EM_SELECTIONTYPE = @as(u32, 1090);
pub const EM_SETBKGNDCOLOR = @as(u32, 1091);
pub const EM_SETCHARFORMAT = @as(u32, 1092);
pub const EM_SETEVENTMASK = @as(u32, 1093);
pub const EM_SETOLECALLBACK = @as(u32, 1094);
pub const EM_SETPARAFORMAT = @as(u32, 1095);
pub const EM_SETTARGETDEVICE = @as(u32, 1096);
pub const EM_STREAMIN = @as(u32, 1097);
pub const EM_STREAMOUT = @as(u32, 1098);
pub const EM_GETTEXTRANGE = @as(u32, 1099);
pub const EM_FINDWORDBREAK = @as(u32, 1100);
pub const EM_SETOPTIONS = @as(u32, 1101);
pub const EM_GETOPTIONS = @as(u32, 1102);
pub const EM_FINDTEXTEX = @as(u32, 1103);
pub const EM_GETWORDBREAKPROCEX = @as(u32, 1104);
pub const EM_SETWORDBREAKPROCEX = @as(u32, 1105);
pub const EM_SETUNDOLIMIT = @as(u32, 1106);
pub const EM_REDO = @as(u32, 1108);
pub const EM_CANREDO = @as(u32, 1109);
pub const EM_GETUNDONAME = @as(u32, 1110);
pub const EM_GETREDONAME = @as(u32, 1111);
pub const EM_STOPGROUPTYPING = @as(u32, 1112);
pub const EM_SETTEXTMODE = @as(u32, 1113);
pub const EM_GETTEXTMODE = @as(u32, 1114);
pub const EM_AUTOURLDETECT = @as(u32, 1115);
pub const AURL_ENABLEURL = @as(u32, 1);
pub const AURL_ENABLEEMAILADDR = @as(u32, 2);
pub const AURL_ENABLETELNO = @as(u32, 4);
pub const AURL_ENABLEEAURLS = @as(u32, 8);
pub const AURL_ENABLEDRIVELETTERS = @as(u32, 16);
pub const AURL_DISABLEMIXEDLGC = @as(u32, 32);
pub const EM_GETAUTOURLDETECT = @as(u32, 1116);
pub const EM_SETPALETTE = @as(u32, 1117);
pub const EM_GETTEXTEX = @as(u32, 1118);
pub const EM_GETTEXTLENGTHEX = @as(u32, 1119);
pub const EM_SHOWSCROLLBAR = @as(u32, 1120);
pub const EM_SETTEXTEX = @as(u32, 1121);
pub const EM_SETPUNCTUATION = @as(u32, 1124);
pub const EM_GETPUNCTUATION = @as(u32, 1125);
pub const EM_SETWORDWRAPMODE = @as(u32, 1126);
pub const EM_GETWORDWRAPMODE = @as(u32, 1127);
pub const EM_SETIMECOLOR = @as(u32, 1128);
pub const EM_GETIMECOLOR = @as(u32, 1129);
pub const EM_SETIMEOPTIONS = @as(u32, 1130);
pub const EM_GETIMEOPTIONS = @as(u32, 1131);
pub const EM_CONVPOSITION = @as(u32, 1132);
pub const EM_SETLANGOPTIONS = @as(u32, 1144);
pub const EM_GETLANGOPTIONS = @as(u32, 1145);
pub const EM_GETIMECOMPMODE = @as(u32, 1146);
pub const EM_FINDTEXTW = @as(u32, 1147);
pub const EM_FINDTEXTEXW = @as(u32, 1148);
pub const EM_RECONVERSION = @as(u32, 1149);
pub const EM_SETIMEMODEBIAS = @as(u32, 1150);
pub const EM_GETIMEMODEBIAS = @as(u32, 1151);
pub const EM_SETBIDIOPTIONS = @as(u32, 1224);
pub const EM_GETBIDIOPTIONS = @as(u32, 1225);
pub const EM_SETTYPOGRAPHYOPTIONS = @as(u32, 1226);
pub const EM_GETTYPOGRAPHYOPTIONS = @as(u32, 1227);
pub const EM_SETEDITSTYLE = @as(u32, 1228);
pub const EM_GETEDITSTYLE = @as(u32, 1229);
pub const SES_EMULATESYSEDIT = @as(u32, 1);
pub const SES_BEEPONMAXTEXT = @as(u32, 2);
pub const SES_EXTENDBACKCOLOR = @as(u32, 4);
pub const SES_MAPCPS = @as(u32, 8);
pub const SES_HYPERLINKTOOLTIPS = @as(u32, 8);
pub const SES_EMULATE10 = @as(u32, 16);
pub const SES_DEFAULTLATINLIGA = @as(u32, 16);
pub const SES_USECRLF = @as(u32, 32);
pub const SES_NOFOCUSLINKNOTIFY = @as(u32, 32);
pub const SES_USEAIMM = @as(u32, 64);
pub const SES_NOIME = @as(u32, 128);
pub const SES_ALLOWBEEPS = @as(u32, 256);
pub const SES_UPPERCASE = @as(u32, 512);
pub const SES_LOWERCASE = @as(u32, 1024);
pub const SES_NOINPUTSEQUENCECHK = @as(u32, 2048);
pub const SES_BIDI = @as(u32, 4096);
pub const SES_SCROLLONKILLFOCUS = @as(u32, 8192);
pub const SES_XLTCRCRLFTOCR = @as(u32, 16384);
pub const SES_DRAFTMODE = @as(u32, 32768);
pub const SES_USECTF = @as(u32, 65536);
pub const SES_HIDEGRIDLINES = @as(u32, 131072);
pub const SES_USEATFONT = @as(u32, 262144);
pub const SES_CUSTOMLOOK = @as(u32, 524288);
pub const SES_LBSCROLLNOTIFY = @as(u32, 1048576);
pub const SES_CTFALLOWEMBED = @as(u32, 2097152);
pub const SES_CTFALLOWSMARTTAG = @as(u32, 4194304);
pub const SES_CTFALLOWPROOFING = @as(u32, 8388608);
pub const SES_LOGICALCARET = @as(u32, 16777216);
pub const SES_WORDDRAGDROP = @as(u32, 33554432);
pub const SES_SMARTDRAGDROP = @as(u32, 67108864);
pub const SES_MULTISELECT = @as(u32, 134217728);
pub const SES_CTFNOLOCK = @as(u32, 268435456);
pub const SES_NOEALINEHEIGHTADJUST = @as(u32, 536870912);
pub const SES_MAX = @as(u32, 536870912);
pub const IMF_AUTOKEYBOARD = @as(u32, 1);
pub const IMF_AUTOFONT = @as(u32, 2);
pub const IMF_IMECANCELCOMPLETE = @as(u32, 4);
pub const IMF_IMEALWAYSSENDNOTIFY = @as(u32, 8);
pub const IMF_AUTOFONTSIZEADJUST = @as(u32, 16);
pub const IMF_UIFONTS = @as(u32, 32);
pub const IMF_NOIMPLICITLANG = @as(u32, 64);
pub const IMF_DUALFONT = @as(u32, 128);
pub const IMF_NOKBDLIDFIXUP = @as(u32, 512);
pub const IMF_NORTFFONTSUBSTITUTE = @as(u32, 1024);
pub const IMF_SPELLCHECKING = @as(u32, 2048);
pub const IMF_TKBPREDICTION = @as(u32, 4096);
pub const IMF_IMEUIINTEGRATION = @as(u32, 8192);
pub const ICM_NOTOPEN = @as(u32, 0);
pub const ICM_LEVEL3 = @as(u32, 1);
pub const ICM_LEVEL2 = @as(u32, 2);
pub const ICM_LEVEL2_5 = @as(u32, 3);
pub const ICM_LEVEL2_SUI = @as(u32, 4);
pub const ICM_CTF = @as(u32, 5);
pub const TO_ADVANCEDTYPOGRAPHY = @as(u32, 1);
pub const TO_SIMPLELINEBREAK = @as(u32, 2);
pub const TO_DISABLECUSTOMTEXTOUT = @as(u32, 4);
pub const TO_ADVANCEDLAYOUT = @as(u32, 8);
pub const EM_OUTLINE = @as(u32, 1244);
pub const EM_GETSCROLLPOS = @as(u32, 1245);
pub const EM_SETSCROLLPOS = @as(u32, 1246);
pub const EM_SETFONTSIZE = @as(u32, 1247);
pub const EM_GETZOOM = @as(u32, 1248);
pub const EM_SETZOOM = @as(u32, 1249);
pub const EM_GETVIEWKIND = @as(u32, 1250);
pub const EM_SETVIEWKIND = @as(u32, 1251);
pub const EM_GETPAGE = @as(u32, 1252);
pub const EM_SETPAGE = @as(u32, 1253);
pub const EM_GETHYPHENATEINFO = @as(u32, 1254);
pub const EM_SETHYPHENATEINFO = @as(u32, 1255);
pub const EM_GETPAGEROTATE = @as(u32, 1259);
pub const EM_SETPAGEROTATE = @as(u32, 1260);
pub const EM_GETCTFMODEBIAS = @as(u32, 1261);
pub const EM_SETCTFMODEBIAS = @as(u32, 1262);
pub const EM_GETCTFOPENSTATUS = @as(u32, 1264);
pub const EM_SETCTFOPENSTATUS = @as(u32, 1265);
pub const EM_GETIMECOMPTEXT = @as(u32, 1266);
pub const EM_ISIME = @as(u32, 1267);
pub const EM_GETIMEPROPERTY = @as(u32, 1268);
pub const EM_GETQUERYRTFOBJ = @as(u32, 1293);
pub const EM_SETQUERYRTFOBJ = @as(u32, 1294);
pub const EPR_0 = @as(u32, 0);
pub const EPR_270 = @as(u32, 1);
pub const EPR_180 = @as(u32, 2);
pub const EPR_90 = @as(u32, 3);
pub const EPR_SE = @as(u32, 5);
pub const CTFMODEBIAS_DEFAULT = @as(u32, 0);
pub const CTFMODEBIAS_FILENAME = @as(u32, 1);
pub const CTFMODEBIAS_NAME = @as(u32, 2);
pub const CTFMODEBIAS_READING = @as(u32, 3);
pub const CTFMODEBIAS_DATETIME = @as(u32, 4);
pub const CTFMODEBIAS_CONVERSATION = @as(u32, 5);
pub const CTFMODEBIAS_NUMERIC = @as(u32, 6);
pub const CTFMODEBIAS_HIRAGANA = @as(u32, 7);
pub const CTFMODEBIAS_KATAKANA = @as(u32, 8);
pub const CTFMODEBIAS_HANGUL = @as(u32, 9);
pub const CTFMODEBIAS_HALFWIDTHKATAKANA = @as(u32, 10);
pub const CTFMODEBIAS_FULLWIDTHALPHANUMERIC = @as(u32, 11);
pub const CTFMODEBIAS_HALFWIDTHALPHANUMERIC = @as(u32, 12);
pub const IMF_SMODE_PLAURALCLAUSE = @as(u32, 1);
pub const IMF_SMODE_NONE = @as(u32, 2);
pub const EMO_EXIT = @as(u32, 0);
pub const EMO_ENTER = @as(u32, 1);
pub const EMO_PROMOTE = @as(u32, 2);
pub const EMO_EXPAND = @as(u32, 3);
pub const EMO_MOVESELECTION = @as(u32, 4);
pub const EMO_GETVIEWMODE = @as(u32, 5);
pub const EMO_EXPANDSELECTION = @as(u32, 0);
pub const EMO_EXPANDDOCUMENT = @as(u32, 1);
pub const VM_NORMAL = @as(u32, 4);
pub const VM_OUTLINE = @as(u32, 2);
pub const VM_PAGE = @as(u32, 9);
pub const EM_INSERTTABLE = @as(u32, 1256);
pub const EM_GETAUTOCORRECTPROC = @as(u32, 1257);
pub const EM_SETAUTOCORRECTPROC = @as(u32, 1258);
pub const EM_CALLAUTOCORRECTPROC = @as(u32, 1279);
pub const ATP_NOCHANGE = @as(u32, 0);
pub const ATP_CHANGE = @as(u32, 1);
pub const ATP_NODELIMITER = @as(u32, 2);
pub const ATP_REPLACEALLTEXT = @as(u32, 4);
pub const EM_GETTABLEPARMS = @as(u32, 1289);
pub const EM_SETEDITSTYLEEX = @as(u32, 1299);
pub const EM_GETEDITSTYLEEX = @as(u32, 1300);
pub const SES_EX_NOTABLE = @as(u32, 4);
pub const SES_EX_NOMATH = @as(u32, 64);
pub const SES_EX_HANDLEFRIENDLYURL = @as(u32, 256);
pub const SES_EX_NOTHEMING = @as(u32, 524288);
pub const SES_EX_NOACETATESELECTION = @as(u32, 1048576);
pub const SES_EX_USESINGLELINE = @as(u32, 2097152);
pub const SES_EX_MULTITOUCH = @as(u32, 134217728);
pub const SES_EX_HIDETEMPFORMAT = @as(u32, 268435456);
pub const SES_EX_USEMOUSEWPARAM = @as(u32, 536870912);
pub const EM_GETSTORYTYPE = @as(u32, 1314);
pub const EM_SETSTORYTYPE = @as(u32, 1315);
pub const EM_GETELLIPSISMODE = @as(u32, 1329);
pub const EM_SETELLIPSISMODE = @as(u32, 1330);
pub const ELLIPSIS_MASK = @as(u32, 3);
pub const ELLIPSIS_NONE = @as(u32, 0);
pub const ELLIPSIS_END = @as(u32, 1);
pub const ELLIPSIS_WORD = @as(u32, 3);
pub const EM_SETTABLEPARMS = @as(u32, 1331);
pub const EM_GETTOUCHOPTIONS = @as(u32, 1334);
pub const EM_SETTOUCHOPTIONS = @as(u32, 1335);
pub const EM_INSERTIMAGE = @as(u32, 1338);
pub const EM_SETUIANAME = @as(u32, 1344);
pub const EM_GETELLIPSISSTATE = @as(u32, 1346);
pub const RTO_SHOWHANDLES = @as(u32, 1);
pub const RTO_DISABLEHANDLES = @as(u32, 2);
pub const RTO_READINGMODE = @as(u32, 3);
pub const EN_MSGFILTER = @as(u32, 1792);
pub const EN_REQUESTRESIZE = @as(u32, 1793);
pub const EN_SELCHANGE = @as(u32, 1794);
pub const EN_DROPFILES = @as(u32, 1795);
pub const EN_PROTECTED = @as(u32, 1796);
pub const EN_CORRECTTEXT = @as(u32, 1797);
pub const EN_STOPNOUNDO = @as(u32, 1798);
pub const EN_IMECHANGE = @as(u32, 1799);
pub const EN_SAVECLIPBOARD = @as(u32, 1800);
pub const EN_OLEOPFAILED = @as(u32, 1801);
pub const EN_OBJECTPOSITIONS = @as(u32, 1802);
pub const EN_LINK = @as(u32, 1803);
pub const EN_DRAGDROPDONE = @as(u32, 1804);
pub const EN_PARAGRAPHEXPANDED = @as(u32, 1805);
pub const EN_PAGECHANGE = @as(u32, 1806);
pub const EN_LOWFIRTF = @as(u32, 1807);
pub const EN_ALIGNLTR = @as(u32, 1808);
pub const EN_ALIGNRTL = @as(u32, 1809);
pub const EN_CLIPFORMAT = @as(u32, 1810);
pub const EN_STARTCOMPOSITION = @as(u32, 1811);
pub const EN_ENDCOMPOSITION = @as(u32, 1812);
pub const ENM_NONE = @as(u32, 0);
pub const ENM_CHANGE = @as(u32, 1);
pub const ENM_UPDATE = @as(u32, 2);
pub const ENM_SCROLL = @as(u32, 4);
pub const ENM_SCROLLEVENTS = @as(u32, 8);
pub const ENM_DRAGDROPDONE = @as(u32, 16);
pub const ENM_PARAGRAPHEXPANDED = @as(u32, 32);
pub const ENM_PAGECHANGE = @as(u32, 64);
pub const ENM_CLIPFORMAT = @as(u32, 128);
pub const ENM_KEYEVENTS = @as(u32, 65536);
pub const ENM_MOUSEEVENTS = @as(u32, 131072);
pub const ENM_REQUESTRESIZE = @as(u32, 262144);
pub const ENM_SELCHANGE = @as(u32, 524288);
pub const ENM_DROPFILES = @as(u32, 1048576);
pub const ENM_PROTECTED = @as(u32, 2097152);
pub const ENM_CORRECTTEXT = @as(u32, 4194304);
pub const ENM_IMECHANGE = @as(u32, 8388608);
pub const ENM_LANGCHANGE = @as(u32, 16777216);
pub const ENM_OBJECTPOSITIONS = @as(u32, 33554432);
pub const ENM_LINK = @as(u32, 67108864);
pub const ENM_LOWFIRTF = @as(u32, 134217728);
pub const ENM_STARTCOMPOSITION = @as(u32, 268435456);
pub const ENM_ENDCOMPOSITION = @as(u32, 536870912);
pub const ENM_GROUPTYPINGCHANGE = @as(u32, 1073741824);
pub const ENM_HIDELINKTOOLTIP = @as(u32, 2147483648);
pub const ES_SAVESEL = @as(u32, 32768);
pub const ES_SUNKEN = @as(u32, 16384);
pub const ES_DISABLENOSCROLL = @as(u32, 8192);
pub const ES_SELECTIONBAR = @as(u32, 16777216);
pub const ES_NOOLEDRAGDROP = @as(u32, 8);
pub const ES_EX_NOCALLOLEINIT = @as(u32, 0);
pub const ES_VERTICAL = @as(u32, 4194304);
pub const ES_NOIME = @as(u32, 524288);
pub const ES_SELFIME = @as(u32, 262144);
pub const ECO_AUTOWORDSELECTION = @as(u32, 1);
pub const ECO_AUTOVSCROLL = @as(u32, 64);
pub const ECO_AUTOHSCROLL = @as(u32, 128);
pub const ECO_NOHIDESEL = @as(u32, 256);
pub const ECO_READONLY = @as(u32, 2048);
pub const ECO_WANTRETURN = @as(u32, 4096);
pub const ECO_SAVESEL = @as(u32, 32768);
pub const ECO_SELECTIONBAR = @as(u32, 16777216);
pub const ECO_VERTICAL = @as(u32, 4194304);
pub const ECOOP_SET = @as(u32, 1);
pub const ECOOP_OR = @as(u32, 2);
pub const ECOOP_AND = @as(u32, 3);
pub const ECOOP_XOR = @as(u32, 4);
pub const WB_MOVEWORDPREV = @as(u32, 4);
pub const WB_MOVEWORDNEXT = @as(u32, 5);
pub const WB_PREVBREAK = @as(u32, 6);
pub const WB_NEXTBREAK = @as(u32, 7);
pub const PC_FOLLOWING = @as(u32, 1);
pub const PC_LEADING = @as(u32, 2);
pub const PC_OVERFLOW = @as(u32, 3);
pub const PC_DELIMITER = @as(u32, 4);
pub const WBF_WORDWRAP = @as(u32, 16);
pub const WBF_WORDBREAK = @as(u32, 32);
pub const WBF_OVERFLOW = @as(u32, 64);
pub const WBF_LEVEL1 = @as(u32, 128);
pub const WBF_LEVEL2 = @as(u32, 256);
pub const WBF_CUSTOM = @as(u32, 512);
pub const IMF_FORCENONE = @as(u32, 1);
pub const IMF_FORCEENABLE = @as(u32, 2);
pub const IMF_FORCEDISABLE = @as(u32, 4);
pub const IMF_CLOSESTATUSWINDOW = @as(u32, 8);
pub const IMF_VERTICAL = @as(u32, 32);
pub const IMF_FORCEACTIVE = @as(u32, 64);
pub const IMF_FORCEINACTIVE = @as(u32, 128);
pub const IMF_FORCEREMEMBER = @as(u32, 256);
pub const IMF_MULTIPLEEDIT = @as(u32, 1024);
pub const SCF_SELECTION = @as(u32, 1);
pub const SCF_WORD = @as(u32, 2);
pub const SCF_DEFAULT = @as(u32, 0);
pub const SCF_ALL = @as(u32, 4);
pub const SCF_USEUIRULES = @as(u32, 8);
pub const SCF_ASSOCIATEFONT = @as(u32, 16);
pub const SCF_NOKBUPDATE = @as(u32, 32);
pub const SCF_ASSOCIATEFONT2 = @as(u32, 64);
pub const SCF_SMARTFONT = @as(u32, 128);
pub const SCF_CHARREPFROMLCID = @as(u32, 256);
pub const SPF_DONTSETDEFAULT = @as(u32, 2);
pub const SPF_SETDEFAULT = @as(u32, 4);
pub const SF_TEXT = @as(u32, 1);
pub const SF_RTF = @as(u32, 2);
pub const SF_RTFNOOBJS = @as(u32, 3);
pub const SF_TEXTIZED = @as(u32, 4);
pub const SF_UNICODE = @as(u32, 16);
pub const SF_USECODEPAGE = @as(u32, 32);
pub const SF_NCRFORNONASCII = @as(u32, 64);
pub const SFF_WRITEXTRAPAR = @as(u32, 128);
pub const SFF_SELECTION = @as(u32, 32768);
pub const SFF_PLAINRTF = @as(u32, 16384);
pub const SFF_PERSISTVIEWSCALE = @as(u32, 8192);
pub const SFF_KEEPDOCINFO = @as(u32, 4096);
pub const SFF_PWD = @as(u32, 2048);
pub const SF_RTFVAL = @as(u32, 1792);
pub const MAX_TAB_STOPS = @as(u32, 32);
pub const MAX_TABLE_CELLS = @as(u32, 63);
pub const PFM_SPACEBEFORE = @as(u32, 64);
pub const PFM_SPACEAFTER = @as(u32, 128);
pub const PFM_LINESPACING = @as(u32, 256);
pub const PFM_STYLE = @as(u32, 1024);
pub const PFM_BORDER = @as(u32, 2048);
pub const PFM_SHADING = @as(u32, 4096);
pub const PFM_NUMBERINGSTYLE = @as(u32, 8192);
pub const PFM_NUMBERINGTAB = @as(u32, 16384);
pub const PFM_NUMBERINGSTART = @as(u32, 32768);
pub const PFM_KEEP = @as(u32, 131072);
pub const PFM_KEEPNEXT = @as(u32, 262144);
pub const PFM_PAGEBREAKBEFORE = @as(u32, 524288);
pub const PFM_NOLINENUMBER = @as(u32, 1048576);
pub const PFM_NOWIDOWCONTROL = @as(u32, 2097152);
pub const PFM_DONOTHYPHEN = @as(u32, 4194304);
pub const PFM_SIDEBYSIDE = @as(u32, 8388608);
pub const PFM_COLLAPSED = @as(u32, 16777216);
pub const PFM_OUTLINELEVEL = @as(u32, 33554432);
pub const PFM_BOX = @as(u32, 67108864);
pub const PFM_RESERVED2 = @as(u32, 134217728);
pub const PFM_TABLEROWDELIMITER = @as(u32, 268435456);
pub const PFM_TEXTWRAPPINGBREAK = @as(u32, 536870912);
pub const PFM_TABLE = @as(u32, 1073741824);
pub const PFN_BULLET = @as(u32, 1);
pub const PFN_ARABIC = @as(u32, 2);
pub const PFN_LCLETTER = @as(u32, 3);
pub const PFN_UCLETTER = @as(u32, 4);
pub const PFN_LCROMAN = @as(u32, 5);
pub const PFN_UCROMAN = @as(u32, 6);
pub const PFA_JUSTIFY = @as(u32, 4);
pub const PFA_FULL_INTERWORD = @as(u32, 4);
pub const WM_NOTIFY = @as(u32, 78);
pub const GCMF_GRIPPER = @as(u32, 1);
pub const GCMF_SPELLING = @as(u32, 2);
pub const GCMF_TOUCHMENU = @as(u32, 16384);
pub const GCMF_MOUSEMENU = @as(u32, 8192);
pub const OLEOP_DOVERB = @as(u32, 1);
pub const ST_DEFAULT = @as(u32, 0);
pub const ST_KEEPUNDO = @as(u32, 1);
pub const ST_SELECTION = @as(u32, 2);
pub const ST_NEWCHARS = @as(u32, 4);
pub const ST_UNICODE = @as(u32, 8);
pub const BOM_DEFPARADIR = @as(u32, 1);
pub const BOM_PLAINTEXT = @as(u32, 2);
pub const BOM_NEUTRALOVERRIDE = @as(u32, 4);
pub const BOM_CONTEXTREADING = @as(u32, 8);
pub const BOM_CONTEXTALIGNMENT = @as(u32, 16);
pub const BOM_LEGACYBIDICLASS = @as(u32, 64);
pub const BOM_UNICODEBIDI = @as(u32, 128);
pub const BOE_RTLDIR = @as(u32, 1);
pub const BOE_PLAINTEXT = @as(u32, 2);
pub const BOE_NEUTRALOVERRIDE = @as(u32, 4);
pub const BOE_CONTEXTREADING = @as(u32, 8);
pub const BOE_CONTEXTALIGNMENT = @as(u32, 16);
pub const BOE_FORCERECALC = @as(u32, 32);
pub const BOE_LEGACYBIDICLASS = @as(u32, 64);
pub const BOE_UNICODEBIDI = @as(u32, 128);
pub const FR_MATCHDIAC = @as(u32, 536870912);
pub const FR_MATCHKASHIDA = @as(u32, 1073741824);
pub const FR_MATCHALEFHAMZA = @as(u32, 2147483648);
pub const PFA_FULL_NEWSPAPER = @as(u32, 5);
pub const PFA_FULL_INTERLETTER = @as(u32, 6);
pub const PFA_FULL_SCALED = @as(u32, 7);
pub const PFA_FULL_GLYPHS = @as(u32, 8);
pub const AURL_ENABLEEA = @as(u32, 1);
pub const GCM_TOUCHMENU = @as(u32, 16384);
pub const GCM_MOUSEMENU = @as(u32, 8192);
pub const REO_NULL = @as(i32, 0);
pub const REO_READWRITEMASK = @as(i32, 2047);
pub const RECO_PASTE = @as(i32, 0);
pub const RECO_DROP = @as(i32, 1);
pub const RECO_COPY = @as(i32, 2);
pub const RECO_CUT = @as(i32, 3);
pub const RECO_DRAG = @as(i32, 4);
pub const S_MSG_KEY_IGNORED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 262657));
pub const TXTBIT_RICHTEXT = @as(u32, 1);
pub const TXTBIT_MULTILINE = @as(u32, 2);
pub const TXTBIT_READONLY = @as(u32, 4);
pub const TXTBIT_SHOWACCELERATOR = @as(u32, 8);
pub const TXTBIT_USEPASSWORD = @as(u32, 16);
pub const TXTBIT_HIDESELECTION = @as(u32, 32);
pub const TXTBIT_SAVESELECTION = @as(u32, 64);
pub const TXTBIT_AUTOWORDSEL = @as(u32, 128);
pub const TXTBIT_VERTICAL = @as(u32, 256);
pub const TXTBIT_SELBARCHANGE = @as(u32, 512);
pub const TXTBIT_WORDWRAP = @as(u32, 1024);
pub const TXTBIT_ALLOWBEEP = @as(u32, 2048);
pub const TXTBIT_DISABLEDRAG = @as(u32, 4096);
pub const TXTBIT_VIEWINSETCHANGE = @as(u32, 8192);
pub const TXTBIT_BACKSTYLECHANGE = @as(u32, 16384);
pub const TXTBIT_MAXLENGTHCHANGE = @as(u32, 32768);
pub const TXTBIT_SCROLLBARCHANGE = @as(u32, 65536);
pub const TXTBIT_CHARFORMATCHANGE = @as(u32, 131072);
pub const TXTBIT_PARAFORMATCHANGE = @as(u32, 262144);
pub const TXTBIT_EXTENTCHANGE = @as(u32, 524288);
pub const TXTBIT_CLIENTRECTCHANGE = @as(u32, 1048576);
pub const TXTBIT_USECURRENTBKG = @as(u32, 2097152);
pub const TXTBIT_NOTHREADREFCOUNT = @as(u32, 4194304);
pub const TXTBIT_SHOWPASSWORD = @as(u32, 8388608);
pub const TXTBIT_D2DDWRITE = @as(u32, 16777216);
pub const TXTBIT_D2DSIMPLETYPOGRAPHY = @as(u32, 33554432);
pub const TXTBIT_D2DPIXELSNAPPED = @as(u32, 67108864);
pub const TXTBIT_D2DSUBPIXELLINES = @as(u32, 134217728);
pub const TXTBIT_FLASHLASTPASSWORDCHAR = @as(u32, 268435456);
pub const TXTBIT_ADVANCEDINPUT = @as(u32, 536870912);
pub const TXES_ISDIALOG = @as(u32, 1);
pub const DA_LAST = @as(u32, 2147483647);
pub const DA_ERR = @as(i32, -1);
pub const DPAM_SORTED = @as(u32, 1);
pub const DPAM_NORMAL = @as(u32, 2);
pub const DPAM_UNION = @as(u32, 4);
pub const DPAM_INTERSECT = @as(u32, 8);
pub const DPAS_SORTED = @as(u32, 1);
pub const DPAS_INSERTBEFORE = @as(u32, 2);
pub const DPAS_INSERTAFTER = @as(u32, 4);
pub const MAX_THEMECOLOR = @as(u32, 64);
pub const MAX_THEMESIZE = @as(u32, 64);
pub const DTBG_CLIPRECT = @as(u32, 1);
pub const DTBG_DRAWSOLID = @as(u32, 2);
pub const DTBG_OMITBORDER = @as(u32, 4);
pub const DTBG_OMITCONTENT = @as(u32, 8);
pub const DTBG_COMPUTINGREGION = @as(u32, 16);
pub const DTBG_MIRRORDC = @as(u32, 32);
pub const DTBG_NOMIRROR = @as(u32, 64);
pub const DTT_GRAYED = @as(u32, 1);
pub const HTTB_BACKGROUNDSEG = @as(u32, 0);
pub const HTTB_FIXEDBORDER = @as(u32, 2);
pub const HTTB_CAPTION = @as(u32, 4);
pub const HTTB_RESIZINGBORDER_LEFT = @as(u32, 16);
pub const HTTB_RESIZINGBORDER_TOP = @as(u32, 32);
pub const HTTB_RESIZINGBORDER_RIGHT = @as(u32, 64);
pub const HTTB_RESIZINGBORDER_BOTTOM = @as(u32, 128);
pub const HTTB_SIZINGTEMPLATE = @as(u32, 256);
pub const HTTB_SYSTEMSIZINGMARGINS = @as(u32, 512);
pub const MAX_INTLIST_COUNT = @as(u32, 402);
pub const ETDT_DISABLE = @as(u32, 1);
pub const ETDT_ENABLE = @as(u32, 2);
pub const ETDT_USETABTEXTURE = @as(u32, 4);
pub const ETDT_USEAEROWIZARDTABTEXTURE = @as(u32, 8);
pub const WTNCA_NODRAWCAPTION = @as(u32, 1);
pub const WTNCA_NODRAWICON = @as(u32, 2);
pub const WTNCA_NOSYSMENU = @as(u32, 4);
pub const WTNCA_NOMIRRORHELP = @as(u32, 8);
pub const ODT_HEADER = @as(u32, 100);
pub const LVM_FIRST = @as(u32, 4096);
pub const TV_FIRST = @as(u32, 4352);
pub const HDM_FIRST = @as(u32, 4608);
pub const TCM_FIRST = @as(u32, 4864);
pub const PGM_FIRST = @as(u32, 5120);
pub const ECM_FIRST = @as(u32, 5376);
pub const BCM_FIRST = @as(u32, 5632);
pub const CBM_FIRST = @as(u32, 5888);
pub const CCM_FIRST = @as(u32, 8192);
pub const CCM_LAST = @as(u32, 8704);
pub const CCM_SETBKCOLOR = @as(u32, 8193);
pub const CCM_SETCOLORSCHEME = @as(u32, 8194);
pub const CCM_GETCOLORSCHEME = @as(u32, 8195);
pub const CCM_GETDROPTARGET = @as(u32, 8196);
pub const CCM_SETUNICODEFORMAT = @as(u32, 8197);
pub const CCM_GETUNICODEFORMAT = @as(u32, 8198);
pub const COMCTL32_VERSION = @as(u32, 6);
pub const CCM_SETVERSION = @as(u32, 8199);
pub const CCM_GETVERSION = @as(u32, 8200);
pub const CCM_SETNOTIFYWINDOW = @as(u32, 8201);
pub const CCM_SETWINDOWTHEME = @as(u32, 8203);
pub const CCM_DPISCALE = @as(u32, 8204);
pub const INFOTIPSIZE = @as(u32, 1024);
pub const MSGF_COMMCTRL_BEGINDRAG = @as(u32, 16896);
pub const MSGF_COMMCTRL_SIZEHEADER = @as(u32, 16897);
pub const MSGF_COMMCTRL_DRAGSELECT = @as(u32, 16898);
pub const MSGF_COMMCTRL_TOOLBARCUST = @as(u32, 16899);
pub const CDRF_DODEFAULT = @as(u32, 0);
pub const CDRF_NEWFONT = @as(u32, 2);
pub const CDRF_SKIPDEFAULT = @as(u32, 4);
pub const CDRF_DOERASE = @as(u32, 8);
pub const CDRF_SKIPPOSTPAINT = @as(u32, 256);
pub const CDRF_NOTIFYPOSTPAINT = @as(u32, 16);
pub const CDRF_NOTIFYITEMDRAW = @as(u32, 32);
pub const CDRF_NOTIFYSUBITEMDRAW = @as(u32, 32);
pub const CDRF_NOTIFYPOSTERASE = @as(u32, 64);
pub const CDDS_POSTERASE = @as(u32, 4);
pub const CDDS_ITEM = @as(u32, 65536);
pub const CDIS_SELECTED = @as(u32, 1);
pub const CDIS_GRAYED = @as(u32, 2);
pub const CDIS_DISABLED = @as(u32, 4);
pub const CDIS_CHECKED = @as(u32, 8);
pub const CDIS_FOCUS = @as(u32, 16);
pub const CDIS_DEFAULT = @as(u32, 32);
pub const CDIS_HOT = @as(u32, 64);
pub const CDIS_MARKED = @as(u32, 128);
pub const CDIS_INDETERMINATE = @as(u32, 256);
pub const CDIS_SHOWKEYBOARDCUES = @as(u32, 512);
pub const CDIS_NEARHOT = @as(u32, 1024);
pub const CDIS_OTHERSIDEHOT = @as(u32, 2048);
pub const CDIS_DROPHILITED = @as(u32, 4096);
pub const NM_GETCUSTOMSPLITRECT = @as(u32, 4294966049);
pub const CLR_NONE = @as(i32, -1);
pub const CLR_DEFAULT = @as(i32, -16777216);
pub const ILD_TRANSPARENT = @as(u32, 1);
pub const ILD_IMAGE = @as(u32, 32);
pub const ILD_ROP = @as(u32, 64);
pub const ILD_BLEND25 = @as(u32, 2);
pub const ILD_OVERLAYMASK = @as(u32, 3840);
pub const ILD_PRESERVEALPHA = @as(u32, 4096);
pub const ILD_SCALE = @as(u32, 8192);
pub const ILD_DPISCALE = @as(u32, 16384);
pub const ILD_ASYNC = @as(u32, 32768);
pub const ILS_NORMAL = @as(u32, 0);
pub const ILS_GLOW = @as(u32, 1);
pub const ILS_SHADOW = @as(u32, 2);
pub const ILS_SATURATE = @as(u32, 4);
pub const ILS_ALPHA = @as(u32, 8);
pub const ILGT_NORMAL = @as(u32, 0);
pub const ILGT_ASYNC = @as(u32, 1);
pub const ILP_NORMAL = @as(u32, 0);
pub const ILP_DOWNLEVEL = @as(u32, 1);
pub const HDS_HORZ = @as(u32, 0);
pub const HDS_BUTTONS = @as(u32, 2);
pub const HDS_HOTTRACK = @as(u32, 4);
pub const HDS_HIDDEN = @as(u32, 8);
pub const HDS_DRAGDROP = @as(u32, 64);
pub const HDS_FULLDRAG = @as(u32, 128);
pub const HDS_FILTERBAR = @as(u32, 256);
pub const HDS_FLAT = @as(u32, 512);
pub const HDS_CHECKBOXES = @as(u32, 1024);
pub const HDS_NOSIZING = @as(u32, 2048);
pub const HDS_OVERFLOW = @as(u32, 4096);
pub const HDFT_ISSTRING = @as(u32, 0);
pub const HDFT_ISNUMBER = @as(u32, 1);
pub const HDFT_ISDATE = @as(u32, 2);
pub const HDFT_HASNOVALUE = @as(u32, 32768);
pub const HDF_LEFT = @as(u32, 0);
pub const HDF_RIGHT = @as(u32, 1);
pub const HDF_CENTER = @as(u32, 2);
pub const HDF_JUSTIFYMASK = @as(u32, 3);
pub const HDF_RTLREADING = @as(u32, 4);
pub const HDF_BITMAP = @as(u32, 8192);
pub const HDF_STRING = @as(u32, 16384);
pub const HDF_OWNERDRAW = @as(u32, 32768);
pub const HDF_IMAGE = @as(u32, 2048);
pub const HDF_BITMAP_ON_RIGHT = @as(u32, 4096);
pub const HDF_SORTUP = @as(u32, 1024);
pub const HDF_SORTDOWN = @as(u32, 512);
pub const HDF_CHECKBOX = @as(u32, 64);
pub const HDF_CHECKED = @as(u32, 128);
pub const HDF_FIXEDWIDTH = @as(u32, 256);
pub const HDF_SPLITBUTTON = @as(u32, 16777216);
pub const HDIS_FOCUSED = @as(u32, 1);
pub const HDM_GETITEMCOUNT = @as(u32, 4608);
pub const HDM_INSERTITEMA = @as(u32, 4609);
pub const HDM_INSERTITEMW = @as(u32, 4618);
pub const HDM_DELETEITEM = @as(u32, 4610);
pub const HDM_GETITEMA = @as(u32, 4611);
pub const HDM_GETITEMW = @as(u32, 4619);
pub const HDM_SETITEMA = @as(u32, 4612);
pub const HDM_SETITEMW = @as(u32, 4620);
pub const HDM_LAYOUT = @as(u32, 4613);
pub const HHT_NOWHERE = @as(u32, 1);
pub const HHT_ONHEADER = @as(u32, 2);
pub const HHT_ONDIVIDER = @as(u32, 4);
pub const HHT_ONDIVOPEN = @as(u32, 8);
pub const HHT_ONFILTER = @as(u32, 16);
pub const HHT_ONFILTERBUTTON = @as(u32, 32);
pub const HHT_ABOVE = @as(u32, 256);
pub const HHT_BELOW = @as(u32, 512);
pub const HHT_TORIGHT = @as(u32, 1024);
pub const HHT_TOLEFT = @as(u32, 2048);
pub const HHT_ONITEMSTATEICON = @as(u32, 4096);
pub const HHT_ONDROPDOWN = @as(u32, 8192);
pub const HHT_ONOVERFLOW = @as(u32, 16384);
pub const HDSIL_NORMAL = @as(u32, 0);
pub const HDSIL_STATE = @as(u32, 1);
pub const HDM_HITTEST = @as(u32, 4614);
pub const HDM_GETITEMRECT = @as(u32, 4615);
pub const HDM_SETIMAGELIST = @as(u32, 4616);
pub const HDM_GETIMAGELIST = @as(u32, 4617);
pub const HDM_ORDERTOINDEX = @as(u32, 4623);
pub const HDM_CREATEDRAGIMAGE = @as(u32, 4624);
pub const HDM_GETORDERARRAY = @as(u32, 4625);
pub const HDM_SETORDERARRAY = @as(u32, 4626);
pub const HDM_SETHOTDIVIDER = @as(u32, 4627);
pub const HDM_SETBITMAPMARGIN = @as(u32, 4628);
pub const HDM_GETBITMAPMARGIN = @as(u32, 4629);
pub const HDM_SETFILTERCHANGETIMEOUT = @as(u32, 4630);
pub const HDM_EDITFILTER = @as(u32, 4631);
pub const HDM_CLEARFILTER = @as(u32, 4632);
pub const HDM_GETITEMDROPDOWNRECT = @as(u32, 4633);
pub const HDM_GETOVERFLOWRECT = @as(u32, 4634);
pub const HDM_GETFOCUSEDITEM = @as(u32, 4635);
pub const HDM_SETFOCUSEDITEM = @as(u32, 4636);
pub const CMB_MASKED = @as(u32, 2);
pub const TBSTATE_CHECKED = @as(u32, 1);
pub const TBSTATE_PRESSED = @as(u32, 2);
pub const TBSTATE_ENABLED = @as(u32, 4);
pub const TBSTATE_HIDDEN = @as(u32, 8);
pub const TBSTATE_INDETERMINATE = @as(u32, 16);
pub const TBSTATE_WRAP = @as(u32, 32);
pub const TBSTATE_ELLIPSES = @as(u32, 64);
pub const TBSTATE_MARKED = @as(u32, 128);
pub const TBSTYLE_BUTTON = @as(u32, 0);
pub const TBSTYLE_SEP = @as(u32, 1);
pub const TBSTYLE_CHECK = @as(u32, 2);
pub const TBSTYLE_GROUP = @as(u32, 4);
pub const TBSTYLE_DROPDOWN = @as(u32, 8);
pub const TBSTYLE_AUTOSIZE = @as(u32, 16);
pub const TBSTYLE_NOPREFIX = @as(u32, 32);
pub const TBSTYLE_TOOLTIPS = @as(u32, 256);
pub const TBSTYLE_WRAPABLE = @as(u32, 512);
pub const TBSTYLE_ALTDRAG = @as(u32, 1024);
pub const TBSTYLE_FLAT = @as(u32, 2048);
pub const TBSTYLE_LIST = @as(u32, 4096);
pub const TBSTYLE_CUSTOMERASE = @as(u32, 8192);
pub const TBSTYLE_REGISTERDROP = @as(u32, 16384);
pub const TBSTYLE_TRANSPARENT = @as(u32, 32768);
pub const TBSTYLE_EX_DRAWDDARROWS = @as(u32, 1);
pub const BTNS_SHOWTEXT = @as(u32, 64);
pub const BTNS_WHOLEDROPDOWN = @as(u32, 128);
pub const TBSTYLE_EX_MIXEDBUTTONS = @as(u32, 8);
pub const TBSTYLE_EX_HIDECLIPPEDBUTTONS = @as(u32, 16);
pub const TBSTYLE_EX_MULTICOLUMN = @as(u32, 2);
pub const TBSTYLE_EX_VERTICAL = @as(u32, 4);
pub const TBSTYLE_EX_DOUBLEBUFFER = @as(u32, 128);
pub const TBCDRF_NOEDGES = @as(u32, 65536);
pub const TBCDRF_HILITEHOTTRACK = @as(u32, 131072);
pub const TBCDRF_NOOFFSET = @as(u32, 262144);
pub const TBCDRF_NOMARK = @as(u32, 524288);
pub const TBCDRF_NOETCHEDEFFECT = @as(u32, 1048576);
pub const TBCDRF_BLENDICON = @as(u32, 2097152);
pub const TBCDRF_NOBACKGROUND = @as(u32, 4194304);
pub const TBCDRF_USECDCOLORS = @as(u32, 8388608);
pub const TB_ENABLEBUTTON = @as(u32, 1025);
pub const TB_CHECKBUTTON = @as(u32, 1026);
pub const TB_PRESSBUTTON = @as(u32, 1027);
pub const TB_HIDEBUTTON = @as(u32, 1028);
pub const TB_INDETERMINATE = @as(u32, 1029);
pub const TB_MARKBUTTON = @as(u32, 1030);
pub const TB_ISBUTTONENABLED = @as(u32, 1033);
pub const TB_ISBUTTONCHECKED = @as(u32, 1034);
pub const TB_ISBUTTONPRESSED = @as(u32, 1035);
pub const TB_ISBUTTONHIDDEN = @as(u32, 1036);
pub const TB_ISBUTTONINDETERMINATE = @as(u32, 1037);
pub const TB_ISBUTTONHIGHLIGHTED = @as(u32, 1038);
pub const TB_SETSTATE = @as(u32, 1041);
pub const TB_GETSTATE = @as(u32, 1042);
pub const TB_ADDBITMAP = @as(u32, 1043);
pub const IDB_STD_SMALL_COLOR = @as(u32, 0);
pub const IDB_STD_LARGE_COLOR = @as(u32, 1);
pub const IDB_VIEW_SMALL_COLOR = @as(u32, 4);
pub const IDB_VIEW_LARGE_COLOR = @as(u32, 5);
pub const IDB_HIST_SMALL_COLOR = @as(u32, 8);
pub const IDB_HIST_LARGE_COLOR = @as(u32, 9);
pub const IDB_HIST_NORMAL = @as(u32, 12);
pub const IDB_HIST_HOT = @as(u32, 13);
pub const IDB_HIST_DISABLED = @as(u32, 14);
pub const IDB_HIST_PRESSED = @as(u32, 15);
pub const STD_CUT = @as(u32, 0);
pub const STD_COPY = @as(u32, 1);
pub const STD_PASTE = @as(u32, 2);
pub const STD_UNDO = @as(u32, 3);
pub const STD_REDOW = @as(u32, 4);
pub const STD_DELETE = @as(u32, 5);
pub const STD_FILENEW = @as(u32, 6);
pub const STD_FILEOPEN = @as(u32, 7);
pub const STD_FILESAVE = @as(u32, 8);
pub const STD_PRINTPRE = @as(u32, 9);
pub const STD_PROPERTIES = @as(u32, 10);
pub const STD_HELP = @as(u32, 11);
pub const STD_FIND = @as(u32, 12);
pub const STD_REPLACE = @as(u32, 13);
pub const STD_PRINT = @as(u32, 14);
pub const VIEW_LARGEICONS = @as(u32, 0);
pub const VIEW_SMALLICONS = @as(u32, 1);
pub const VIEW_LIST = @as(u32, 2);
pub const VIEW_DETAILS = @as(u32, 3);
pub const VIEW_SORTNAME = @as(u32, 4);
pub const VIEW_SORTSIZE = @as(u32, 5);
pub const VIEW_SORTDATE = @as(u32, 6);
pub const VIEW_SORTTYPE = @as(u32, 7);
pub const VIEW_PARENTFOLDER = @as(u32, 8);
pub const VIEW_NETCONNECT = @as(u32, 9);
pub const VIEW_NETDISCONNECT = @as(u32, 10);
pub const VIEW_NEWFOLDER = @as(u32, 11);
pub const VIEW_VIEWMENU = @as(u32, 12);
pub const HIST_BACK = @as(u32, 0);
pub const HIST_FORWARD = @as(u32, 1);
pub const HIST_FAVORITES = @as(u32, 2);
pub const HIST_ADDTOFAVORITES = @as(u32, 3);
pub const HIST_VIEWTREE = @as(u32, 4);
pub const TB_ADDBUTTONSA = @as(u32, 1044);
pub const TB_INSERTBUTTONA = @as(u32, 1045);
pub const TB_DELETEBUTTON = @as(u32, 1046);
pub const TB_GETBUTTON = @as(u32, 1047);
pub const TB_BUTTONCOUNT = @as(u32, 1048);
pub const TB_COMMANDTOINDEX = @as(u32, 1049);
pub const TB_SAVERESTOREA = @as(u32, 1050);
pub const TB_SAVERESTOREW = @as(u32, 1100);
pub const TB_CUSTOMIZE = @as(u32, 1051);
pub const TB_ADDSTRINGA = @as(u32, 1052);
pub const TB_ADDSTRINGW = @as(u32, 1101);
pub const TB_GETITEMRECT = @as(u32, 1053);
pub const TB_BUTTONSTRUCTSIZE = @as(u32, 1054);
pub const TB_SETBUTTONSIZE = @as(u32, 1055);
pub const TB_SETBITMAPSIZE = @as(u32, 1056);
pub const TB_AUTOSIZE = @as(u32, 1057);
pub const TB_GETTOOLTIPS = @as(u32, 1059);
pub const TB_SETTOOLTIPS = @as(u32, 1060);
pub const TB_SETPARENT = @as(u32, 1061);
pub const TB_SETROWS = @as(u32, 1063);
pub const TB_GETROWS = @as(u32, 1064);
pub const TB_SETCMDID = @as(u32, 1066);
pub const TB_CHANGEBITMAP = @as(u32, 1067);
pub const TB_GETBITMAP = @as(u32, 1068);
pub const TB_GETBUTTONTEXTA = @as(u32, 1069);
pub const TB_GETBUTTONTEXTW = @as(u32, 1099);
pub const TB_REPLACEBITMAP = @as(u32, 1070);
pub const TB_SETINDENT = @as(u32, 1071);
pub const TB_SETIMAGELIST = @as(u32, 1072);
pub const TB_GETIMAGELIST = @as(u32, 1073);
pub const TB_LOADIMAGES = @as(u32, 1074);
pub const TB_GETRECT = @as(u32, 1075);
pub const TB_SETHOTIMAGELIST = @as(u32, 1076);
pub const TB_GETHOTIMAGELIST = @as(u32, 1077);
pub const TB_SETDISABLEDIMAGELIST = @as(u32, 1078);
pub const TB_GETDISABLEDIMAGELIST = @as(u32, 1079);
pub const TB_SETSTYLE = @as(u32, 1080);
pub const TB_GETSTYLE = @as(u32, 1081);
pub const TB_GETBUTTONSIZE = @as(u32, 1082);
pub const TB_SETBUTTONWIDTH = @as(u32, 1083);
pub const TB_SETMAXTEXTROWS = @as(u32, 1084);
pub const TB_GETTEXTROWS = @as(u32, 1085);
pub const TB_GETOBJECT = @as(u32, 1086);
pub const TB_GETHOTITEM = @as(u32, 1095);
pub const TB_SETHOTITEM = @as(u32, 1096);
pub const TB_SETANCHORHIGHLIGHT = @as(u32, 1097);
pub const TB_GETANCHORHIGHLIGHT = @as(u32, 1098);
pub const TB_MAPACCELERATORA = @as(u32, 1102);
pub const TB_GETINSERTMARK = @as(u32, 1103);
pub const TB_SETINSERTMARK = @as(u32, 1104);
pub const TB_INSERTMARKHITTEST = @as(u32, 1105);
pub const TB_MOVEBUTTON = @as(u32, 1106);
pub const TB_GETMAXSIZE = @as(u32, 1107);
pub const TB_SETEXTENDEDSTYLE = @as(u32, 1108);
pub const TB_GETEXTENDEDSTYLE = @as(u32, 1109);
pub const TB_GETPADDING = @as(u32, 1110);
pub const TB_SETPADDING = @as(u32, 1111);
pub const TB_SETINSERTMARKCOLOR = @as(u32, 1112);
pub const TB_GETINSERTMARKCOLOR = @as(u32, 1113);
pub const TB_MAPACCELERATORW = @as(u32, 1114);
pub const TBBF_LARGE = @as(u32, 1);
pub const TB_GETBITMAPFLAGS = @as(u32, 1065);
pub const TB_GETBUTTONINFOW = @as(u32, 1087);
pub const TB_SETBUTTONINFOW = @as(u32, 1088);
pub const TB_GETBUTTONINFOA = @as(u32, 1089);
pub const TB_SETBUTTONINFOA = @as(u32, 1090);
pub const TB_INSERTBUTTONW = @as(u32, 1091);
pub const TB_ADDBUTTONSW = @as(u32, 1092);
pub const TB_HITTEST = @as(u32, 1093);
pub const TB_SETDRAWTEXTFLAGS = @as(u32, 1094);
pub const TB_GETSTRINGW = @as(u32, 1115);
pub const TB_GETSTRINGA = @as(u32, 1116);
pub const TB_SETBOUNDINGSIZE = @as(u32, 1117);
pub const TB_SETHOTITEM2 = @as(u32, 1118);
pub const TB_HASACCELERATOR = @as(u32, 1119);
pub const TB_SETLISTGAP = @as(u32, 1120);
pub const TB_GETIMAGELISTCOUNT = @as(u32, 1122);
pub const TB_GETIDEALSIZE = @as(u32, 1123);
pub const TBMF_PAD = @as(u32, 1);
pub const TBMF_BARPAD = @as(u32, 2);
pub const TBMF_BUTTONSPACING = @as(u32, 4);
pub const TB_GETMETRICS = @as(u32, 1125);
pub const TB_SETMETRICS = @as(u32, 1126);
pub const TB_GETITEMDROPDOWNRECT = @as(u32, 1127);
pub const TB_SETPRESSEDIMAGELIST = @as(u32, 1128);
pub const TB_GETPRESSEDIMAGELIST = @as(u32, 1129);
pub const TBNRF_HIDEHELP = @as(u32, 1);
pub const TBNRF_ENDCUSTOMIZE = @as(u32, 2);
pub const TBDDRET_DEFAULT = @as(u32, 0);
pub const TBDDRET_NODEFAULT = @as(u32, 1);
pub const TBDDRET_TREATPRESSED = @as(u32, 2);
pub const RBIM_IMAGELIST = @as(u32, 1);
pub const RBS_TOOLTIPS = @as(u32, 256);
pub const RBS_VARHEIGHT = @as(u32, 512);
pub const RBS_BANDBORDERS = @as(u32, 1024);
pub const RBS_FIXEDORDER = @as(u32, 2048);
pub const RBS_REGISTERDROP = @as(u32, 4096);
pub const RBS_AUTOSIZE = @as(u32, 8192);
pub const RBS_VERTICALGRIPPER = @as(u32, 16384);
pub const RBS_DBLCLKTOGGLE = @as(u32, 32768);
pub const RBBS_BREAK = @as(u32, 1);
pub const RBBS_FIXEDSIZE = @as(u32, 2);
pub const RBBS_CHILDEDGE = @as(u32, 4);
pub const RBBS_HIDDEN = @as(u32, 8);
pub const RBBS_NOVERT = @as(u32, 16);
pub const RBBS_FIXEDBMP = @as(u32, 32);
pub const RBBS_VARIABLEHEIGHT = @as(u32, 64);
pub const RBBS_GRIPPERALWAYS = @as(u32, 128);
pub const RBBS_NOGRIPPER = @as(u32, 256);
pub const RBBS_USECHEVRON = @as(u32, 512);
pub const RBBS_HIDETITLE = @as(u32, 1024);
pub const RBBS_TOPALIGN = @as(u32, 2048);
pub const RBBIM_STYLE = @as(u32, 1);
pub const RBBIM_COLORS = @as(u32, 2);
pub const RBBIM_TEXT = @as(u32, 4);
pub const RBBIM_IMAGE = @as(u32, 8);
pub const RBBIM_CHILD = @as(u32, 16);
pub const RBBIM_CHILDSIZE = @as(u32, 32);
pub const RBBIM_SIZE = @as(u32, 64);
pub const RBBIM_BACKGROUND = @as(u32, 128);
pub const RBBIM_ID = @as(u32, 256);
pub const RBBIM_IDEALSIZE = @as(u32, 512);
pub const RBBIM_LPARAM = @as(u32, 1024);
pub const RBBIM_HEADERSIZE = @as(u32, 2048);
pub const RBBIM_CHEVRONLOCATION = @as(u32, 4096);
pub const RBBIM_CHEVRONSTATE = @as(u32, 8192);
pub const RB_INSERTBANDA = @as(u32, 1025);
pub const RB_DELETEBAND = @as(u32, 1026);
pub const RB_GETBARINFO = @as(u32, 1027);
pub const RB_SETBARINFO = @as(u32, 1028);
pub const RB_SETBANDINFOA = @as(u32, 1030);
pub const RB_SETPARENT = @as(u32, 1031);
pub const RB_HITTEST = @as(u32, 1032);
pub const RB_GETRECT = @as(u32, 1033);
pub const RB_INSERTBANDW = @as(u32, 1034);
pub const RB_SETBANDINFOW = @as(u32, 1035);
pub const RB_GETBANDCOUNT = @as(u32, 1036);
pub const RB_GETROWCOUNT = @as(u32, 1037);
pub const RB_GETROWHEIGHT = @as(u32, 1038);
pub const RB_IDTOINDEX = @as(u32, 1040);
pub const RB_GETTOOLTIPS = @as(u32, 1041);
pub const RB_SETTOOLTIPS = @as(u32, 1042);
pub const RB_SETBKCOLOR = @as(u32, 1043);
pub const RB_GETBKCOLOR = @as(u32, 1044);
pub const RB_SETTEXTCOLOR = @as(u32, 1045);
pub const RB_GETTEXTCOLOR = @as(u32, 1046);
pub const RBSTR_CHANGERECT = @as(u32, 1);
pub const RB_SIZETORECT = @as(u32, 1047);
pub const RB_BEGINDRAG = @as(u32, 1048);
pub const RB_ENDDRAG = @as(u32, 1049);
pub const RB_DRAGMOVE = @as(u32, 1050);
pub const RB_GETBARHEIGHT = @as(u32, 1051);
pub const RB_GETBANDINFOW = @as(u32, 1052);
pub const RB_GETBANDINFOA = @as(u32, 1053);
pub const RB_MINIMIZEBAND = @as(u32, 1054);
pub const RB_MAXIMIZEBAND = @as(u32, 1055);
pub const RB_GETBANDBORDERS = @as(u32, 1058);
pub const RB_SHOWBAND = @as(u32, 1059);
pub const RB_SETPALETTE = @as(u32, 1061);
pub const RB_GETPALETTE = @as(u32, 1062);
pub const RB_MOVEBAND = @as(u32, 1063);
pub const RB_GETBANDMARGINS = @as(u32, 1064);
pub const RB_SETEXTENDEDSTYLE = @as(u32, 1065);
pub const RB_GETEXTENDEDSTYLE = @as(u32, 1066);
pub const RB_PUSHCHEVRON = @as(u32, 1067);
pub const RB_SETBANDWIDTH = @as(u32, 1068);
pub const RBAB_AUTOSIZE = @as(u32, 1);
pub const RBAB_ADDBAND = @as(u32, 2);
pub const RBHT_NOWHERE = @as(u32, 1);
pub const RBHT_CAPTION = @as(u32, 2);
pub const RBHT_CLIENT = @as(u32, 3);
pub const RBHT_GRABBER = @as(u32, 4);
pub const RBHT_CHEVRON = @as(u32, 8);
pub const RBHT_SPLITTER = @as(u32, 16);
pub const TTS_ALWAYSTIP = @as(u32, 1);
pub const TTS_NOPREFIX = @as(u32, 2);
pub const TTS_NOANIMATE = @as(u32, 16);
pub const TTS_NOFADE = @as(u32, 32);
pub const TTS_BALLOON = @as(u32, 64);
pub const TTS_CLOSE = @as(u32, 128);
pub const TTS_USEVISUALSTYLE = @as(u32, 256);
pub const TTF_DI_SETITEM = @as(u32, 32768);
pub const TTDT_AUTOMATIC = @as(u32, 0);
pub const TTDT_RESHOW = @as(u32, 1);
pub const TTDT_AUTOPOP = @as(u32, 2);
pub const TTDT_INITIAL = @as(u32, 3);
pub const TTM_ACTIVATE = @as(u32, 1025);
pub const TTM_SETDELAYTIME = @as(u32, 1027);
pub const TTM_ADDTOOLA = @as(u32, 1028);
pub const TTM_ADDTOOLW = @as(u32, 1074);
pub const TTM_DELTOOLA = @as(u32, 1029);
pub const TTM_DELTOOLW = @as(u32, 1075);
pub const TTM_NEWTOOLRECTA = @as(u32, 1030);
pub const TTM_NEWTOOLRECTW = @as(u32, 1076);
pub const TTM_RELAYEVENT = @as(u32, 1031);
pub const TTM_GETTOOLINFOA = @as(u32, 1032);
pub const TTM_GETTOOLINFOW = @as(u32, 1077);
pub const TTM_SETTOOLINFOA = @as(u32, 1033);
pub const TTM_SETTOOLINFOW = @as(u32, 1078);
pub const TTM_HITTESTA = @as(u32, 1034);
pub const TTM_HITTESTW = @as(u32, 1079);
pub const TTM_GETTEXTA = @as(u32, 1035);
pub const TTM_GETTEXTW = @as(u32, 1080);
pub const TTM_UPDATETIPTEXTA = @as(u32, 1036);
pub const TTM_UPDATETIPTEXTW = @as(u32, 1081);
pub const TTM_GETTOOLCOUNT = @as(u32, 1037);
pub const TTM_ENUMTOOLSA = @as(u32, 1038);
pub const TTM_ENUMTOOLSW = @as(u32, 1082);
pub const TTM_GETCURRENTTOOLA = @as(u32, 1039);
pub const TTM_GETCURRENTTOOLW = @as(u32, 1083);
pub const TTM_WINDOWFROMPOINT = @as(u32, 1040);
pub const TTM_TRACKACTIVATE = @as(u32, 1041);
pub const TTM_TRACKPOSITION = @as(u32, 1042);
pub const TTM_SETTIPBKCOLOR = @as(u32, 1043);
pub const TTM_SETTIPTEXTCOLOR = @as(u32, 1044);
pub const TTM_GETDELAYTIME = @as(u32, 1045);
pub const TTM_GETTIPBKCOLOR = @as(u32, 1046);
pub const TTM_GETTIPTEXTCOLOR = @as(u32, 1047);
pub const TTM_SETMAXTIPWIDTH = @as(u32, 1048);
pub const TTM_GETMAXTIPWIDTH = @as(u32, 1049);
pub const TTM_SETMARGIN = @as(u32, 1050);
pub const TTM_GETMARGIN = @as(u32, 1051);
pub const TTM_POP = @as(u32, 1052);
pub const TTM_UPDATE = @as(u32, 1053);
pub const TTM_GETBUBBLESIZE = @as(u32, 1054);
pub const TTM_ADJUSTRECT = @as(u32, 1055);
pub const TTM_SETTITLEA = @as(u32, 1056);
pub const TTM_SETTITLEW = @as(u32, 1057);
pub const TTM_POPUP = @as(u32, 1058);
pub const TTM_GETTITLE = @as(u32, 1059);
pub const SBARS_SIZEGRIP = @as(u32, 256);
pub const SBARS_TOOLTIPS = @as(u32, 2048);
pub const SBT_TOOLTIPS = @as(u32, 2048);
pub const SB_SETTEXTA = @as(u32, 1025);
pub const SB_SETTEXTW = @as(u32, 1035);
pub const SB_GETTEXTA = @as(u32, 1026);
pub const SB_GETTEXTW = @as(u32, 1037);
pub const SB_GETTEXTLENGTHA = @as(u32, 1027);
pub const SB_GETTEXTLENGTHW = @as(u32, 1036);
pub const SB_SETPARTS = @as(u32, 1028);
pub const SB_GETPARTS = @as(u32, 1030);
pub const SB_GETBORDERS = @as(u32, 1031);
pub const SB_SETMINHEIGHT = @as(u32, 1032);
pub const SB_SIMPLE = @as(u32, 1033);
pub const SB_GETRECT = @as(u32, 1034);
pub const SB_ISSIMPLE = @as(u32, 1038);
pub const SB_SETICON = @as(u32, 1039);
pub const SB_SETTIPTEXTA = @as(u32, 1040);
pub const SB_SETTIPTEXTW = @as(u32, 1041);
pub const SB_GETTIPTEXTA = @as(u32, 1042);
pub const SB_GETTIPTEXTW = @as(u32, 1043);
pub const SB_GETICON = @as(u32, 1044);
pub const SBT_OWNERDRAW = @as(u32, 4096);
pub const SBT_NOBORDERS = @as(u32, 256);
pub const SBT_POPOUT = @as(u32, 512);
pub const SBT_RTLREADING = @as(u32, 1024);
pub const SBT_NOTABPARSING = @as(u32, 2048);
pub const SB_SIMPLEID = @as(u32, 255);
pub const TBS_AUTOTICKS = @as(u32, 1);
pub const TBS_VERT = @as(u32, 2);
pub const TBS_HORZ = @as(u32, 0);
pub const TBS_TOP = @as(u32, 4);
pub const TBS_BOTTOM = @as(u32, 0);
pub const TBS_LEFT = @as(u32, 4);
pub const TBS_RIGHT = @as(u32, 0);
pub const TBS_BOTH = @as(u32, 8);
pub const TBS_NOTICKS = @as(u32, 16);
pub const TBS_ENABLESELRANGE = @as(u32, 32);
pub const TBS_FIXEDLENGTH = @as(u32, 64);
pub const TBS_NOTHUMB = @as(u32, 128);
pub const TBS_TOOLTIPS = @as(u32, 256);
pub const TBS_REVERSED = @as(u32, 512);
pub const TBS_DOWNISLEFT = @as(u32, 1024);
pub const TBS_NOTIFYBEFOREMOVE = @as(u32, 2048);
pub const TBS_TRANSPARENTBKGND = @as(u32, 4096);
pub const TBM_GETRANGEMIN = @as(u32, 1025);
pub const TBM_GETRANGEMAX = @as(u32, 1026);
pub const TBM_GETTIC = @as(u32, 1027);
pub const TBM_SETTIC = @as(u32, 1028);
pub const TBM_SETPOS = @as(u32, 1029);
pub const TBM_SETRANGE = @as(u32, 1030);
pub const TBM_SETRANGEMIN = @as(u32, 1031);
pub const TBM_SETRANGEMAX = @as(u32, 1032);
pub const TBM_CLEARTICS = @as(u32, 1033);
pub const TBM_SETSEL = @as(u32, 1034);
pub const TBM_SETSELSTART = @as(u32, 1035);
pub const TBM_SETSELEND = @as(u32, 1036);
pub const TBM_GETPTICS = @as(u32, 1038);
pub const TBM_GETTICPOS = @as(u32, 1039);
pub const TBM_GETNUMTICS = @as(u32, 1040);
pub const TBM_GETSELSTART = @as(u32, 1041);
pub const TBM_GETSELEND = @as(u32, 1042);
pub const TBM_CLEARSEL = @as(u32, 1043);
pub const TBM_SETTICFREQ = @as(u32, 1044);
pub const TBM_SETPAGESIZE = @as(u32, 1045);
pub const TBM_GETPAGESIZE = @as(u32, 1046);
pub const TBM_SETLINESIZE = @as(u32, 1047);
pub const TBM_GETLINESIZE = @as(u32, 1048);
pub const TBM_GETTHUMBRECT = @as(u32, 1049);
pub const TBM_GETCHANNELRECT = @as(u32, 1050);
pub const TBM_SETTHUMBLENGTH = @as(u32, 1051);
pub const TBM_GETTHUMBLENGTH = @as(u32, 1052);
pub const TBM_SETTOOLTIPS = @as(u32, 1053);
pub const TBM_GETTOOLTIPS = @as(u32, 1054);
pub const TBM_SETTIPSIDE = @as(u32, 1055);
pub const TBTS_TOP = @as(u32, 0);
pub const TBTS_LEFT = @as(u32, 1);
pub const TBTS_BOTTOM = @as(u32, 2);
pub const TBTS_RIGHT = @as(u32, 3);
pub const TBM_SETBUDDY = @as(u32, 1056);
pub const TBM_GETBUDDY = @as(u32, 1057);
pub const TBM_SETPOSNOTIFY = @as(u32, 1058);
pub const TB_LINEUP = @as(u32, 0);
pub const TB_LINEDOWN = @as(u32, 1);
pub const TB_PAGEUP = @as(u32, 2);
pub const TB_PAGEDOWN = @as(u32, 3);
pub const TB_THUMBPOSITION = @as(u32, 4);
pub const TB_THUMBTRACK = @as(u32, 5);
pub const TB_TOP = @as(u32, 6);
pub const TB_BOTTOM = @as(u32, 7);
pub const TB_ENDTRACK = @as(u32, 8);
pub const TBCD_TICS = @as(u32, 1);
pub const TBCD_THUMB = @as(u32, 2);
pub const TBCD_CHANNEL = @as(u32, 3);
pub const DL_CURSORSET = @as(u32, 0);
pub const DL_STOPCURSOR = @as(u32, 1);
pub const DL_COPYCURSOR = @as(u32, 2);
pub const DL_MOVECURSOR = @as(u32, 3);
pub const UD_MAXVAL = @as(u32, 32767);
pub const UDS_WRAP = @as(u32, 1);
pub const UDS_SETBUDDYINT = @as(u32, 2);
pub const UDS_ALIGNRIGHT = @as(u32, 4);
pub const UDS_ALIGNLEFT = @as(u32, 8);
pub const UDS_AUTOBUDDY = @as(u32, 16);
pub const UDS_ARROWKEYS = @as(u32, 32);
pub const UDS_HORZ = @as(u32, 64);
pub const UDS_NOTHOUSANDS = @as(u32, 128);
pub const UDS_HOTTRACK = @as(u32, 256);
pub const UDM_SETRANGE = @as(u32, 1125);
pub const UDM_GETRANGE = @as(u32, 1126);
pub const UDM_SETPOS = @as(u32, 1127);
pub const UDM_GETPOS = @as(u32, 1128);
pub const UDM_SETBUDDY = @as(u32, 1129);
pub const UDM_GETBUDDY = @as(u32, 1130);
pub const UDM_SETACCEL = @as(u32, 1131);
pub const UDM_GETACCEL = @as(u32, 1132);
pub const UDM_SETBASE = @as(u32, 1133);
pub const UDM_GETBASE = @as(u32, 1134);
pub const UDM_SETRANGE32 = @as(u32, 1135);
pub const UDM_GETRANGE32 = @as(u32, 1136);
pub const UDM_SETPOS32 = @as(u32, 1137);
pub const UDM_GETPOS32 = @as(u32, 1138);
pub const PBS_SMOOTH = @as(u32, 1);
pub const PBS_VERTICAL = @as(u32, 4);
pub const PBM_SETRANGE = @as(u32, 1025);
pub const PBM_SETPOS = @as(u32, 1026);
pub const PBM_DELTAPOS = @as(u32, 1027);
pub const PBM_SETSTEP = @as(u32, 1028);
pub const PBM_STEPIT = @as(u32, 1029);
pub const PBM_SETRANGE32 = @as(u32, 1030);
pub const PBM_GETRANGE = @as(u32, 1031);
pub const PBM_GETPOS = @as(u32, 1032);
pub const PBM_SETBARCOLOR = @as(u32, 1033);
pub const PBS_MARQUEE = @as(u32, 8);
pub const PBM_SETMARQUEE = @as(u32, 1034);
pub const PBS_SMOOTHREVERSE = @as(u32, 16);
pub const PBM_GETSTEP = @as(u32, 1037);
pub const PBM_GETBKCOLOR = @as(u32, 1038);
pub const PBM_GETBARCOLOR = @as(u32, 1039);
pub const PBM_SETSTATE = @as(u32, 1040);
pub const PBM_GETSTATE = @as(u32, 1041);
pub const PBST_NORMAL = @as(u32, 1);
pub const PBST_ERROR = @as(u32, 2);
pub const PBST_PAUSED = @as(u32, 3);
pub const HOTKEYF_SHIFT = @as(u32, 1);
pub const HOTKEYF_CONTROL = @as(u32, 2);
pub const HOTKEYF_ALT = @as(u32, 4);
pub const HOTKEYF_EXT = @as(u32, 128);
pub const HKCOMB_NONE = @as(u32, 1);
pub const HKCOMB_S = @as(u32, 2);
pub const HKCOMB_C = @as(u32, 4);
pub const HKCOMB_A = @as(u32, 8);
pub const HKCOMB_SC = @as(u32, 16);
pub const HKCOMB_SA = @as(u32, 32);
pub const HKCOMB_CA = @as(u32, 64);
pub const HKCOMB_SCA = @as(u32, 128);
pub const HKM_SETHOTKEY = @as(u32, 1025);
pub const HKM_GETHOTKEY = @as(u32, 1026);
pub const HKM_SETRULES = @as(u32, 1027);
pub const CCS_TOP = @as(i32, 1);
pub const CCS_NOMOVEY = @as(i32, 2);
pub const CCS_BOTTOM = @as(i32, 3);
pub const CCS_NORESIZE = @as(i32, 4);
pub const CCS_NOPARENTALIGN = @as(i32, 8);
pub const CCS_ADJUSTABLE = @as(i32, 32);
pub const CCS_NODIVIDER = @as(i32, 64);
pub const CCS_VERT = @as(i32, 128);
pub const INVALID_LINK_INDEX = @as(i32, -1);
pub const MAX_LINKID_TEXT = @as(u32, 48);
pub const LWS_TRANSPARENT = @as(u32, 1);
pub const LWS_IGNORERETURN = @as(u32, 2);
pub const LWS_NOPREFIX = @as(u32, 4);
pub const LWS_USEVISUALSTYLE = @as(u32, 8);
pub const LWS_USECUSTOMTEXT = @as(u32, 16);
pub const LWS_RIGHT = @as(u32, 32);
pub const LIF_ITEMINDEX = @as(u32, 1);
pub const LIF_STATE = @as(u32, 2);
pub const LIF_ITEMID = @as(u32, 4);
pub const LIF_URL = @as(u32, 8);
pub const LIS_FOCUSED = @as(u32, 1);
pub const LIS_ENABLED = @as(u32, 2);
pub const LIS_VISITED = @as(u32, 4);
pub const LIS_HOTTRACK = @as(u32, 8);
pub const LIS_DEFAULTCOLORS = @as(u32, 16);
pub const LM_HITTEST = @as(u32, 1792);
pub const LM_GETIDEALHEIGHT = @as(u32, 1793);
pub const LM_SETITEM = @as(u32, 1794);
pub const LM_GETITEM = @as(u32, 1795);
pub const LVS_ICON = @as(u32, 0);
pub const LVS_REPORT = @as(u32, 1);
pub const LVS_SMALLICON = @as(u32, 2);
pub const LVS_LIST = @as(u32, 3);
pub const LVS_TYPEMASK = @as(u32, 3);
pub const LVS_SINGLESEL = @as(u32, 4);
pub const LVS_SHOWSELALWAYS = @as(u32, 8);
pub const LVS_SORTASCENDING = @as(u32, 16);
pub const LVS_SORTDESCENDING = @as(u32, 32);
pub const LVS_SHAREIMAGELISTS = @as(u32, 64);
pub const LVS_NOLABELWRAP = @as(u32, 128);
pub const LVS_AUTOARRANGE = @as(u32, 256);
pub const LVS_EDITLABELS = @as(u32, 512);
pub const LVS_OWNERDATA = @as(u32, 4096);
pub const LVS_NOSCROLL = @as(u32, 8192);
pub const LVS_TYPESTYLEMASK = @as(u32, 64512);
pub const LVS_ALIGNTOP = @as(u32, 0);
pub const LVS_ALIGNLEFT = @as(u32, 2048);
pub const LVS_ALIGNMASK = @as(u32, 3072);
pub const LVS_OWNERDRAWFIXED = @as(u32, 1024);
pub const LVS_NOCOLUMNHEADER = @as(u32, 16384);
pub const LVS_NOSORTHEADER = @as(u32, 32768);
pub const LVM_GETBKCOLOR = @as(u32, 4096);
pub const LVM_SETBKCOLOR = @as(u32, 4097);
pub const LVM_GETIMAGELIST = @as(u32, 4098);
pub const LVSIL_NORMAL = @as(u32, 0);
pub const LVSIL_SMALL = @as(u32, 1);
pub const LVSIL_STATE = @as(u32, 2);
pub const LVSIL_GROUPHEADER = @as(u32, 3);
pub const LVM_SETIMAGELIST = @as(u32, 4099);
pub const LVM_GETITEMCOUNT = @as(u32, 4100);
pub const LVIF_TEXT = @as(u32, 1);
pub const LVIF_IMAGE = @as(u32, 2);
pub const LVIF_PARAM = @as(u32, 4);
pub const LVIF_STATE = @as(u32, 8);
pub const LVIF_INDENT = @as(u32, 16);
pub const LVIF_NORECOMPUTE = @as(u32, 2048);
pub const LVIF_GROUPID = @as(u32, 256);
pub const LVIF_COLUMNS = @as(u32, 512);
pub const LVIF_COLFMT = @as(u32, 65536);
pub const LVIS_FOCUSED = @as(u32, 1);
pub const LVIS_SELECTED = @as(u32, 2);
pub const LVIS_CUT = @as(u32, 4);
pub const LVIS_DROPHILITED = @as(u32, 8);
pub const LVIS_GLOW = @as(u32, 16);
pub const LVIS_ACTIVATING = @as(u32, 32);
pub const LVIS_OVERLAYMASK = @as(u32, 3840);
pub const LVIS_STATEIMAGEMASK = @as(u32, 61440);
pub const I_INDENTCALLBACK = @as(i32, -1);
pub const I_IMAGECALLBACK = @as(i32, -1);
pub const I_IMAGENONE = @as(i32, -2);
pub const LVM_GETITEMA = @as(u32, 4101);
pub const LVM_GETITEMW = @as(u32, 4171);
pub const LVM_SETITEMA = @as(u32, 4102);
pub const LVM_SETITEMW = @as(u32, 4172);
pub const LVM_INSERTITEMA = @as(u32, 4103);
pub const LVM_INSERTITEMW = @as(u32, 4173);
pub const LVM_DELETEITEM = @as(u32, 4104);
pub const LVM_DELETEALLITEMS = @as(u32, 4105);
pub const LVM_GETCALLBACKMASK = @as(u32, 4106);
pub const LVM_SETCALLBACKMASK = @as(u32, 4107);
pub const LVNI_ALL = @as(u32, 0);
pub const LVNI_FOCUSED = @as(u32, 1);
pub const LVNI_SELECTED = @as(u32, 2);
pub const LVNI_CUT = @as(u32, 4);
pub const LVNI_DROPHILITED = @as(u32, 8);
pub const LVNI_VISIBLEORDER = @as(u32, 16);
pub const LVNI_PREVIOUS = @as(u32, 32);
pub const LVNI_VISIBLEONLY = @as(u32, 64);
pub const LVNI_SAMEGROUPONLY = @as(u32, 128);
pub const LVNI_ABOVE = @as(u32, 256);
pub const LVNI_BELOW = @as(u32, 512);
pub const LVNI_TOLEFT = @as(u32, 1024);
pub const LVNI_TORIGHT = @as(u32, 2048);
pub const LVM_GETNEXTITEM = @as(u32, 4108);
pub const LVM_FINDITEMA = @as(u32, 4109);
pub const LVM_FINDITEMW = @as(u32, 4179);
pub const LVIR_BOUNDS = @as(u32, 0);
pub const LVIR_ICON = @as(u32, 1);
pub const LVIR_LABEL = @as(u32, 2);
pub const LVIR_SELECTBOUNDS = @as(u32, 3);
pub const LVM_GETITEMRECT = @as(u32, 4110);
pub const LVM_SETITEMPOSITION = @as(u32, 4111);
pub const LVM_GETITEMPOSITION = @as(u32, 4112);
pub const LVM_GETSTRINGWIDTHA = @as(u32, 4113);
pub const LVM_GETSTRINGWIDTHW = @as(u32, 4183);
pub const LVM_HITTEST = @as(u32, 4114);
pub const LVM_ENSUREVISIBLE = @as(u32, 4115);
pub const LVM_SCROLL = @as(u32, 4116);
pub const LVM_REDRAWITEMS = @as(u32, 4117);
pub const LVA_DEFAULT = @as(u32, 0);
pub const LVA_ALIGNLEFT = @as(u32, 1);
pub const LVA_ALIGNTOP = @as(u32, 2);
pub const LVA_SNAPTOGRID = @as(u32, 5);
pub const LVM_ARRANGE = @as(u32, 4118);
pub const LVM_EDITLABELA = @as(u32, 4119);
pub const LVM_EDITLABELW = @as(u32, 4214);
pub const LVM_GETEDITCONTROL = @as(u32, 4120);
pub const LVCFMT_LINE_BREAK = @as(u32, 1048576);
pub const LVCFMT_FILL = @as(u32, 2097152);
pub const LVCFMT_WRAP = @as(u32, 4194304);
pub const LVCFMT_NO_TITLE = @as(u32, 8388608);
pub const LVM_GETCOLUMNA = @as(u32, 4121);
pub const LVM_GETCOLUMNW = @as(u32, 4191);
pub const LVM_SETCOLUMNA = @as(u32, 4122);
pub const LVM_SETCOLUMNW = @as(u32, 4192);
pub const LVM_INSERTCOLUMNA = @as(u32, 4123);
pub const LVM_INSERTCOLUMNW = @as(u32, 4193);
pub const LVM_DELETECOLUMN = @as(u32, 4124);
pub const LVM_GETCOLUMNWIDTH = @as(u32, 4125);
pub const LVSCW_AUTOSIZE = @as(i32, -1);
pub const LVSCW_AUTOSIZE_USEHEADER = @as(i32, -2);
pub const LVM_SETCOLUMNWIDTH = @as(u32, 4126);
pub const LVM_GETHEADER = @as(u32, 4127);
pub const LVM_CREATEDRAGIMAGE = @as(u32, 4129);
pub const LVM_GETVIEWRECT = @as(u32, 4130);
pub const LVM_GETTEXTCOLOR = @as(u32, 4131);
pub const LVM_SETTEXTCOLOR = @as(u32, 4132);
pub const LVM_GETTEXTBKCOLOR = @as(u32, 4133);
pub const LVM_SETTEXTBKCOLOR = @as(u32, 4134);
pub const LVM_GETTOPINDEX = @as(u32, 4135);
pub const LVM_GETCOUNTPERPAGE = @as(u32, 4136);
pub const LVM_GETORIGIN = @as(u32, 4137);
pub const LVM_UPDATE = @as(u32, 4138);
pub const LVM_SETITEMSTATE = @as(u32, 4139);
pub const LVM_GETITEMSTATE = @as(u32, 4140);
pub const LVM_GETITEMTEXTA = @as(u32, 4141);
pub const LVM_GETITEMTEXTW = @as(u32, 4211);
pub const LVM_SETITEMTEXTA = @as(u32, 4142);
pub const LVM_SETITEMTEXTW = @as(u32, 4212);
pub const LVSICF_NOINVALIDATEALL = @as(u32, 1);
pub const LVSICF_NOSCROLL = @as(u32, 2);
pub const LVM_SETITEMCOUNT = @as(u32, 4143);
pub const LVM_SORTITEMS = @as(u32, 4144);
pub const LVM_SETITEMPOSITION32 = @as(u32, 4145);
pub const LVM_GETSELECTEDCOUNT = @as(u32, 4146);
pub const LVM_GETITEMSPACING = @as(u32, 4147);
pub const LVM_GETISEARCHSTRINGA = @as(u32, 4148);
pub const LVM_GETISEARCHSTRINGW = @as(u32, 4213);
pub const LVM_SETICONSPACING = @as(u32, 4149);
pub const LVM_SETEXTENDEDLISTVIEWSTYLE = @as(u32, 4150);
pub const LVM_GETEXTENDEDLISTVIEWSTYLE = @as(u32, 4151);
pub const LVS_EX_GRIDLINES = @as(u32, 1);
pub const LVS_EX_SUBITEMIMAGES = @as(u32, 2);
pub const LVS_EX_CHECKBOXES = @as(u32, 4);
pub const LVS_EX_TRACKSELECT = @as(u32, 8);
pub const LVS_EX_HEADERDRAGDROP = @as(u32, 16);
pub const LVS_EX_FULLROWSELECT = @as(u32, 32);
pub const LVS_EX_ONECLICKACTIVATE = @as(u32, 64);
pub const LVS_EX_TWOCLICKACTIVATE = @as(u32, 128);
pub const LVS_EX_FLATSB = @as(u32, 256);
pub const LVS_EX_REGIONAL = @as(u32, 512);
pub const LVS_EX_INFOTIP = @as(u32, 1024);
pub const LVS_EX_UNDERLINEHOT = @as(u32, 2048);
pub const LVS_EX_UNDERLINECOLD = @as(u32, 4096);
pub const LVS_EX_MULTIWORKAREAS = @as(u32, 8192);
pub const LVS_EX_LABELTIP = @as(u32, 16384);
pub const LVS_EX_BORDERSELECT = @as(u32, 32768);
pub const LVS_EX_DOUBLEBUFFER = @as(u32, 65536);
pub const LVS_EX_HIDELABELS = @as(u32, 131072);
pub const LVS_EX_SINGLEROW = @as(u32, 262144);
pub const LVS_EX_SNAPTOGRID = @as(u32, 524288);
pub const LVS_EX_SIMPLESELECT = @as(u32, 1048576);
pub const LVS_EX_JUSTIFYCOLUMNS = @as(u32, 2097152);
pub const LVS_EX_TRANSPARENTBKGND = @as(u32, 4194304);
pub const LVS_EX_TRANSPARENTSHADOWTEXT = @as(u32, 8388608);
pub const LVS_EX_AUTOAUTOARRANGE = @as(u32, 16777216);
pub const LVS_EX_HEADERINALLVIEWS = @as(u32, 33554432);
pub const LVS_EX_AUTOCHECKSELECT = @as(u32, 134217728);
pub const LVS_EX_AUTOSIZECOLUMNS = @as(u32, 268435456);
pub const LVS_EX_COLUMNSNAPPOINTS = @as(u32, 1073741824);
pub const LVS_EX_COLUMNOVERFLOW = @as(u32, 2147483648);
pub const LVM_GETSUBITEMRECT = @as(u32, 4152);
pub const LVM_SUBITEMHITTEST = @as(u32, 4153);
pub const LVM_SETCOLUMNORDERARRAY = @as(u32, 4154);
pub const LVM_GETCOLUMNORDERARRAY = @as(u32, 4155);
pub const LVM_SETHOTITEM = @as(u32, 4156);
pub const LVM_GETHOTITEM = @as(u32, 4157);
pub const LVM_SETHOTCURSOR = @as(u32, 4158);
pub const LVM_GETHOTCURSOR = @as(u32, 4159);
pub const LVM_APPROXIMATEVIEWRECT = @as(u32, 4160);
pub const LV_MAX_WORKAREAS = @as(u32, 16);
pub const LVM_SETWORKAREAS = @as(u32, 4161);
pub const LVM_GETWORKAREAS = @as(u32, 4166);
pub const LVM_GETNUMBEROFWORKAREAS = @as(u32, 4169);
pub const LVM_GETSELECTIONMARK = @as(u32, 4162);
pub const LVM_SETSELECTIONMARK = @as(u32, 4163);
pub const LVM_SETHOVERTIME = @as(u32, 4167);
pub const LVM_GETHOVERTIME = @as(u32, 4168);
pub const LVM_SETTOOLTIPS = @as(u32, 4170);
pub const LVM_GETTOOLTIPS = @as(u32, 4174);
pub const LVM_SORTITEMSEX = @as(u32, 4177);
pub const LVBKIF_SOURCE_NONE = @as(u32, 0);
pub const LVBKIF_SOURCE_HBITMAP = @as(u32, 1);
pub const LVBKIF_SOURCE_URL = @as(u32, 2);
pub const LVBKIF_SOURCE_MASK = @as(u32, 3);
pub const LVBKIF_STYLE_NORMAL = @as(u32, 0);
pub const LVBKIF_STYLE_TILE = @as(u32, 16);
pub const LVBKIF_STYLE_MASK = @as(u32, 16);
pub const LVBKIF_FLAG_TILEOFFSET = @as(u32, 256);
pub const LVBKIF_TYPE_WATERMARK = @as(u32, 268435456);
pub const LVBKIF_FLAG_ALPHABLEND = @as(u32, 536870912);
pub const LVM_SETBKIMAGEA = @as(u32, 4164);
pub const LVM_SETBKIMAGEW = @as(u32, 4234);
pub const LVM_GETBKIMAGEA = @as(u32, 4165);
pub const LVM_GETBKIMAGEW = @as(u32, 4235);
pub const LVM_SETSELECTEDCOLUMN = @as(u32, 4236);
pub const LV_VIEW_ICON = @as(u32, 0);
pub const LV_VIEW_DETAILS = @as(u32, 1);
pub const LV_VIEW_SMALLICON = @as(u32, 2);
pub const LV_VIEW_LIST = @as(u32, 3);
pub const LV_VIEW_TILE = @as(u32, 4);
pub const LV_VIEW_MAX = @as(u32, 4);
pub const LVM_SETVIEW = @as(u32, 4238);
pub const LVM_GETVIEW = @as(u32, 4239);
pub const LVGF_ALIGN = @as(u32, 8);
pub const LVGF_GROUPID = @as(u32, 16);
pub const LVGF_SUBTITLE = @as(u32, 256);
pub const LVGF_TASK = @as(u32, 512);
pub const LVGF_DESCRIPTIONTOP = @as(u32, 1024);
pub const LVGF_DESCRIPTIONBOTTOM = @as(u32, 2048);
pub const LVGF_TITLEIMAGE = @as(u32, 4096);
pub const LVGF_EXTENDEDIMAGE = @as(u32, 8192);
pub const LVGF_ITEMS = @as(u32, 16384);
pub const LVGF_SUBSET = @as(u32, 32768);
pub const LVGF_SUBSETITEMS = @as(u32, 65536);
pub const LVGS_NORMAL = @as(u32, 0);
pub const LVGS_COLLAPSED = @as(u32, 1);
pub const LVGS_HIDDEN = @as(u32, 2);
pub const LVGS_NOHEADER = @as(u32, 4);
pub const LVGS_COLLAPSIBLE = @as(u32, 8);
pub const LVGS_FOCUSED = @as(u32, 16);
pub const LVGS_SELECTED = @as(u32, 32);
pub const LVGS_SUBSETED = @as(u32, 64);
pub const LVGS_SUBSETLINKFOCUSED = @as(u32, 128);
pub const LVGA_FOOTER_LEFT = @as(u32, 8);
pub const LVGA_FOOTER_CENTER = @as(u32, 16);
pub const LVGA_FOOTER_RIGHT = @as(u32, 32);
pub const LVM_INSERTGROUP = @as(u32, 4241);
pub const LVM_SETGROUPINFO = @as(u32, 4243);
pub const LVM_GETGROUPINFO = @as(u32, 4245);
pub const LVM_REMOVEGROUP = @as(u32, 4246);
pub const LVM_MOVEGROUP = @as(u32, 4247);
pub const LVM_GETGROUPCOUNT = @as(u32, 4248);
pub const LVM_GETGROUPINFOBYINDEX = @as(u32, 4249);
pub const LVM_MOVEITEMTOGROUP = @as(u32, 4250);
pub const LVGGR_GROUP = @as(u32, 0);
pub const LVGGR_HEADER = @as(u32, 1);
pub const LVGGR_LABEL = @as(u32, 2);
pub const LVGGR_SUBSETLINK = @as(u32, 3);
pub const LVM_GETGROUPRECT = @as(u32, 4194);
pub const LVGMF_NONE = @as(u32, 0);
pub const LVGMF_BORDERSIZE = @as(u32, 1);
pub const LVGMF_BORDERCOLOR = @as(u32, 2);
pub const LVGMF_TEXTCOLOR = @as(u32, 4);
pub const LVM_SETGROUPMETRICS = @as(u32, 4251);
pub const LVM_GETGROUPMETRICS = @as(u32, 4252);
pub const LVM_ENABLEGROUPVIEW = @as(u32, 4253);
pub const LVM_SORTGROUPS = @as(u32, 4254);
pub const LVM_INSERTGROUPSORTED = @as(u32, 4255);
pub const LVM_REMOVEALLGROUPS = @as(u32, 4256);
pub const LVM_HASGROUP = @as(u32, 4257);
pub const LVM_GETGROUPSTATE = @as(u32, 4188);
pub const LVM_GETFOCUSEDGROUP = @as(u32, 4189);
pub const LVTVIF_AUTOSIZE = @as(u32, 0);
pub const LVTVIF_FIXEDWIDTH = @as(u32, 1);
pub const LVTVIF_FIXEDHEIGHT = @as(u32, 2);
pub const LVTVIF_FIXEDSIZE = @as(u32, 3);
pub const LVTVIM_TILESIZE = @as(u32, 1);
pub const LVTVIM_COLUMNS = @as(u32, 2);
pub const LVTVIM_LABELMARGIN = @as(u32, 4);
pub const LVM_SETTILEVIEWINFO = @as(u32, 4258);
pub const LVM_GETTILEVIEWINFO = @as(u32, 4259);
pub const LVM_SETTILEINFO = @as(u32, 4260);
pub const LVM_GETTILEINFO = @as(u32, 4261);
pub const LVIM_AFTER = @as(u32, 1);
pub const LVM_SETINSERTMARK = @as(u32, 4262);
pub const LVM_GETINSERTMARK = @as(u32, 4263);
pub const LVM_INSERTMARKHITTEST = @as(u32, 4264);
pub const LVM_GETINSERTMARKRECT = @as(u32, 4265);
pub const LVM_SETINSERTMARKCOLOR = @as(u32, 4266);
pub const LVM_GETINSERTMARKCOLOR = @as(u32, 4267);
pub const LVM_SETINFOTIP = @as(u32, 4269);
pub const LVM_GETSELECTEDCOLUMN = @as(u32, 4270);
pub const LVM_ISGROUPVIEWENABLED = @as(u32, 4271);
pub const LVM_GETOUTLINECOLOR = @as(u32, 4272);
pub const LVM_SETOUTLINECOLOR = @as(u32, 4273);
pub const LVM_CANCELEDITLABEL = @as(u32, 4275);
pub const LVM_MAPINDEXTOID = @as(u32, 4276);
pub const LVM_MAPIDTOINDEX = @as(u32, 4277);
pub const LVM_ISITEMVISIBLE = @as(u32, 4278);
pub const LVM_GETEMPTYTEXT = @as(u32, 4300);
pub const LVM_GETFOOTERRECT = @as(u32, 4301);
pub const LVFF_ITEMCOUNT = @as(u32, 1);
pub const LVM_GETFOOTERINFO = @as(u32, 4302);
pub const LVM_GETFOOTERITEMRECT = @as(u32, 4303);
pub const LVFIS_FOCUSED = @as(u32, 1);
pub const LVM_GETFOOTERITEM = @as(u32, 4304);
pub const LVM_GETITEMINDEXRECT = @as(u32, 4305);
pub const LVM_SETITEMINDEXSTATE = @as(u32, 4306);
pub const LVM_GETNEXTITEMINDEX = @as(u32, 4307);
pub const LVKF_ALT = @as(u32, 1);
pub const LVKF_CONTROL = @as(u32, 2);
pub const LVKF_SHIFT = @as(u32, 4);
pub const LVCDRF_NOSELECT = @as(u32, 65536);
pub const LVCDRF_NOGROUPFRAME = @as(u32, 131072);
pub const LVIF_DI_SETITEM = @as(u32, 4096);
pub const LVGIT_UNFOLDED = @as(u32, 1);
pub const LVNSCH_DEFAULT = @as(i32, -1);
pub const LVNSCH_ERROR = @as(i32, -2);
pub const LVNSCH_IGNORE = @as(i32, -3);
pub const TVS_HASBUTTONS = @as(u32, 1);
pub const TVS_HASLINES = @as(u32, 2);
pub const TVS_LINESATROOT = @as(u32, 4);
pub const TVS_EDITLABELS = @as(u32, 8);
pub const TVS_DISABLEDRAGDROP = @as(u32, 16);
pub const TVS_SHOWSELALWAYS = @as(u32, 32);
pub const TVS_RTLREADING = @as(u32, 64);
pub const TVS_NOTOOLTIPS = @as(u32, 128);
pub const TVS_CHECKBOXES = @as(u32, 256);
pub const TVS_TRACKSELECT = @as(u32, 512);
pub const TVS_SINGLEEXPAND = @as(u32, 1024);
pub const TVS_INFOTIP = @as(u32, 2048);
pub const TVS_FULLROWSELECT = @as(u32, 4096);
pub const TVS_NOSCROLL = @as(u32, 8192);
pub const TVS_NONEVENHEIGHT = @as(u32, 16384);
pub const TVS_NOHSCROLL = @as(u32, 32768);
pub const TVS_EX_NOSINGLECOLLAPSE = @as(u32, 1);
pub const TVS_EX_MULTISELECT = @as(u32, 2);
pub const TVS_EX_DOUBLEBUFFER = @as(u32, 4);
pub const TVS_EX_NOINDENTSTATE = @as(u32, 8);
pub const TVS_EX_RICHTOOLTIP = @as(u32, 16);
pub const TVS_EX_AUTOHSCROLL = @as(u32, 32);
pub const TVS_EX_FADEINOUTEXPANDOS = @as(u32, 64);
pub const TVS_EX_PARTIALCHECKBOXES = @as(u32, 128);
pub const TVS_EX_EXCLUSIONCHECKBOXES = @as(u32, 256);
pub const TVS_EX_DIMMEDCHECKBOXES = @as(u32, 512);
pub const TVS_EX_DRAWIMAGEASYNC = @as(u32, 1024);
pub const TVIS_SELECTED = @as(u32, 2);
pub const TVIS_CUT = @as(u32, 4);
pub const TVIS_DROPHILITED = @as(u32, 8);
pub const TVIS_BOLD = @as(u32, 16);
pub const TVIS_EXPANDED = @as(u32, 32);
pub const TVIS_EXPANDEDONCE = @as(u32, 64);
pub const TVIS_EXPANDPARTIAL = @as(u32, 128);
pub const TVIS_OVERLAYMASK = @as(u32, 3840);
pub const TVIS_STATEIMAGEMASK = @as(u32, 61440);
pub const TVIS_USERMASK = @as(u32, 61440);
pub const TVIS_EX_FLAT = @as(u32, 1);
pub const TVIS_EX_DISABLED = @as(u32, 2);
pub const TVIS_EX_ALL = @as(u32, 2);
pub const TVM_INSERTITEMA = @as(u32, 4352);
pub const TVM_INSERTITEMW = @as(u32, 4402);
pub const TVM_DELETEITEM = @as(u32, 4353);
pub const TVM_EXPAND = @as(u32, 4354);
pub const TVE_COLLAPSE = @as(u32, 1);
pub const TVE_EXPAND = @as(u32, 2);
pub const TVE_TOGGLE = @as(u32, 3);
pub const TVE_EXPANDPARTIAL = @as(u32, 16384);
pub const TVE_COLLAPSERESET = @as(u32, 32768);
pub const TVM_GETITEMRECT = @as(u32, 4356);
pub const TVM_GETCOUNT = @as(u32, 4357);
pub const TVM_GETINDENT = @as(u32, 4358);
pub const TVM_SETINDENT = @as(u32, 4359);
pub const TVM_GETIMAGELIST = @as(u32, 4360);
pub const TVSIL_NORMAL = @as(u32, 0);
pub const TVSIL_STATE = @as(u32, 2);
pub const TVM_SETIMAGELIST = @as(u32, 4361);
pub const TVM_GETNEXTITEM = @as(u32, 4362);
pub const TVGN_ROOT = @as(u32, 0);
pub const TVGN_NEXT = @as(u32, 1);
pub const TVGN_PREVIOUS = @as(u32, 2);
pub const TVGN_PARENT = @as(u32, 3);
pub const TVGN_CHILD = @as(u32, 4);
pub const TVGN_FIRSTVISIBLE = @as(u32, 5);
pub const TVGN_NEXTVISIBLE = @as(u32, 6);
pub const TVGN_PREVIOUSVISIBLE = @as(u32, 7);
pub const TVGN_DROPHILITE = @as(u32, 8);
pub const TVGN_CARET = @as(u32, 9);
pub const TVGN_LASTVISIBLE = @as(u32, 10);
pub const TVGN_NEXTSELECTED = @as(u32, 11);
pub const TVSI_NOSINGLEEXPAND = @as(u32, 32768);
pub const TVM_SELECTITEM = @as(u32, 4363);
pub const TVM_GETITEMA = @as(u32, 4364);
pub const TVM_GETITEMW = @as(u32, 4414);
pub const TVM_SETITEMA = @as(u32, 4365);
pub const TVM_SETITEMW = @as(u32, 4415);
pub const TVM_EDITLABELA = @as(u32, 4366);
pub const TVM_EDITLABELW = @as(u32, 4417);
pub const TVM_GETEDITCONTROL = @as(u32, 4367);
pub const TVM_GETVISIBLECOUNT = @as(u32, 4368);
pub const TVM_HITTEST = @as(u32, 4369);
pub const TVM_CREATEDRAGIMAGE = @as(u32, 4370);
pub const TVM_SORTCHILDREN = @as(u32, 4371);
pub const TVM_ENSUREVISIBLE = @as(u32, 4372);
pub const TVM_SORTCHILDRENCB = @as(u32, 4373);
pub const TVM_ENDEDITLABELNOW = @as(u32, 4374);
pub const TVM_GETISEARCHSTRINGA = @as(u32, 4375);
pub const TVM_GETISEARCHSTRINGW = @as(u32, 4416);
pub const TVM_SETTOOLTIPS = @as(u32, 4376);
pub const TVM_GETTOOLTIPS = @as(u32, 4377);
pub const TVM_SETINSERTMARK = @as(u32, 4378);
pub const TVM_SETITEMHEIGHT = @as(u32, 4379);
pub const TVM_GETITEMHEIGHT = @as(u32, 4380);
pub const TVM_SETBKCOLOR = @as(u32, 4381);
pub const TVM_SETTEXTCOLOR = @as(u32, 4382);
pub const TVM_GETBKCOLOR = @as(u32, 4383);
pub const TVM_GETTEXTCOLOR = @as(u32, 4384);
pub const TVM_SETSCROLLTIME = @as(u32, 4385);
pub const TVM_GETSCROLLTIME = @as(u32, 4386);
pub const TVM_SETINSERTMARKCOLOR = @as(u32, 4389);
pub const TVM_GETINSERTMARKCOLOR = @as(u32, 4390);
pub const TVM_SETBORDER = @as(u32, 4387);
pub const TVSBF_XBORDER = @as(u32, 1);
pub const TVSBF_YBORDER = @as(u32, 2);
pub const TVM_GETITEMSTATE = @as(u32, 4391);
pub const TVM_SETLINECOLOR = @as(u32, 4392);
pub const TVM_GETLINECOLOR = @as(u32, 4393);
pub const TVM_MAPACCIDTOHTREEITEM = @as(u32, 4394);
pub const TVM_MAPHTREEITEMTOACCID = @as(u32, 4395);
pub const TVM_SETEXTENDEDSTYLE = @as(u32, 4396);
pub const TVM_GETEXTENDEDSTYLE = @as(u32, 4397);
pub const TVM_SETAUTOSCROLLINFO = @as(u32, 4411);
pub const TVM_SETHOT = @as(u32, 4410);
pub const TVM_GETSELECTEDCOUNT = @as(u32, 4422);
pub const TVM_SHOWINFOTIP = @as(u32, 4423);
pub const TVM_GETITEMPARTRECT = @as(u32, 4424);
pub const TVC_UNKNOWN = @as(u32, 0);
pub const TVC_BYMOUSE = @as(u32, 1);
pub const TVC_BYKEYBOARD = @as(u32, 2);
pub const TVNRET_DEFAULT = @as(u32, 0);
pub const TVNRET_SKIPOLD = @as(u32, 1);
pub const TVNRET_SKIPNEW = @as(u32, 2);
pub const TVCDRF_NOIMAGES = @as(u32, 65536);
pub const CBEM_INSERTITEMA = @as(u32, 1025);
pub const CBEM_SETIMAGELIST = @as(u32, 1026);
pub const CBEM_GETIMAGELIST = @as(u32, 1027);
pub const CBEM_GETITEMA = @as(u32, 1028);
pub const CBEM_SETITEMA = @as(u32, 1029);
pub const CBEM_GETCOMBOCONTROL = @as(u32, 1030);
pub const CBEM_GETEDITCONTROL = @as(u32, 1031);
pub const CBEM_SETEXSTYLE = @as(u32, 1032);
pub const CBEM_SETEXTENDEDSTYLE = @as(u32, 1038);
pub const CBEM_GETEXSTYLE = @as(u32, 1033);
pub const CBEM_GETEXTENDEDSTYLE = @as(u32, 1033);
pub const CBEM_HASEDITCHANGED = @as(u32, 1034);
pub const CBEM_INSERTITEMW = @as(u32, 1035);
pub const CBEM_SETITEMW = @as(u32, 1036);
pub const CBEM_GETITEMW = @as(u32, 1037);
pub const CBES_EX_NOEDITIMAGE = @as(u32, 1);
pub const CBES_EX_NOEDITIMAGEINDENT = @as(u32, 2);
pub const CBES_EX_PATHWORDBREAKPROC = @as(u32, 4);
pub const CBES_EX_NOSIZELIMIT = @as(u32, 8);
pub const CBES_EX_CASESENSITIVE = @as(u32, 16);
pub const CBES_EX_TEXTENDELLIPSIS = @as(u32, 32);
pub const CBENF_KILLFOCUS = @as(u32, 1);
pub const CBENF_RETURN = @as(u32, 2);
pub const CBENF_ESCAPE = @as(u32, 3);
pub const CBENF_DROPDOWN = @as(u32, 4);
pub const CBEMAXSTRLEN = @as(u32, 260);
pub const TCS_SCROLLOPPOSITE = @as(u32, 1);
pub const TCS_BOTTOM = @as(u32, 2);
pub const TCS_RIGHT = @as(u32, 2);
pub const TCS_MULTISELECT = @as(u32, 4);
pub const TCS_FLATBUTTONS = @as(u32, 8);
pub const TCS_FORCEICONLEFT = @as(u32, 16);
pub const TCS_FORCELABELLEFT = @as(u32, 32);
pub const TCS_HOTTRACK = @as(u32, 64);
pub const TCS_VERTICAL = @as(u32, 128);
pub const TCS_TABS = @as(u32, 0);
pub const TCS_BUTTONS = @as(u32, 256);
pub const TCS_SINGLELINE = @as(u32, 0);
pub const TCS_MULTILINE = @as(u32, 512);
pub const TCS_RIGHTJUSTIFY = @as(u32, 0);
pub const TCS_FIXEDWIDTH = @as(u32, 1024);
pub const TCS_RAGGEDRIGHT = @as(u32, 2048);
pub const TCS_FOCUSONBUTTONDOWN = @as(u32, 4096);
pub const TCS_OWNERDRAWFIXED = @as(u32, 8192);
pub const TCS_TOOLTIPS = @as(u32, 16384);
pub const TCS_FOCUSNEVER = @as(u32, 32768);
pub const TCS_EX_FLATSEPARATORS = @as(u32, 1);
pub const TCS_EX_REGISTERDROP = @as(u32, 2);
pub const TCM_GETIMAGELIST = @as(u32, 4866);
pub const TCM_SETIMAGELIST = @as(u32, 4867);
pub const TCM_GETITEMCOUNT = @as(u32, 4868);
pub const TCIS_BUTTONPRESSED = @as(u32, 1);
pub const TCIS_HIGHLIGHTED = @as(u32, 2);
pub const TCM_GETITEMA = @as(u32, 4869);
pub const TCM_GETITEMW = @as(u32, 4924);
pub const TCM_SETITEMA = @as(u32, 4870);
pub const TCM_SETITEMW = @as(u32, 4925);
pub const TCM_INSERTITEMA = @as(u32, 4871);
pub const TCM_INSERTITEMW = @as(u32, 4926);
pub const TCM_DELETEITEM = @as(u32, 4872);
pub const TCM_DELETEALLITEMS = @as(u32, 4873);
pub const TCM_GETITEMRECT = @as(u32, 4874);
pub const TCM_GETCURSEL = @as(u32, 4875);
pub const TCM_SETCURSEL = @as(u32, 4876);
pub const TCM_HITTEST = @as(u32, 4877);
pub const TCM_SETITEMEXTRA = @as(u32, 4878);
pub const TCM_ADJUSTRECT = @as(u32, 4904);
pub const TCM_SETITEMSIZE = @as(u32, 4905);
pub const TCM_REMOVEIMAGE = @as(u32, 4906);
pub const TCM_SETPADDING = @as(u32, 4907);
pub const TCM_GETROWCOUNT = @as(u32, 4908);
pub const TCM_GETTOOLTIPS = @as(u32, 4909);
pub const TCM_SETTOOLTIPS = @as(u32, 4910);
pub const TCM_GETCURFOCUS = @as(u32, 4911);
pub const TCM_SETCURFOCUS = @as(u32, 4912);
pub const TCM_SETMINTABWIDTH = @as(u32, 4913);
pub const TCM_DESELECTALL = @as(u32, 4914);
pub const TCM_HIGHLIGHTITEM = @as(u32, 4915);
pub const TCM_SETEXTENDEDSTYLE = @as(u32, 4916);
pub const TCM_GETEXTENDEDSTYLE = @as(u32, 4917);
pub const ACS_CENTER = @as(u32, 1);
pub const ACS_TRANSPARENT = @as(u32, 2);
pub const ACS_AUTOPLAY = @as(u32, 4);
pub const ACS_TIMER = @as(u32, 8);
pub const ACM_OPENA = @as(u32, 1124);
pub const ACM_OPENW = @as(u32, 1127);
pub const ACM_PLAY = @as(u32, 1125);
pub const ACM_STOP = @as(u32, 1126);
pub const ACM_ISPLAYING = @as(u32, 1128);
pub const ACN_START = @as(u32, 1);
pub const ACN_STOP = @as(u32, 2);
pub const MCM_FIRST = @as(u32, 4096);
pub const MCM_GETCURSEL = @as(u32, 4097);
pub const MCM_SETCURSEL = @as(u32, 4098);
pub const MCM_GETMAXSELCOUNT = @as(u32, 4099);
pub const MCM_SETMAXSELCOUNT = @as(u32, 4100);
pub const MCM_GETSELRANGE = @as(u32, 4101);
pub const MCM_SETSELRANGE = @as(u32, 4102);
pub const MCM_GETMONTHRANGE = @as(u32, 4103);
pub const MCM_SETDAYSTATE = @as(u32, 4104);
pub const MCM_GETMINREQRECT = @as(u32, 4105);
pub const MCM_SETCOLOR = @as(u32, 4106);
pub const MCM_GETCOLOR = @as(u32, 4107);
pub const MCSC_BACKGROUND = @as(u32, 0);
pub const MCSC_TEXT = @as(u32, 1);
pub const MCSC_TITLEBK = @as(u32, 2);
pub const MCSC_TITLETEXT = @as(u32, 3);
pub const MCSC_MONTHBK = @as(u32, 4);
pub const MCSC_TRAILINGTEXT = @as(u32, 5);
pub const MCM_SETTODAY = @as(u32, 4108);
pub const MCM_GETTODAY = @as(u32, 4109);
pub const MCM_HITTEST = @as(u32, 4110);
pub const MCHT_TITLE = @as(u32, 65536);
pub const MCHT_CALENDAR = @as(u32, 131072);
pub const MCHT_TODAYLINK = @as(u32, 196608);
pub const MCHT_CALENDARCONTROL = @as(u32, 1048576);
pub const MCHT_NEXT = @as(u32, 16777216);
pub const MCHT_PREV = @as(u32, 33554432);
pub const MCHT_NOWHERE = @as(u32, 0);
pub const MCM_SETFIRSTDAYOFWEEK = @as(u32, 4111);
pub const MCM_GETFIRSTDAYOFWEEK = @as(u32, 4112);
pub const MCM_GETRANGE = @as(u32, 4113);
pub const MCM_SETRANGE = @as(u32, 4114);
pub const MCM_GETMONTHDELTA = @as(u32, 4115);
pub const MCM_SETMONTHDELTA = @as(u32, 4116);
pub const MCM_GETMAXTODAYWIDTH = @as(u32, 4117);
pub const MCMV_MONTH = @as(u32, 0);
pub const MCMV_YEAR = @as(u32, 1);
pub const MCMV_DECADE = @as(u32, 2);
pub const MCMV_CENTURY = @as(u32, 3);
pub const MCM_GETCURRENTVIEW = @as(u32, 4118);
pub const MCM_GETCALENDARCOUNT = @as(u32, 4119);
pub const MCM_GETCALENDARGRIDINFO = @as(u32, 4120);
pub const MCM_GETCALID = @as(u32, 4123);
pub const MCM_SETCALID = @as(u32, 4124);
pub const MCM_SIZERECTTOMIN = @as(u32, 4125);
pub const MCM_SETCALENDARBORDER = @as(u32, 4126);
pub const MCM_GETCALENDARBORDER = @as(u32, 4127);
pub const MCM_SETCURRENTVIEW = @as(u32, 4128);
pub const MCS_DAYSTATE = @as(u32, 1);
pub const MCS_MULTISELECT = @as(u32, 2);
pub const MCS_WEEKNUMBERS = @as(u32, 4);
pub const MCS_NOTODAYCIRCLE = @as(u32, 8);
pub const MCS_NOTODAY = @as(u32, 16);
pub const MCS_NOTRAILINGDATES = @as(u32, 64);
pub const MCS_SHORTDAYSOFWEEK = @as(u32, 128);
pub const MCS_NOSELCHANGEONNAV = @as(u32, 256);
pub const GMR_VISIBLE = @as(u32, 0);
pub const GMR_DAYSTATE = @as(u32, 1);
pub const DTM_FIRST = @as(u32, 4096);
pub const DTM_GETSYSTEMTIME = @as(u32, 4097);
pub const DTM_SETSYSTEMTIME = @as(u32, 4098);
pub const DTM_GETRANGE = @as(u32, 4099);
pub const DTM_SETRANGE = @as(u32, 4100);
pub const DTM_SETFORMATA = @as(u32, 4101);
pub const DTM_SETFORMATW = @as(u32, 4146);
pub const DTM_SETMCCOLOR = @as(u32, 4102);
pub const DTM_GETMCCOLOR = @as(u32, 4103);
pub const DTM_GETMONTHCAL = @as(u32, 4104);
pub const DTM_SETMCFONT = @as(u32, 4105);
pub const DTM_GETMCFONT = @as(u32, 4106);
pub const DTM_SETMCSTYLE = @as(u32, 4107);
pub const DTM_GETMCSTYLE = @as(u32, 4108);
pub const DTM_CLOSEMONTHCAL = @as(u32, 4109);
pub const DTM_GETDATETIMEPICKERINFO = @as(u32, 4110);
pub const DTM_GETIDEALSIZE = @as(u32, 4111);
pub const DTS_UPDOWN = @as(u32, 1);
pub const DTS_SHOWNONE = @as(u32, 2);
pub const DTS_SHORTDATEFORMAT = @as(u32, 0);
pub const DTS_LONGDATEFORMAT = @as(u32, 4);
pub const DTS_SHORTDATECENTURYFORMAT = @as(u32, 12);
pub const DTS_TIMEFORMAT = @as(u32, 9);
pub const DTS_APPCANPARSE = @as(u32, 16);
pub const DTS_RIGHTALIGN = @as(u32, 32);
pub const GDTR_MIN = @as(u32, 1);
pub const GDTR_MAX = @as(u32, 2);
pub const GDT_ERROR = @as(i32, -1);
pub const GDT_VALID = @as(u32, 0);
pub const GDT_NONE = @as(u32, 1);
pub const IPM_CLEARADDRESS = @as(u32, 1124);
pub const IPM_SETADDRESS = @as(u32, 1125);
pub const IPM_GETADDRESS = @as(u32, 1126);
pub const IPM_SETRANGE = @as(u32, 1127);
pub const IPM_SETFOCUS = @as(u32, 1128);
pub const IPM_ISBLANK = @as(u32, 1129);
pub const PGS_VERT = @as(u32, 0);
pub const PGS_HORZ = @as(u32, 1);
pub const PGS_AUTOSCROLL = @as(u32, 2);
pub const PGS_DRAGNDROP = @as(u32, 4);
pub const PGF_INVISIBLE = @as(u32, 0);
pub const PGF_NORMAL = @as(u32, 1);
pub const PGF_GRAYED = @as(u32, 2);
pub const PGF_DEPRESSED = @as(u32, 4);
pub const PGF_HOT = @as(u32, 8);
pub const PGB_TOPORLEFT = @as(u32, 0);
pub const PGB_BOTTOMORRIGHT = @as(u32, 1);
pub const PGM_SETCHILD = @as(u32, 5121);
pub const PGM_RECALCSIZE = @as(u32, 5122);
pub const PGM_FORWARDMOUSE = @as(u32, 5123);
pub const PGM_SETBKCOLOR = @as(u32, 5124);
pub const PGM_GETBKCOLOR = @as(u32, 5125);
pub const PGM_SETBORDER = @as(u32, 5126);
pub const PGM_GETBORDER = @as(u32, 5127);
pub const PGM_SETPOS = @as(u32, 5128);
pub const PGM_GETPOS = @as(u32, 5129);
pub const PGM_SETBUTTONSIZE = @as(u32, 5130);
pub const PGM_GETBUTTONSIZE = @as(u32, 5131);
pub const PGM_GETBUTTONSTATE = @as(u32, 5132);
pub const PGM_SETSCROLLINFO = @as(u32, 5133);
pub const NFS_EDIT = @as(u32, 1);
pub const NFS_STATIC = @as(u32, 2);
pub const NFS_LISTCOMBO = @as(u32, 4);
pub const NFS_BUTTON = @as(u32, 8);
pub const NFS_ALL = @as(u32, 16);
pub const NFS_USEFONTASSOC = @as(u32, 32);
pub const BCM_GETIDEALSIZE = @as(u32, 5633);
pub const BCM_SETIMAGELIST = @as(u32, 5634);
pub const BCM_GETIMAGELIST = @as(u32, 5635);
pub const BCM_SETTEXTMARGIN = @as(u32, 5636);
pub const BCM_GETTEXTMARGIN = @as(u32, 5637);
pub const BCN_HOTITEMCHANGE = @as(u32, 4294966047);
pub const BST_HOT = @as(u32, 512);
pub const BST_DROPDOWNPUSHED = @as(u32, 1024);
pub const BS_SPLITBUTTON = @as(i32, 12);
pub const BS_DEFSPLITBUTTON = @as(i32, 13);
pub const BS_COMMANDLINK = @as(i32, 14);
pub const BS_DEFCOMMANDLINK = @as(i32, 15);
pub const BCSIF_GLYPH = @as(u32, 1);
pub const BCSIF_IMAGE = @as(u32, 2);
pub const BCSIF_STYLE = @as(u32, 4);
pub const BCSIF_SIZE = @as(u32, 8);
pub const BCSS_NOSPLIT = @as(u32, 1);
pub const BCSS_STRETCH = @as(u32, 2);
pub const BCSS_ALIGNLEFT = @as(u32, 4);
pub const BCSS_IMAGE = @as(u32, 8);
pub const BCM_SETDROPDOWNSTATE = @as(u32, 5638);
pub const BCM_SETSPLITINFO = @as(u32, 5639);
pub const BCM_GETSPLITINFO = @as(u32, 5640);
pub const BCM_SETNOTE = @as(u32, 5641);
pub const BCM_GETNOTE = @as(u32, 5642);
pub const BCM_GETNOTELENGTH = @as(u32, 5643);
pub const BCM_SETSHIELD = @as(u32, 5644);
pub const BCN_DROPDOWN = @as(u32, 4294966048);
pub const ES_EX_ALLOWEOL_CR = @as(i32, 1);
pub const ES_EX_ALLOWEOL_LF = @as(i32, 2);
pub const ES_EX_CONVERT_EOL_ON_PASTE = @as(i32, 4);
pub const ES_EX_ZOOMABLE = @as(i32, 16);
pub const EM_SETCUEBANNER = @as(u32, 5377);
pub const EM_GETCUEBANNER = @as(u32, 5378);
pub const EM_SHOWBALLOONTIP = @as(u32, 5379);
pub const EM_HIDEBALLOONTIP = @as(u32, 5380);
pub const EM_SETHILITE = @as(u32, 5381);
pub const EM_GETHILITE = @as(u32, 5382);
pub const EM_NOSETFOCUS = @as(u32, 5383);
pub const EM_TAKEFOCUS = @as(u32, 5384);
pub const EM_SETEXTENDEDSTYLE = @as(u32, 5386);
pub const EM_GETEXTENDEDSTYLE = @as(u32, 5387);
pub const EM_SETENDOFLINE = @as(u32, 5388);
pub const EM_GETENDOFLINE = @as(u32, 5389);
pub const EM_ENABLESEARCHWEB = @as(u32, 5390);
pub const EM_SEARCHWEB = @as(u32, 5391);
pub const EM_SETCARETINDEX = @as(u32, 5393);
pub const EM_GETCARETINDEX = @as(u32, 5394);
pub const EM_FILELINEFROMCHAR = @as(u32, 5395);
pub const EM_FILELINEINDEX = @as(u32, 5396);
pub const EM_FILELINELENGTH = @as(u32, 5397);
pub const EM_GETFILELINE = @as(u32, 5398);
pub const EM_GETFILELINECOUNT = @as(u32, 5399);
pub const CB_SETMINVISIBLE = @as(u32, 5889);
pub const CB_GETMINVISIBLE = @as(u32, 5890);
pub const CB_SETCUEBANNER = @as(u32, 5891);
pub const CB_GETCUEBANNER = @as(u32, 5892);
pub const WM_MOUSEHOVER = @as(u32, 673);
pub const WM_MOUSELEAVE = @as(u32, 675);
pub const HOVER_DEFAULT = @as(u32, 4294967295);
pub const WSB_PROP_MASK = @as(i32, 4095);
pub const FSB_FLAT_MODE = @as(u32, 2);
pub const FSB_ENCARTA_MODE = @as(u32, 1);
pub const FSB_REGULAR_MODE = @as(u32, 0);
pub const EM_GETSEL = @as(u32, 176);
pub const EM_SETSEL = @as(u32, 177);
pub const EM_GETRECT = @as(u32, 178);
pub const EM_SETRECT = @as(u32, 179);
pub const EM_SETRECTNP = @as(u32, 180);
pub const EM_SCROLL = @as(u32, 181);
pub const EM_LINESCROLL = @as(u32, 182);
pub const EM_GETMODIFY = @as(u32, 184);
pub const EM_SETMODIFY = @as(u32, 185);
pub const EM_GETLINECOUNT = @as(u32, 186);
pub const EM_LINEINDEX = @as(u32, 187);
pub const EM_SETHANDLE = @as(u32, 188);
pub const EM_GETHANDLE = @as(u32, 189);
pub const EM_GETTHUMB = @as(u32, 190);
pub const EM_LINELENGTH = @as(u32, 193);
pub const EM_REPLACESEL = @as(u32, 194);
pub const EM_GETLINE = @as(u32, 196);
pub const EM_LIMITTEXT = @as(u32, 197);
pub const EM_CANUNDO = @as(u32, 198);
pub const EM_UNDO = @as(u32, 199);
pub const EM_FMTLINES = @as(u32, 200);
pub const EM_LINEFROMCHAR = @as(u32, 201);
pub const EM_SETTABSTOPS = @as(u32, 203);
pub const EM_SETPASSWORDCHAR = @as(u32, 204);
pub const EM_EMPTYUNDOBUFFER = @as(u32, 205);
pub const EM_GETFIRSTVISIBLELINE = @as(u32, 206);
pub const EM_SETREADONLY = @as(u32, 207);
pub const EM_SETWORDBREAKPROC = @as(u32, 208);
pub const EM_GETWORDBREAKPROC = @as(u32, 209);
pub const EM_GETPASSWORDCHAR = @as(u32, 210);
pub const EM_SETMARGINS = @as(u32, 211);
pub const EM_GETMARGINS = @as(u32, 212);
pub const EM_SETIMESTATUS = @as(u32, 216);
pub const EM_GETIMESTATUS = @as(u32, 217);
pub const EM_ENABLEFEATURE = @as(u32, 218);
//--------------------------------------------------------------------------------
// Section: Types (500)
//--------------------------------------------------------------------------------
pub const THEME_PROPERTY_SYMBOL_ID = enum(u32) {
RESERVEDLOW = 0,
RESERVEDHIGH = 7999,
DIBDATA = 2,
GLYPHDIBDATA = 8,
ENUM = 200,
STRING = 201,
INT = 202,
BOOL = 203,
COLOR = 204,
MARGINS = 205,
FILENAME = 206,
SIZE = 207,
POSITION = 208,
RECT = 209,
FONT = 210,
INTLIST = 211,
HBITMAP = 212,
DISKSTREAM = 213,
STREAM = 214,
BITMAPREF = 215,
FLOAT = 216,
FLOATLIST = 217,
COLORSCHEMES = 401,
SIZES = 402,
CHARSET = 403,
NAME = 600,
DISPLAYNAME = 601,
TOOLTIP = 602,
COMPANY = 603,
AUTHOR = 604,
COPYRIGHT = 605,
URL = 606,
VERSION = 607,
DESCRIPTION = 608,
// FIRST_RCSTRING_NAME = 601, this enum value conflicts with DISPLAYNAME
// LAST_RCSTRING_NAME = 608, this enum value conflicts with DESCRIPTION
CAPTIONFONT = 801,
SMALLCAPTIONFONT = 802,
MENUFONT = 803,
STATUSFONT = 804,
MSGBOXFONT = 805,
ICONTITLEFONT = 806,
HEADING1FONT = 807,
HEADING2FONT = 808,
BODYFONT = 809,
// FIRSTFONT = 801, this enum value conflicts with CAPTIONFONT
// LASTFONT = 809, this enum value conflicts with BODYFONT
FLATMENUS = 1001,
// FIRSTBOOL = 1001, this enum value conflicts with FLATMENUS
// LASTBOOL = 1001, this enum value conflicts with FLATMENUS
SIZINGBORDERWIDTH = 1201,
SCROLLBARWIDTH = 1202,
SCROLLBARHEIGHT = 1203,
CAPTIONBARWIDTH = 1204,
CAPTIONBARHEIGHT = 1205,
SMCAPTIONBARWIDTH = 1206,
SMCAPTIONBARHEIGHT = 1207,
MENUBARWIDTH = 1208,
MENUBARHEIGHT = 1209,
PADDEDBORDERWIDTH = 1210,
// FIRSTSIZE = 1201, this enum value conflicts with SIZINGBORDERWIDTH
// LASTSIZE = 1210, this enum value conflicts with PADDEDBORDERWIDTH
MINCOLORDEPTH = 1301,
// FIRSTINT = 1301, this enum value conflicts with MINCOLORDEPTH
// LASTINT = 1301, this enum value conflicts with MINCOLORDEPTH
CSSNAME = 1401,
XMLNAME = 1402,
LASTUPDATED = 1403,
ALIAS = 1404,
// FIRSTSTRING = 1401, this enum value conflicts with CSSNAME
// LASTSTRING = 1404, this enum value conflicts with ALIAS
SCROLLBAR = 1601,
BACKGROUND = 1602,
ACTIVECAPTION = 1603,
INACTIVECAPTION = 1604,
MENU = 1605,
WINDOW = 1606,
WINDOWFRAME = 1607,
MENUTEXT = 1608,
WINDOWTEXT = 1609,
CAPTIONTEXT = 1610,
ACTIVEBORDER = 1611,
INACTIVEBORDER = 1612,
APPWORKSPACE = 1613,
HIGHLIGHT = 1614,
HIGHLIGHTTEXT = 1615,
BTNFACE = 1616,
BTNSHADOW = 1617,
GRAYTEXT = 1618,
BTNTEXT = 1619,
INACTIVECAPTIONTEXT = 1620,
BTNHIGHLIGHT = 1621,
DKSHADOW3D = 1622,
LIGHT3D = 1623,
INFOTEXT = 1624,
INFOBK = 1625,
BUTTONALTERNATEFACE = 1626,
HOTTRACKING = 1627,
GRADIENTACTIVECAPTION = 1628,
GRADIENTINACTIVECAPTION = 1629,
MENUHILIGHT = 1630,
MENUBAR = 1631,
// FIRSTCOLOR = 1601, this enum value conflicts with SCROLLBAR
// LASTCOLOR = 1631, this enum value conflicts with MENUBAR
FROMHUE1 = 1801,
FROMHUE2 = 1802,
FROMHUE3 = 1803,
FROMHUE4 = 1804,
FROMHUE5 = 1805,
TOHUE1 = 1806,
TOHUE2 = 1807,
TOHUE3 = 1808,
TOHUE4 = 1809,
TOHUE5 = 1810,
FROMCOLOR1 = 2001,
FROMCOLOR2 = 2002,
FROMCOLOR3 = 2003,
FROMCOLOR4 = 2004,
FROMCOLOR5 = 2005,
TOCOLOR1 = 2006,
TOCOLOR2 = 2007,
TOCOLOR3 = 2008,
TOCOLOR4 = 2009,
TOCOLOR5 = 2010,
TRANSPARENT = 2201,
AUTOSIZE = 2202,
BORDERONLY = 2203,
COMPOSITED = 2204,
BGFILL = 2205,
GLYPHTRANSPARENT = 2206,
GLYPHONLY = 2207,
ALWAYSSHOWSIZINGBAR = 2208,
MIRRORIMAGE = 2209,
UNIFORMSIZING = 2210,
INTEGRALSIZING = 2211,
SOURCEGROW = 2212,
SOURCESHRINK = 2213,
DRAWBORDERS = 2214,
NOETCHEDEFFECT = 2215,
TEXTAPPLYOVERLAY = 2216,
TEXTGLOW = 2217,
TEXTITALIC = 2218,
COMPOSITEDOPAQUE = 2219,
LOCALIZEDMIRRORIMAGE = 2220,
IMAGECOUNT = 2401,
ALPHALEVEL = 2402,
BORDERSIZE = 2403,
ROUNDCORNERWIDTH = 2404,
ROUNDCORNERHEIGHT = 2405,
GRADIENTRATIO1 = 2406,
GRADIENTRATIO2 = 2407,
GRADIENTRATIO3 = 2408,
GRADIENTRATIO4 = 2409,
GRADIENTRATIO5 = 2410,
PROGRESSCHUNKSIZE = 2411,
PROGRESSSPACESIZE = 2412,
SATURATION = 2413,
TEXTBORDERSIZE = 2414,
ALPHATHRESHOLD = 2415,
WIDTH = 2416,
HEIGHT = 2417,
GLYPHINDEX = 2418,
TRUESIZESTRETCHMARK = 2419,
MINDPI1 = 2420,
MINDPI2 = 2421,
MINDPI3 = 2422,
MINDPI4 = 2423,
MINDPI5 = 2424,
TEXTGLOWSIZE = 2425,
FRAMESPERSECOND = 2426,
PIXELSPERFRAME = 2427,
ANIMATIONDELAY = 2428,
GLOWINTENSITY = 2429,
OPACITY = 2430,
COLORIZATIONCOLOR = 2431,
COLORIZATIONOPACITY = 2432,
MINDPI6 = 2433,
MINDPI7 = 2434,
GLYPHFONT = 2601,
IMAGEFILE = 3001,
IMAGEFILE1 = 3002,
IMAGEFILE2 = 3003,
IMAGEFILE3 = 3004,
IMAGEFILE4 = 3005,
IMAGEFILE5 = 3006,
GLYPHIMAGEFILE = 3008,
IMAGEFILE6 = 3009,
IMAGEFILE7 = 3010,
TEXT = 3201,
CLASSICVALUE = 3202,
OFFSET = 3401,
TEXTSHADOWOFFSET = 3402,
MINSIZE = 3403,
MINSIZE1 = 3404,
MINSIZE2 = 3405,
MINSIZE3 = 3406,
MINSIZE4 = 3407,
MINSIZE5 = 3408,
NORMALSIZE = 3409,
MINSIZE6 = 3410,
MINSIZE7 = 3411,
SIZINGMARGINS = 3601,
CONTENTMARGINS = 3602,
CAPTIONMARGINS = 3603,
BORDERCOLOR = 3801,
FILLCOLOR = 3802,
TEXTCOLOR = 3803,
EDGELIGHTCOLOR = 3804,
EDGEHIGHLIGHTCOLOR = 3805,
EDGESHADOWCOLOR = 3806,
EDGEDKSHADOWCOLOR = 3807,
EDGEFILLCOLOR = 3808,
TRANSPARENTCOLOR = 3809,
GRADIENTCOLOR1 = 3810,
GRADIENTCOLOR2 = 3811,
GRADIENTCOLOR3 = 3812,
GRADIENTCOLOR4 = 3813,
GRADIENTCOLOR5 = 3814,
SHADOWCOLOR = 3815,
GLOWCOLOR = 3816,
TEXTBORDERCOLOR = 3817,
TEXTSHADOWCOLOR = 3818,
GLYPHTEXTCOLOR = 3819,
GLYPHTRANSPARENTCOLOR = 3820,
FILLCOLORHINT = 3821,
BORDERCOLORHINT = 3822,
ACCENTCOLORHINT = 3823,
TEXTCOLORHINT = 3824,
HEADING1TEXTCOLOR = 3825,
HEADING2TEXTCOLOR = 3826,
BODYTEXTCOLOR = 3827,
BGTYPE = 4001,
BORDERTYPE = 4002,
FILLTYPE = 4003,
SIZINGTYPE = 4004,
HALIGN = 4005,
CONTENTALIGNMENT = 4006,
VALIGN = 4007,
OFFSETTYPE = 4008,
ICONEFFECT = 4009,
TEXTSHADOWTYPE = 4010,
IMAGELAYOUT = 4011,
GLYPHTYPE = 4012,
IMAGESELECTTYPE = 4013,
GLYPHFONTSIZINGTYPE = 4014,
TRUESIZESCALINGTYPE = 4015,
USERPICTURE = 5001,
DEFAULTPANESIZE = 5002,
BLENDCOLOR = 5003,
CUSTOMSPLITRECT = 5004,
ANIMATIONBUTTONRECT = 5005,
ANIMATIONDURATION = 5006,
TRANSITIONDURATIONS = 6000,
SCALEDBACKGROUND = 7001,
ATLASIMAGE = 8000,
ATLASINPUTIMAGE = 8001,
ATLASRECT = 8002,
};
pub const TMT_RESERVEDLOW = THEME_PROPERTY_SYMBOL_ID.RESERVEDLOW;
pub const TMT_RESERVEDHIGH = THEME_PROPERTY_SYMBOL_ID.RESERVEDHIGH;
pub const TMT_DIBDATA = THEME_PROPERTY_SYMBOL_ID.DIBDATA;
pub const TMT_GLYPHDIBDATA = THEME_PROPERTY_SYMBOL_ID.GLYPHDIBDATA;
pub const TMT_ENUM = THEME_PROPERTY_SYMBOL_ID.ENUM;
pub const TMT_STRING = THEME_PROPERTY_SYMBOL_ID.STRING;
pub const TMT_INT = THEME_PROPERTY_SYMBOL_ID.INT;
pub const TMT_BOOL = THEME_PROPERTY_SYMBOL_ID.BOOL;
pub const TMT_COLOR = THEME_PROPERTY_SYMBOL_ID.COLOR;
pub const TMT_MARGINS = THEME_PROPERTY_SYMBOL_ID.MARGINS;
pub const TMT_FILENAME = THEME_PROPERTY_SYMBOL_ID.FILENAME;
pub const TMT_SIZE = THEME_PROPERTY_SYMBOL_ID.SIZE;
pub const TMT_POSITION = THEME_PROPERTY_SYMBOL_ID.POSITION;
pub const TMT_RECT = THEME_PROPERTY_SYMBOL_ID.RECT;
pub const TMT_FONT = THEME_PROPERTY_SYMBOL_ID.FONT;
pub const TMT_INTLIST = THEME_PROPERTY_SYMBOL_ID.INTLIST;
pub const TMT_HBITMAP = THEME_PROPERTY_SYMBOL_ID.HBITMAP;
pub const TMT_DISKSTREAM = THEME_PROPERTY_SYMBOL_ID.DISKSTREAM;
pub const TMT_STREAM = THEME_PROPERTY_SYMBOL_ID.STREAM;
pub const TMT_BITMAPREF = THEME_PROPERTY_SYMBOL_ID.BITMAPREF;
pub const TMT_FLOAT = THEME_PROPERTY_SYMBOL_ID.FLOAT;
pub const TMT_FLOATLIST = THEME_PROPERTY_SYMBOL_ID.FLOATLIST;
pub const TMT_COLORSCHEMES = THEME_PROPERTY_SYMBOL_ID.COLORSCHEMES;
pub const TMT_SIZES = THEME_PROPERTY_SYMBOL_ID.SIZES;
pub const TMT_CHARSET = THEME_PROPERTY_SYMBOL_ID.CHARSET;
pub const TMT_NAME = THEME_PROPERTY_SYMBOL_ID.NAME;
pub const TMT_DISPLAYNAME = THEME_PROPERTY_SYMBOL_ID.DISPLAYNAME;
pub const TMT_TOOLTIP = THEME_PROPERTY_SYMBOL_ID.TOOLTIP;
pub const TMT_COMPANY = THEME_PROPERTY_SYMBOL_ID.COMPANY;
pub const TMT_AUTHOR = THEME_PROPERTY_SYMBOL_ID.AUTHOR;
pub const TMT_COPYRIGHT = THEME_PROPERTY_SYMBOL_ID.COPYRIGHT;
pub const TMT_URL = THEME_PROPERTY_SYMBOL_ID.URL;
pub const TMT_VERSION = THEME_PROPERTY_SYMBOL_ID.VERSION;
pub const TMT_DESCRIPTION = THEME_PROPERTY_SYMBOL_ID.DESCRIPTION;
pub const TMT_FIRST_RCSTRING_NAME = THEME_PROPERTY_SYMBOL_ID.DISPLAYNAME;
pub const TMT_LAST_RCSTRING_NAME = THEME_PROPERTY_SYMBOL_ID.DESCRIPTION;
pub const TMT_CAPTIONFONT = THEME_PROPERTY_SYMBOL_ID.CAPTIONFONT;
pub const TMT_SMALLCAPTIONFONT = THEME_PROPERTY_SYMBOL_ID.SMALLCAPTIONFONT;
pub const TMT_MENUFONT = THEME_PROPERTY_SYMBOL_ID.MENUFONT;
pub const TMT_STATUSFONT = THEME_PROPERTY_SYMBOL_ID.STATUSFONT;
pub const TMT_MSGBOXFONT = THEME_PROPERTY_SYMBOL_ID.MSGBOXFONT;
pub const TMT_ICONTITLEFONT = THEME_PROPERTY_SYMBOL_ID.ICONTITLEFONT;
pub const TMT_HEADING1FONT = THEME_PROPERTY_SYMBOL_ID.HEADING1FONT;
pub const TMT_HEADING2FONT = THEME_PROPERTY_SYMBOL_ID.HEADING2FONT;
pub const TMT_BODYFONT = THEME_PROPERTY_SYMBOL_ID.BODYFONT;
pub const TMT_FIRSTFONT = THEME_PROPERTY_SYMBOL_ID.CAPTIONFONT;
pub const TMT_LASTFONT = THEME_PROPERTY_SYMBOL_ID.BODYFONT;
pub const TMT_FLATMENUS = THEME_PROPERTY_SYMBOL_ID.FLATMENUS;
pub const TMT_FIRSTBOOL = THEME_PROPERTY_SYMBOL_ID.FLATMENUS;
pub const TMT_LASTBOOL = THEME_PROPERTY_SYMBOL_ID.FLATMENUS;
pub const TMT_SIZINGBORDERWIDTH = THEME_PROPERTY_SYMBOL_ID.SIZINGBORDERWIDTH;
pub const TMT_SCROLLBARWIDTH = THEME_PROPERTY_SYMBOL_ID.SCROLLBARWIDTH;
pub const TMT_SCROLLBARHEIGHT = THEME_PROPERTY_SYMBOL_ID.SCROLLBARHEIGHT;
pub const TMT_CAPTIONBARWIDTH = THEME_PROPERTY_SYMBOL_ID.CAPTIONBARWIDTH;
pub const TMT_CAPTIONBARHEIGHT = THEME_PROPERTY_SYMBOL_ID.CAPTIONBARHEIGHT;
pub const TMT_SMCAPTIONBARWIDTH = THEME_PROPERTY_SYMBOL_ID.SMCAPTIONBARWIDTH;
pub const TMT_SMCAPTIONBARHEIGHT = THEME_PROPERTY_SYMBOL_ID.SMCAPTIONBARHEIGHT;
pub const TMT_MENUBARWIDTH = THEME_PROPERTY_SYMBOL_ID.MENUBARWIDTH;
pub const TMT_MENUBARHEIGHT = THEME_PROPERTY_SYMBOL_ID.MENUBARHEIGHT;
pub const TMT_PADDEDBORDERWIDTH = THEME_PROPERTY_SYMBOL_ID.PADDEDBORDERWIDTH;
pub const TMT_FIRSTSIZE = THEME_PROPERTY_SYMBOL_ID.SIZINGBORDERWIDTH;
pub const TMT_LASTSIZE = THEME_PROPERTY_SYMBOL_ID.PADDEDBORDERWIDTH;
pub const TMT_MINCOLORDEPTH = THEME_PROPERTY_SYMBOL_ID.MINCOLORDEPTH;
pub const TMT_FIRSTINT = THEME_PROPERTY_SYMBOL_ID.MINCOLORDEPTH;
pub const TMT_LASTINT = THEME_PROPERTY_SYMBOL_ID.MINCOLORDEPTH;
pub const TMT_CSSNAME = THEME_PROPERTY_SYMBOL_ID.CSSNAME;
pub const TMT_XMLNAME = THEME_PROPERTY_SYMBOL_ID.XMLNAME;
pub const TMT_LASTUPDATED = THEME_PROPERTY_SYMBOL_ID.LASTUPDATED;
pub const TMT_ALIAS = THEME_PROPERTY_SYMBOL_ID.ALIAS;
pub const TMT_FIRSTSTRING = THEME_PROPERTY_SYMBOL_ID.CSSNAME;
pub const TMT_LASTSTRING = THEME_PROPERTY_SYMBOL_ID.ALIAS;
pub const TMT_SCROLLBAR = THEME_PROPERTY_SYMBOL_ID.SCROLLBAR;
pub const TMT_BACKGROUND = THEME_PROPERTY_SYMBOL_ID.BACKGROUND;
pub const TMT_ACTIVECAPTION = THEME_PROPERTY_SYMBOL_ID.ACTIVECAPTION;
pub const TMT_INACTIVECAPTION = THEME_PROPERTY_SYMBOL_ID.INACTIVECAPTION;
pub const TMT_MENU = THEME_PROPERTY_SYMBOL_ID.MENU;
pub const TMT_WINDOW = THEME_PROPERTY_SYMBOL_ID.WINDOW;
pub const TMT_WINDOWFRAME = THEME_PROPERTY_SYMBOL_ID.WINDOWFRAME;
pub const TMT_MENUTEXT = THEME_PROPERTY_SYMBOL_ID.MENUTEXT;
pub const TMT_WINDOWTEXT = THEME_PROPERTY_SYMBOL_ID.WINDOWTEXT;
pub const TMT_CAPTIONTEXT = THEME_PROPERTY_SYMBOL_ID.CAPTIONTEXT;
pub const TMT_ACTIVEBORDER = THEME_PROPERTY_SYMBOL_ID.ACTIVEBORDER;
pub const TMT_INACTIVEBORDER = THEME_PROPERTY_SYMBOL_ID.INACTIVEBORDER;
pub const TMT_APPWORKSPACE = THEME_PROPERTY_SYMBOL_ID.APPWORKSPACE;
pub const TMT_HIGHLIGHT = THEME_PROPERTY_SYMBOL_ID.HIGHLIGHT;
pub const TMT_HIGHLIGHTTEXT = THEME_PROPERTY_SYMBOL_ID.HIGHLIGHTTEXT;
pub const TMT_BTNFACE = THEME_PROPERTY_SYMBOL_ID.BTNFACE;
pub const TMT_BTNSHADOW = THEME_PROPERTY_SYMBOL_ID.BTNSHADOW;
pub const TMT_GRAYTEXT = THEME_PROPERTY_SYMBOL_ID.GRAYTEXT;
pub const TMT_BTNTEXT = THEME_PROPERTY_SYMBOL_ID.BTNTEXT;
pub const TMT_INACTIVECAPTIONTEXT = THEME_PROPERTY_SYMBOL_ID.INACTIVECAPTIONTEXT;
pub const TMT_BTNHIGHLIGHT = THEME_PROPERTY_SYMBOL_ID.BTNHIGHLIGHT;
pub const TMT_DKSHADOW3D = THEME_PROPERTY_SYMBOL_ID.DKSHADOW3D;
pub const TMT_LIGHT3D = THEME_PROPERTY_SYMBOL_ID.LIGHT3D;
pub const TMT_INFOTEXT = THEME_PROPERTY_SYMBOL_ID.INFOTEXT;
pub const TMT_INFOBK = THEME_PROPERTY_SYMBOL_ID.INFOBK;
pub const TMT_BUTTONALTERNATEFACE = THEME_PROPERTY_SYMBOL_ID.BUTTONALTERNATEFACE;
pub const TMT_HOTTRACKING = THEME_PROPERTY_SYMBOL_ID.HOTTRACKING;
pub const TMT_GRADIENTACTIVECAPTION = THEME_PROPERTY_SYMBOL_ID.GRADIENTACTIVECAPTION;
pub const TMT_GRADIENTINACTIVECAPTION = THEME_PROPERTY_SYMBOL_ID.GRADIENTINACTIVECAPTION;
pub const TMT_MENUHILIGHT = THEME_PROPERTY_SYMBOL_ID.MENUHILIGHT;
pub const TMT_MENUBAR = THEME_PROPERTY_SYMBOL_ID.MENUBAR;
pub const TMT_FIRSTCOLOR = THEME_PROPERTY_SYMBOL_ID.SCROLLBAR;
pub const TMT_LASTCOLOR = THEME_PROPERTY_SYMBOL_ID.MENUBAR;
pub const TMT_FROMHUE1 = THEME_PROPERTY_SYMBOL_ID.FROMHUE1;
pub const TMT_FROMHUE2 = THEME_PROPERTY_SYMBOL_ID.FROMHUE2;
pub const TMT_FROMHUE3 = THEME_PROPERTY_SYMBOL_ID.FROMHUE3;
pub const TMT_FROMHUE4 = THEME_PROPERTY_SYMBOL_ID.FROMHUE4;
pub const TMT_FROMHUE5 = THEME_PROPERTY_SYMBOL_ID.FROMHUE5;
pub const TMT_TOHUE1 = THEME_PROPERTY_SYMBOL_ID.TOHUE1;
pub const TMT_TOHUE2 = THEME_PROPERTY_SYMBOL_ID.TOHUE2;
pub const TMT_TOHUE3 = THEME_PROPERTY_SYMBOL_ID.TOHUE3;
pub const TMT_TOHUE4 = THEME_PROPERTY_SYMBOL_ID.TOHUE4;
pub const TMT_TOHUE5 = THEME_PROPERTY_SYMBOL_ID.TOHUE5;
pub const TMT_FROMCOLOR1 = THEME_PROPERTY_SYMBOL_ID.FROMCOLOR1;
pub const TMT_FROMCOLOR2 = THEME_PROPERTY_SYMBOL_ID.FROMCOLOR2;
pub const TMT_FROMCOLOR3 = THEME_PROPERTY_SYMBOL_ID.FROMCOLOR3;
pub const TMT_FROMCOLOR4 = THEME_PROPERTY_SYMBOL_ID.FROMCOLOR4;
pub const TMT_FROMCOLOR5 = THEME_PROPERTY_SYMBOL_ID.FROMCOLOR5;
pub const TMT_TOCOLOR1 = THEME_PROPERTY_SYMBOL_ID.TOCOLOR1;
pub const TMT_TOCOLOR2 = THEME_PROPERTY_SYMBOL_ID.TOCOLOR2;
pub const TMT_TOCOLOR3 = THEME_PROPERTY_SYMBOL_ID.TOCOLOR3;
pub const TMT_TOCOLOR4 = THEME_PROPERTY_SYMBOL_ID.TOCOLOR4;
pub const TMT_TOCOLOR5 = THEME_PROPERTY_SYMBOL_ID.TOCOLOR5;
pub const TMT_TRANSPARENT = THEME_PROPERTY_SYMBOL_ID.TRANSPARENT;
pub const TMT_AUTOSIZE = THEME_PROPERTY_SYMBOL_ID.AUTOSIZE;
pub const TMT_BORDERONLY = THEME_PROPERTY_SYMBOL_ID.BORDERONLY;
pub const TMT_COMPOSITED = THEME_PROPERTY_SYMBOL_ID.COMPOSITED;
pub const TMT_BGFILL = THEME_PROPERTY_SYMBOL_ID.BGFILL;
pub const TMT_GLYPHTRANSPARENT = THEME_PROPERTY_SYMBOL_ID.GLYPHTRANSPARENT;
pub const TMT_GLYPHONLY = THEME_PROPERTY_SYMBOL_ID.GLYPHONLY;
pub const TMT_ALWAYSSHOWSIZINGBAR = THEME_PROPERTY_SYMBOL_ID.ALWAYSSHOWSIZINGBAR;
pub const TMT_MIRRORIMAGE = THEME_PROPERTY_SYMBOL_ID.MIRRORIMAGE;
pub const TMT_UNIFORMSIZING = THEME_PROPERTY_SYMBOL_ID.UNIFORMSIZING;
pub const TMT_INTEGRALSIZING = THEME_PROPERTY_SYMBOL_ID.INTEGRALSIZING;
pub const TMT_SOURCEGROW = THEME_PROPERTY_SYMBOL_ID.SOURCEGROW;
pub const TMT_SOURCESHRINK = THEME_PROPERTY_SYMBOL_ID.SOURCESHRINK;
pub const TMT_DRAWBORDERS = THEME_PROPERTY_SYMBOL_ID.DRAWBORDERS;
pub const TMT_NOETCHEDEFFECT = THEME_PROPERTY_SYMBOL_ID.NOETCHEDEFFECT;
pub const TMT_TEXTAPPLYOVERLAY = THEME_PROPERTY_SYMBOL_ID.TEXTAPPLYOVERLAY;
pub const TMT_TEXTGLOW = THEME_PROPERTY_SYMBOL_ID.TEXTGLOW;
pub const TMT_TEXTITALIC = THEME_PROPERTY_SYMBOL_ID.TEXTITALIC;
pub const TMT_COMPOSITEDOPAQUE = THEME_PROPERTY_SYMBOL_ID.COMPOSITEDOPAQUE;
pub const TMT_LOCALIZEDMIRRORIMAGE = THEME_PROPERTY_SYMBOL_ID.LOCALIZEDMIRRORIMAGE;
pub const TMT_IMAGECOUNT = THEME_PROPERTY_SYMBOL_ID.IMAGECOUNT;
pub const TMT_ALPHALEVEL = THEME_PROPERTY_SYMBOL_ID.ALPHALEVEL;
pub const TMT_BORDERSIZE = THEME_PROPERTY_SYMBOL_ID.BORDERSIZE;
pub const TMT_ROUNDCORNERWIDTH = THEME_PROPERTY_SYMBOL_ID.ROUNDCORNERWIDTH;
pub const TMT_ROUNDCORNERHEIGHT = THEME_PROPERTY_SYMBOL_ID.ROUNDCORNERHEIGHT;
pub const TMT_GRADIENTRATIO1 = THEME_PROPERTY_SYMBOL_ID.GRADIENTRATIO1;
pub const TMT_GRADIENTRATIO2 = THEME_PROPERTY_SYMBOL_ID.GRADIENTRATIO2;
pub const TMT_GRADIENTRATIO3 = THEME_PROPERTY_SYMBOL_ID.GRADIENTRATIO3;
pub const TMT_GRADIENTRATIO4 = THEME_PROPERTY_SYMBOL_ID.GRADIENTRATIO4;
pub const TMT_GRADIENTRATIO5 = THEME_PROPERTY_SYMBOL_ID.GRADIENTRATIO5;
pub const TMT_PROGRESSCHUNKSIZE = THEME_PROPERTY_SYMBOL_ID.PROGRESSCHUNKSIZE;
pub const TMT_PROGRESSSPACESIZE = THEME_PROPERTY_SYMBOL_ID.PROGRESSSPACESIZE;
pub const TMT_SATURATION = THEME_PROPERTY_SYMBOL_ID.SATURATION;
pub const TMT_TEXTBORDERSIZE = THEME_PROPERTY_SYMBOL_ID.TEXTBORDERSIZE;
pub const TMT_ALPHATHRESHOLD = THEME_PROPERTY_SYMBOL_ID.ALPHATHRESHOLD;
pub const TMT_WIDTH = THEME_PROPERTY_SYMBOL_ID.WIDTH;
pub const TMT_HEIGHT = THEME_PROPERTY_SYMBOL_ID.HEIGHT;
pub const TMT_GLYPHINDEX = THEME_PROPERTY_SYMBOL_ID.GLYPHINDEX;
pub const TMT_TRUESIZESTRETCHMARK = THEME_PROPERTY_SYMBOL_ID.TRUESIZESTRETCHMARK;
pub const TMT_MINDPI1 = THEME_PROPERTY_SYMBOL_ID.MINDPI1;
pub const TMT_MINDPI2 = THEME_PROPERTY_SYMBOL_ID.MINDPI2;
pub const TMT_MINDPI3 = THEME_PROPERTY_SYMBOL_ID.MINDPI3;
pub const TMT_MINDPI4 = THEME_PROPERTY_SYMBOL_ID.MINDPI4;
pub const TMT_MINDPI5 = THEME_PROPERTY_SYMBOL_ID.MINDPI5;
pub const TMT_TEXTGLOWSIZE = THEME_PROPERTY_SYMBOL_ID.TEXTGLOWSIZE;
pub const TMT_FRAMESPERSECOND = THEME_PROPERTY_SYMBOL_ID.FRAMESPERSECOND;
pub const TMT_PIXELSPERFRAME = THEME_PROPERTY_SYMBOL_ID.PIXELSPERFRAME;
pub const TMT_ANIMATIONDELAY = THEME_PROPERTY_SYMBOL_ID.ANIMATIONDELAY;
pub const TMT_GLOWINTENSITY = THEME_PROPERTY_SYMBOL_ID.GLOWINTENSITY;
pub const TMT_OPACITY = THEME_PROPERTY_SYMBOL_ID.OPACITY;
pub const TMT_COLORIZATIONCOLOR = THEME_PROPERTY_SYMBOL_ID.COLORIZATIONCOLOR;
pub const TMT_COLORIZATIONOPACITY = THEME_PROPERTY_SYMBOL_ID.COLORIZATIONOPACITY;
pub const TMT_MINDPI6 = THEME_PROPERTY_SYMBOL_ID.MINDPI6;
pub const TMT_MINDPI7 = THEME_PROPERTY_SYMBOL_ID.MINDPI7;
pub const TMT_GLYPHFONT = THEME_PROPERTY_SYMBOL_ID.GLYPHFONT;
pub const TMT_IMAGEFILE = THEME_PROPERTY_SYMBOL_ID.IMAGEFILE;
pub const TMT_IMAGEFILE1 = THEME_PROPERTY_SYMBOL_ID.IMAGEFILE1;
pub const TMT_IMAGEFILE2 = THEME_PROPERTY_SYMBOL_ID.IMAGEFILE2;
pub const TMT_IMAGEFILE3 = THEME_PROPERTY_SYMBOL_ID.IMAGEFILE3;
pub const TMT_IMAGEFILE4 = THEME_PROPERTY_SYMBOL_ID.IMAGEFILE4;
pub const TMT_IMAGEFILE5 = THEME_PROPERTY_SYMBOL_ID.IMAGEFILE5;
pub const TMT_GLYPHIMAGEFILE = THEME_PROPERTY_SYMBOL_ID.GLYPHIMAGEFILE;
pub const TMT_IMAGEFILE6 = THEME_PROPERTY_SYMBOL_ID.IMAGEFILE6;
pub const TMT_IMAGEFILE7 = THEME_PROPERTY_SYMBOL_ID.IMAGEFILE7;
pub const TMT_TEXT = THEME_PROPERTY_SYMBOL_ID.TEXT;
pub const TMT_CLASSICVALUE = THEME_PROPERTY_SYMBOL_ID.CLASSICVALUE;
pub const TMT_OFFSET = THEME_PROPERTY_SYMBOL_ID.OFFSET;
pub const TMT_TEXTSHADOWOFFSET = THEME_PROPERTY_SYMBOL_ID.TEXTSHADOWOFFSET;
pub const TMT_MINSIZE = THEME_PROPERTY_SYMBOL_ID.MINSIZE;
pub const TMT_MINSIZE1 = THEME_PROPERTY_SYMBOL_ID.MINSIZE1;
pub const TMT_MINSIZE2 = THEME_PROPERTY_SYMBOL_ID.MINSIZE2;
pub const TMT_MINSIZE3 = THEME_PROPERTY_SYMBOL_ID.MINSIZE3;
pub const TMT_MINSIZE4 = THEME_PROPERTY_SYMBOL_ID.MINSIZE4;
pub const TMT_MINSIZE5 = THEME_PROPERTY_SYMBOL_ID.MINSIZE5;
pub const TMT_NORMALSIZE = THEME_PROPERTY_SYMBOL_ID.NORMALSIZE;
pub const TMT_MINSIZE6 = THEME_PROPERTY_SYMBOL_ID.MINSIZE6;
pub const TMT_MINSIZE7 = THEME_PROPERTY_SYMBOL_ID.MINSIZE7;
pub const TMT_SIZINGMARGINS = THEME_PROPERTY_SYMBOL_ID.SIZINGMARGINS;
pub const TMT_CONTENTMARGINS = THEME_PROPERTY_SYMBOL_ID.CONTENTMARGINS;
pub const TMT_CAPTIONMARGINS = THEME_PROPERTY_SYMBOL_ID.CAPTIONMARGINS;
pub const TMT_BORDERCOLOR = THEME_PROPERTY_SYMBOL_ID.BORDERCOLOR;
pub const TMT_FILLCOLOR = THEME_PROPERTY_SYMBOL_ID.FILLCOLOR;
pub const TMT_TEXTCOLOR = THEME_PROPERTY_SYMBOL_ID.TEXTCOLOR;
pub const TMT_EDGELIGHTCOLOR = THEME_PROPERTY_SYMBOL_ID.EDGELIGHTCOLOR;
pub const TMT_EDGEHIGHLIGHTCOLOR = THEME_PROPERTY_SYMBOL_ID.EDGEHIGHLIGHTCOLOR;
pub const TMT_EDGESHADOWCOLOR = THEME_PROPERTY_SYMBOL_ID.EDGESHADOWCOLOR;
pub const TMT_EDGEDKSHADOWCOLOR = THEME_PROPERTY_SYMBOL_ID.EDGEDKSHADOWCOLOR;
pub const TMT_EDGEFILLCOLOR = THEME_PROPERTY_SYMBOL_ID.EDGEFILLCOLOR;
pub const TMT_TRANSPARENTCOLOR = THEME_PROPERTY_SYMBOL_ID.TRANSPARENTCOLOR;
pub const TMT_GRADIENTCOLOR1 = THEME_PROPERTY_SYMBOL_ID.GRADIENTCOLOR1;
pub const TMT_GRADIENTCOLOR2 = THEME_PROPERTY_SYMBOL_ID.GRADIENTCOLOR2;
pub const TMT_GRADIENTCOLOR3 = THEME_PROPERTY_SYMBOL_ID.GRADIENTCOLOR3;
pub const TMT_GRADIENTCOLOR4 = THEME_PROPERTY_SYMBOL_ID.GRADIENTCOLOR4;
pub const TMT_GRADIENTCOLOR5 = THEME_PROPERTY_SYMBOL_ID.GRADIENTCOLOR5;
pub const TMT_SHADOWCOLOR = THEME_PROPERTY_SYMBOL_ID.SHADOWCOLOR;
pub const TMT_GLOWCOLOR = THEME_PROPERTY_SYMBOL_ID.GLOWCOLOR;
pub const TMT_TEXTBORDERCOLOR = THEME_PROPERTY_SYMBOL_ID.TEXTBORDERCOLOR;
pub const TMT_TEXTSHADOWCOLOR = THEME_PROPERTY_SYMBOL_ID.TEXTSHADOWCOLOR;
pub const TMT_GLYPHTEXTCOLOR = THEME_PROPERTY_SYMBOL_ID.GLYPHTEXTCOLOR;
pub const TMT_GLYPHTRANSPARENTCOLOR = THEME_PROPERTY_SYMBOL_ID.GLYPHTRANSPARENTCOLOR;
pub const TMT_FILLCOLORHINT = THEME_PROPERTY_SYMBOL_ID.FILLCOLORHINT;
pub const TMT_BORDERCOLORHINT = THEME_PROPERTY_SYMBOL_ID.BORDERCOLORHINT;
pub const TMT_ACCENTCOLORHINT = THEME_PROPERTY_SYMBOL_ID.ACCENTCOLORHINT;
pub const TMT_TEXTCOLORHINT = THEME_PROPERTY_SYMBOL_ID.TEXTCOLORHINT;
pub const TMT_HEADING1TEXTCOLOR = THEME_PROPERTY_SYMBOL_ID.HEADING1TEXTCOLOR;
pub const TMT_HEADING2TEXTCOLOR = THEME_PROPERTY_SYMBOL_ID.HEADING2TEXTCOLOR;
pub const TMT_BODYTEXTCOLOR = THEME_PROPERTY_SYMBOL_ID.BODYTEXTCOLOR;
pub const TMT_BGTYPE = THEME_PROPERTY_SYMBOL_ID.BGTYPE;
pub const TMT_BORDERTYPE = THEME_PROPERTY_SYMBOL_ID.BORDERTYPE;
pub const TMT_FILLTYPE = THEME_PROPERTY_SYMBOL_ID.FILLTYPE;
pub const TMT_SIZINGTYPE = THEME_PROPERTY_SYMBOL_ID.SIZINGTYPE;
pub const TMT_HALIGN = THEME_PROPERTY_SYMBOL_ID.HALIGN;
pub const TMT_CONTENTALIGNMENT = THEME_PROPERTY_SYMBOL_ID.CONTENTALIGNMENT;
pub const TMT_VALIGN = THEME_PROPERTY_SYMBOL_ID.VALIGN;
pub const TMT_OFFSETTYPE = THEME_PROPERTY_SYMBOL_ID.OFFSETTYPE;
pub const TMT_ICONEFFECT = THEME_PROPERTY_SYMBOL_ID.ICONEFFECT;
pub const TMT_TEXTSHADOWTYPE = THEME_PROPERTY_SYMBOL_ID.TEXTSHADOWTYPE;
pub const TMT_IMAGELAYOUT = THEME_PROPERTY_SYMBOL_ID.IMAGELAYOUT;
pub const TMT_GLYPHTYPE = THEME_PROPERTY_SYMBOL_ID.GLYPHTYPE;
pub const TMT_IMAGESELECTTYPE = THEME_PROPERTY_SYMBOL_ID.IMAGESELECTTYPE;
pub const TMT_GLYPHFONTSIZINGTYPE = THEME_PROPERTY_SYMBOL_ID.GLYPHFONTSIZINGTYPE;
pub const TMT_TRUESIZESCALINGTYPE = THEME_PROPERTY_SYMBOL_ID.TRUESIZESCALINGTYPE;
pub const TMT_USERPICTURE = THEME_PROPERTY_SYMBOL_ID.USERPICTURE;
pub const TMT_DEFAULTPANESIZE = THEME_PROPERTY_SYMBOL_ID.DEFAULTPANESIZE;
pub const TMT_BLENDCOLOR = THEME_PROPERTY_SYMBOL_ID.BLENDCOLOR;
pub const TMT_CUSTOMSPLITRECT = THEME_PROPERTY_SYMBOL_ID.CUSTOMSPLITRECT;
pub const TMT_ANIMATIONBUTTONRECT = THEME_PROPERTY_SYMBOL_ID.ANIMATIONBUTTONRECT;
pub const TMT_ANIMATIONDURATION = THEME_PROPERTY_SYMBOL_ID.ANIMATIONDURATION;
pub const TMT_TRANSITIONDURATIONS = THEME_PROPERTY_SYMBOL_ID.TRANSITIONDURATIONS;
pub const TMT_SCALEDBACKGROUND = THEME_PROPERTY_SYMBOL_ID.SCALEDBACKGROUND;
pub const TMT_ATLASIMAGE = THEME_PROPERTY_SYMBOL_ID.ATLASIMAGE;
pub const TMT_ATLASINPUTIMAGE = THEME_PROPERTY_SYMBOL_ID.ATLASINPUTIMAGE;
pub const TMT_ATLASRECT = THEME_PROPERTY_SYMBOL_ID.ATLASRECT;
pub const TOUCH_FEEDBACK_MODE = enum(u32) {
DEFAULT = 1,
INDIRECT = 2,
NONE = 3,
};
pub const TOUCH_FEEDBACK_DEFAULT = TOUCH_FEEDBACK_MODE.DEFAULT;
pub const TOUCH_FEEDBACK_INDIRECT = TOUCH_FEEDBACK_MODE.INDIRECT;
pub const TOUCH_FEEDBACK_NONE = TOUCH_FEEDBACK_MODE.NONE;
pub const OBJECT_IDENTIFIER = enum(i32) {
WINDOW = 0,
SYSMENU = -1,
TITLEBAR = -2,
MENU = -3,
CLIENT = -4,
VSCROLL = -5,
HSCROLL = -6,
SIZEGRIP = -7,
CARET = -8,
CURSOR = -9,
ALERT = -10,
SOUND = -11,
QUERYCLASSNAMEIDX = -12,
NATIVEOM = -16,
};
pub const OBJID_WINDOW = OBJECT_IDENTIFIER.WINDOW;
pub const OBJID_SYSMENU = OBJECT_IDENTIFIER.SYSMENU;
pub const OBJID_TITLEBAR = OBJECT_IDENTIFIER.TITLEBAR;
pub const OBJID_MENU = OBJECT_IDENTIFIER.MENU;
pub const OBJID_CLIENT = OBJECT_IDENTIFIER.CLIENT;
pub const OBJID_VSCROLL = OBJECT_IDENTIFIER.VSCROLL;
pub const OBJID_HSCROLL = OBJECT_IDENTIFIER.HSCROLL;
pub const OBJID_SIZEGRIP = OBJECT_IDENTIFIER.SIZEGRIP;
pub const OBJID_CARET = OBJECT_IDENTIFIER.CARET;
pub const OBJID_CURSOR = OBJECT_IDENTIFIER.CURSOR;
pub const OBJID_ALERT = OBJECT_IDENTIFIER.ALERT;
pub const OBJID_SOUND = OBJECT_IDENTIFIER.SOUND;
pub const OBJID_QUERYCLASSNAMEIDX = OBJECT_IDENTIFIER.QUERYCLASSNAMEIDX;
pub const OBJID_NATIVEOM = OBJECT_IDENTIFIER.NATIVEOM;
pub const CFM_MASK = enum(u32) {
SUBSCRIPT = 196608,
EFFECTS = 1073741887,
ALL = 4160749631,
BOLD = 1,
CHARSET = 134217728,
COLOR = 1073741824,
FACE = 536870912,
ITALIC = 2,
OFFSET = 268435456,
PROTECTED = 16,
SIZE = 2147483648,
STRIKEOUT = 8,
UNDERLINE = 4,
LINK = 32,
SMALLCAPS = 64,
ALLCAPS = 128,
HIDDEN = 256,
OUTLINE = 512,
SHADOW = 1024,
EMBOSS = 2048,
IMPRINT = 4096,
DISABLED = 8192,
REVISED = 16384,
REVAUTHOR = 32768,
ANIMATION = 262144,
STYLE = 524288,
KERNING = 1048576,
SPACING = 2097152,
WEIGHT = 4194304,
UNDERLINETYPE = 8388608,
COOKIE = 16777216,
LCID = 33554432,
BACKCOLOR = 67108864,
// SUPERSCRIPT = 196608, this enum value conflicts with SUBSCRIPT
EFFECTS2 = 1141080063,
ALL2 = 4294967295,
// FONTBOUND = 1048576, this enum value conflicts with KERNING
// LINKPROTECTED = 8388608, this enum value conflicts with UNDERLINETYPE
// EXTENDED = 33554432, this enum value conflicts with LCID
// MATHNOBUILDUP = 134217728, this enum value conflicts with CHARSET
// MATH = 268435456, this enum value conflicts with OFFSET
// MATHORDINARY = 536870912, this enum value conflicts with FACE
ALLEFFECTS = 2115207167,
_,
pub fn initFlags(o: struct {
SUBSCRIPT: u1 = 0,
EFFECTS: u1 = 0,
ALL: u1 = 0,
BOLD: u1 = 0,
CHARSET: u1 = 0,
COLOR: u1 = 0,
FACE: u1 = 0,
ITALIC: u1 = 0,
OFFSET: u1 = 0,
PROTECTED: u1 = 0,
SIZE: u1 = 0,
STRIKEOUT: u1 = 0,
UNDERLINE: u1 = 0,
LINK: u1 = 0,
SMALLCAPS: u1 = 0,
ALLCAPS: u1 = 0,
HIDDEN: u1 = 0,
OUTLINE: u1 = 0,
SHADOW: u1 = 0,
EMBOSS: u1 = 0,
IMPRINT: u1 = 0,
DISABLED: u1 = 0,
REVISED: u1 = 0,
REVAUTHOR: u1 = 0,
ANIMATION: u1 = 0,
STYLE: u1 = 0,
KERNING: u1 = 0,
SPACING: u1 = 0,
WEIGHT: u1 = 0,
UNDERLINETYPE: u1 = 0,
COOKIE: u1 = 0,
LCID: u1 = 0,
BACKCOLOR: u1 = 0,
EFFECTS2: u1 = 0,
ALL2: u1 = 0,
ALLEFFECTS: u1 = 0,
}) CFM_MASK {
return @intToEnum(CFM_MASK,
(if (o.SUBSCRIPT == 1) @enumToInt(CFM_MASK.SUBSCRIPT) else 0)
| (if (o.EFFECTS == 1) @enumToInt(CFM_MASK.EFFECTS) else 0)
| (if (o.ALL == 1) @enumToInt(CFM_MASK.ALL) else 0)
| (if (o.BOLD == 1) @enumToInt(CFM_MASK.BOLD) else 0)
| (if (o.CHARSET == 1) @enumToInt(CFM_MASK.CHARSET) else 0)
| (if (o.COLOR == 1) @enumToInt(CFM_MASK.COLOR) else 0)
| (if (o.FACE == 1) @enumToInt(CFM_MASK.FACE) else 0)
| (if (o.ITALIC == 1) @enumToInt(CFM_MASK.ITALIC) else 0)
| (if (o.OFFSET == 1) @enumToInt(CFM_MASK.OFFSET) else 0)
| (if (o.PROTECTED == 1) @enumToInt(CFM_MASK.PROTECTED) else 0)
| (if (o.SIZE == 1) @enumToInt(CFM_MASK.SIZE) else 0)
| (if (o.STRIKEOUT == 1) @enumToInt(CFM_MASK.STRIKEOUT) else 0)
| (if (o.UNDERLINE == 1) @enumToInt(CFM_MASK.UNDERLINE) else 0)
| (if (o.LINK == 1) @enumToInt(CFM_MASK.LINK) else 0)
| (if (o.SMALLCAPS == 1) @enumToInt(CFM_MASK.SMALLCAPS) else 0)
| (if (o.ALLCAPS == 1) @enumToInt(CFM_MASK.ALLCAPS) else 0)
| (if (o.HIDDEN == 1) @enumToInt(CFM_MASK.HIDDEN) else 0)
| (if (o.OUTLINE == 1) @enumToInt(CFM_MASK.OUTLINE) else 0)
| (if (o.SHADOW == 1) @enumToInt(CFM_MASK.SHADOW) else 0)
| (if (o.EMBOSS == 1) @enumToInt(CFM_MASK.EMBOSS) else 0)
| (if (o.IMPRINT == 1) @enumToInt(CFM_MASK.IMPRINT) else 0)
| (if (o.DISABLED == 1) @enumToInt(CFM_MASK.DISABLED) else 0)
| (if (o.REVISED == 1) @enumToInt(CFM_MASK.REVISED) else 0)
| (if (o.REVAUTHOR == 1) @enumToInt(CFM_MASK.REVAUTHOR) else 0)
| (if (o.ANIMATION == 1) @enumToInt(CFM_MASK.ANIMATION) else 0)
| (if (o.STYLE == 1) @enumToInt(CFM_MASK.STYLE) else 0)
| (if (o.KERNING == 1) @enumToInt(CFM_MASK.KERNING) else 0)
| (if (o.SPACING == 1) @enumToInt(CFM_MASK.SPACING) else 0)
| (if (o.WEIGHT == 1) @enumToInt(CFM_MASK.WEIGHT) else 0)
| (if (o.UNDERLINETYPE == 1) @enumToInt(CFM_MASK.UNDERLINETYPE) else 0)
| (if (o.COOKIE == 1) @enumToInt(CFM_MASK.COOKIE) else 0)
| (if (o.LCID == 1) @enumToInt(CFM_MASK.LCID) else 0)
| (if (o.BACKCOLOR == 1) @enumToInt(CFM_MASK.BACKCOLOR) else 0)
| (if (o.EFFECTS2 == 1) @enumToInt(CFM_MASK.EFFECTS2) else 0)
| (if (o.ALL2 == 1) @enumToInt(CFM_MASK.ALL2) else 0)
| (if (o.ALLEFFECTS == 1) @enumToInt(CFM_MASK.ALLEFFECTS) else 0)
);
}
};
pub const CFM_SUBSCRIPT = CFM_MASK.SUBSCRIPT;
pub const CFM_EFFECTS = CFM_MASK.EFFECTS;
pub const CFM_ALL = CFM_MASK.ALL;
pub const CFM_BOLD = CFM_MASK.BOLD;
pub const CFM_CHARSET = CFM_MASK.CHARSET;
pub const CFM_COLOR = CFM_MASK.COLOR;
pub const CFM_FACE = CFM_MASK.FACE;
pub const CFM_ITALIC = CFM_MASK.ITALIC;
pub const CFM_OFFSET = CFM_MASK.OFFSET;
pub const CFM_PROTECTED = CFM_MASK.PROTECTED;
pub const CFM_SIZE = CFM_MASK.SIZE;
pub const CFM_STRIKEOUT = CFM_MASK.STRIKEOUT;
pub const CFM_UNDERLINE = CFM_MASK.UNDERLINE;
pub const CFM_LINK = CFM_MASK.LINK;
pub const CFM_SMALLCAPS = CFM_MASK.SMALLCAPS;
pub const CFM_ALLCAPS = CFM_MASK.ALLCAPS;
pub const CFM_HIDDEN = CFM_MASK.HIDDEN;
pub const CFM_OUTLINE = CFM_MASK.OUTLINE;
pub const CFM_SHADOW = CFM_MASK.SHADOW;
pub const CFM_EMBOSS = CFM_MASK.EMBOSS;
pub const CFM_IMPRINT = CFM_MASK.IMPRINT;
pub const CFM_DISABLED = CFM_MASK.DISABLED;
pub const CFM_REVISED = CFM_MASK.REVISED;
pub const CFM_REVAUTHOR = CFM_MASK.REVAUTHOR;
pub const CFM_ANIMATION = CFM_MASK.ANIMATION;
pub const CFM_STYLE = CFM_MASK.STYLE;
pub const CFM_KERNING = CFM_MASK.KERNING;
pub const CFM_SPACING = CFM_MASK.SPACING;
pub const CFM_WEIGHT = CFM_MASK.WEIGHT;
pub const CFM_UNDERLINETYPE = CFM_MASK.UNDERLINETYPE;
pub const CFM_COOKIE = CFM_MASK.COOKIE;
pub const CFM_LCID = CFM_MASK.LCID;
pub const CFM_BACKCOLOR = CFM_MASK.BACKCOLOR;
pub const CFM_SUPERSCRIPT = CFM_MASK.SUBSCRIPT;
pub const CFM_EFFECTS2 = CFM_MASK.EFFECTS2;
pub const CFM_ALL2 = CFM_MASK.ALL2;
pub const CFM_FONTBOUND = CFM_MASK.KERNING;
pub const CFM_LINKPROTECTED = CFM_MASK.UNDERLINETYPE;
pub const CFM_EXTENDED = CFM_MASK.LCID;
pub const CFM_MATHNOBUILDUP = CFM_MASK.CHARSET;
pub const CFM_MATH = CFM_MASK.OFFSET;
pub const CFM_MATHORDINARY = CFM_MASK.FACE;
pub const CFM_ALLEFFECTS = CFM_MASK.ALLEFFECTS;
pub const CFE_EFFECTS = enum(u32) {
ALLCAPS = 128,
AUTOBACKCOLOR = 67108864,
DISABLED = 8192,
EMBOSS = 2048,
HIDDEN = 256,
IMPRINT = 4096,
OUTLINE = 512,
REVISED = 16384,
SHADOW = 1024,
SMALLCAPS = 64,
AUTOCOLOR = 1073741824,
BOLD = 1,
ITALIC = 2,
STRIKEOUT = 8,
UNDERLINE = 4,
PROTECTED = 16,
LINK = 32,
SUBSCRIPT = 65536,
SUPERSCRIPT = 131072,
FONTBOUND = 1048576,
LINKPROTECTED = 8388608,
EXTENDED = 33554432,
MATHNOBUILDUP = 134217728,
MATH = 268435456,
MATHORDINARY = 536870912,
_,
pub fn initFlags(o: struct {
ALLCAPS: u1 = 0,
AUTOBACKCOLOR: u1 = 0,
DISABLED: u1 = 0,
EMBOSS: u1 = 0,
HIDDEN: u1 = 0,
IMPRINT: u1 = 0,
OUTLINE: u1 = 0,
REVISED: u1 = 0,
SHADOW: u1 = 0,
SMALLCAPS: u1 = 0,
AUTOCOLOR: u1 = 0,
BOLD: u1 = 0,
ITALIC: u1 = 0,
STRIKEOUT: u1 = 0,
UNDERLINE: u1 = 0,
PROTECTED: u1 = 0,
LINK: u1 = 0,
SUBSCRIPT: u1 = 0,
SUPERSCRIPT: u1 = 0,
FONTBOUND: u1 = 0,
LINKPROTECTED: u1 = 0,
EXTENDED: u1 = 0,
MATHNOBUILDUP: u1 = 0,
MATH: u1 = 0,
MATHORDINARY: u1 = 0,
}) CFE_EFFECTS {
return @intToEnum(CFE_EFFECTS,
(if (o.ALLCAPS == 1) @enumToInt(CFE_EFFECTS.ALLCAPS) else 0)
| (if (o.AUTOBACKCOLOR == 1) @enumToInt(CFE_EFFECTS.AUTOBACKCOLOR) else 0)
| (if (o.DISABLED == 1) @enumToInt(CFE_EFFECTS.DISABLED) else 0)
| (if (o.EMBOSS == 1) @enumToInt(CFE_EFFECTS.EMBOSS) else 0)
| (if (o.HIDDEN == 1) @enumToInt(CFE_EFFECTS.HIDDEN) else 0)
| (if (o.IMPRINT == 1) @enumToInt(CFE_EFFECTS.IMPRINT) else 0)
| (if (o.OUTLINE == 1) @enumToInt(CFE_EFFECTS.OUTLINE) else 0)
| (if (o.REVISED == 1) @enumToInt(CFE_EFFECTS.REVISED) else 0)
| (if (o.SHADOW == 1) @enumToInt(CFE_EFFECTS.SHADOW) else 0)
| (if (o.SMALLCAPS == 1) @enumToInt(CFE_EFFECTS.SMALLCAPS) else 0)
| (if (o.AUTOCOLOR == 1) @enumToInt(CFE_EFFECTS.AUTOCOLOR) else 0)
| (if (o.BOLD == 1) @enumToInt(CFE_EFFECTS.BOLD) else 0)
| (if (o.ITALIC == 1) @enumToInt(CFE_EFFECTS.ITALIC) else 0)
| (if (o.STRIKEOUT == 1) @enumToInt(CFE_EFFECTS.STRIKEOUT) else 0)
| (if (o.UNDERLINE == 1) @enumToInt(CFE_EFFECTS.UNDERLINE) else 0)
| (if (o.PROTECTED == 1) @enumToInt(CFE_EFFECTS.PROTECTED) else 0)
| (if (o.LINK == 1) @enumToInt(CFE_EFFECTS.LINK) else 0)
| (if (o.SUBSCRIPT == 1) @enumToInt(CFE_EFFECTS.SUBSCRIPT) else 0)
| (if (o.SUPERSCRIPT == 1) @enumToInt(CFE_EFFECTS.SUPERSCRIPT) else 0)
| (if (o.FONTBOUND == 1) @enumToInt(CFE_EFFECTS.FONTBOUND) else 0)
| (if (o.LINKPROTECTED == 1) @enumToInt(CFE_EFFECTS.LINKPROTECTED) else 0)
| (if (o.EXTENDED == 1) @enumToInt(CFE_EFFECTS.EXTENDED) else 0)
| (if (o.MATHNOBUILDUP == 1) @enumToInt(CFE_EFFECTS.MATHNOBUILDUP) else 0)
| (if (o.MATH == 1) @enumToInt(CFE_EFFECTS.MATH) else 0)
| (if (o.MATHORDINARY == 1) @enumToInt(CFE_EFFECTS.MATHORDINARY) else 0)
);
}
};
// TODO: enum 'CFE_EFFECTS' has known issues with its value aliases
pub const PARAFORMAT_MASK = enum(u32) {
ALIGNMENT = 8,
NUMBERING = 32,
OFFSET = 4,
OFFSETINDENT = 2147483648,
RIGHTINDENT = 2,
RTLPARA = 65536,
STARTINDENT = 1,
TABSTOPS = 16,
_,
pub fn initFlags(o: struct {
ALIGNMENT: u1 = 0,
NUMBERING: u1 = 0,
OFFSET: u1 = 0,
OFFSETINDENT: u1 = 0,
RIGHTINDENT: u1 = 0,
RTLPARA: u1 = 0,
STARTINDENT: u1 = 0,
TABSTOPS: u1 = 0,
}) PARAFORMAT_MASK {
return @intToEnum(PARAFORMAT_MASK,
(if (o.ALIGNMENT == 1) @enumToInt(PARAFORMAT_MASK.ALIGNMENT) else 0)
| (if (o.NUMBERING == 1) @enumToInt(PARAFORMAT_MASK.NUMBERING) else 0)
| (if (o.OFFSET == 1) @enumToInt(PARAFORMAT_MASK.OFFSET) else 0)
| (if (o.OFFSETINDENT == 1) @enumToInt(PARAFORMAT_MASK.OFFSETINDENT) else 0)
| (if (o.RIGHTINDENT == 1) @enumToInt(PARAFORMAT_MASK.RIGHTINDENT) else 0)
| (if (o.RTLPARA == 1) @enumToInt(PARAFORMAT_MASK.RTLPARA) else 0)
| (if (o.STARTINDENT == 1) @enumToInt(PARAFORMAT_MASK.STARTINDENT) else 0)
| (if (o.TABSTOPS == 1) @enumToInt(PARAFORMAT_MASK.TABSTOPS) else 0)
);
}
};
pub const PFM_ALIGNMENT = PARAFORMAT_MASK.ALIGNMENT;
pub const PFM_NUMBERING = PARAFORMAT_MASK.NUMBERING;
pub const PFM_OFFSET = PARAFORMAT_MASK.OFFSET;
pub const PFM_OFFSETINDENT = PARAFORMAT_MASK.OFFSETINDENT;
pub const PFM_RIGHTINDENT = PARAFORMAT_MASK.RIGHTINDENT;
pub const PFM_RTLPARA = PARAFORMAT_MASK.RTLPARA;
pub const PFM_STARTINDENT = PARAFORMAT_MASK.STARTINDENT;
pub const PFM_TABSTOPS = PARAFORMAT_MASK.TABSTOPS;
pub const DRAGLISTINFO_NOTIFICATION_FLAGS = enum(u32) {
BEGINDRAG = 1157,
CANCELDRAG = 1160,
DRAGGING = 1158,
DROPPED = 1159,
};
pub const DL_BEGINDRAG = DRAGLISTINFO_NOTIFICATION_FLAGS.BEGINDRAG;
pub const DL_CANCELDRAG = DRAGLISTINFO_NOTIFICATION_FLAGS.CANCELDRAG;
pub const DL_DRAGGING = DRAGLISTINFO_NOTIFICATION_FLAGS.DRAGGING;
pub const DL_DROPPED = DRAGLISTINFO_NOTIFICATION_FLAGS.DROPPED;
pub const TEXT_ALIGN_OPTIONS = enum(u32) {
TA_NOUPDATECP = 0,
TA_UPDATECP = 1,
// TA_LEFT = 0, this enum value conflicts with TA_NOUPDATECP
TA_RIGHT = 2,
TA_CENTER = 6,
// TA_TOP = 0, this enum value conflicts with TA_NOUPDATECP
TA_BOTTOM = 8,
TA_BASELINE = 24,
TA_RTLREADING = 256,
TA_MASK = 287,
// VTA_BASELINE = 24, this enum value conflicts with TA_BASELINE
// VTA_LEFT = 8, this enum value conflicts with TA_BOTTOM
// VTA_RIGHT = 0, this enum value conflicts with TA_NOUPDATECP
// VTA_CENTER = 6, this enum value conflicts with TA_CENTER
// VTA_BOTTOM = 2, this enum value conflicts with TA_RIGHT
// VTA_TOP = 0, this enum value conflicts with TA_NOUPDATECP
};
pub const TA_NOUPDATECP = TEXT_ALIGN_OPTIONS.TA_NOUPDATECP;
pub const TA_UPDATECP = TEXT_ALIGN_OPTIONS.TA_UPDATECP;
pub const TA_LEFT = TEXT_ALIGN_OPTIONS.TA_NOUPDATECP;
pub const TA_RIGHT = TEXT_ALIGN_OPTIONS.TA_RIGHT;
pub const TA_CENTER = TEXT_ALIGN_OPTIONS.TA_CENTER;
pub const TA_TOP = TEXT_ALIGN_OPTIONS.TA_NOUPDATECP;
pub const TA_BOTTOM = TEXT_ALIGN_OPTIONS.TA_BOTTOM;
pub const TA_BASELINE = TEXT_ALIGN_OPTIONS.TA_BASELINE;
pub const TA_RTLREADING = TEXT_ALIGN_OPTIONS.TA_RTLREADING;
pub const TA_MASK = TEXT_ALIGN_OPTIONS.TA_MASK;
pub const VTA_BASELINE = TEXT_ALIGN_OPTIONS.TA_BASELINE;
pub const VTA_LEFT = TEXT_ALIGN_OPTIONS.TA_BOTTOM;
pub const VTA_RIGHT = TEXT_ALIGN_OPTIONS.TA_NOUPDATECP;
pub const VTA_CENTER = TEXT_ALIGN_OPTIONS.TA_CENTER;
pub const VTA_BOTTOM = TEXT_ALIGN_OPTIONS.TA_RIGHT;
pub const VTA_TOP = TEXT_ALIGN_OPTIONS.TA_NOUPDATECP;
pub const SCROLLBAR_CONSTANTS = enum(u32) {
CTL = 2,
HORZ = 0,
VERT = 1,
BOTH = 3,
_,
pub fn initFlags(o: struct {
CTL: u1 = 0,
HORZ: u1 = 0,
VERT: u1 = 0,
BOTH: u1 = 0,
}) SCROLLBAR_CONSTANTS {
return @intToEnum(SCROLLBAR_CONSTANTS,
(if (o.CTL == 1) @enumToInt(SCROLLBAR_CONSTANTS.CTL) else 0)
| (if (o.HORZ == 1) @enumToInt(SCROLLBAR_CONSTANTS.HORZ) else 0)
| (if (o.VERT == 1) @enumToInt(SCROLLBAR_CONSTANTS.VERT) else 0)
| (if (o.BOTH == 1) @enumToInt(SCROLLBAR_CONSTANTS.BOTH) else 0)
);
}
};
pub const SB_CTL = SCROLLBAR_CONSTANTS.CTL;
pub const SB_HORZ = SCROLLBAR_CONSTANTS.HORZ;
pub const SB_VERT = SCROLLBAR_CONSTANTS.VERT;
pub const SB_BOTH = SCROLLBAR_CONSTANTS.BOTH;
pub const WORD_BREAK_ACTION = enum(u32) {
CLASSIFY = 3,
ISDELIMITER = 2,
LEFT = 0,
LEFTBREAK = 6,
MOVEWORDLEFT = 4,
MOVEWORDRIGHT = 5,
RIGHT = 1,
RIGHTBREAK = 7,
};
pub const WB_CLASSIFY = WORD_BREAK_ACTION.CLASSIFY;
pub const WB_ISDELIMITER = WORD_BREAK_ACTION.ISDELIMITER;
pub const WB_LEFT = WORD_BREAK_ACTION.LEFT;
pub const WB_LEFTBREAK = WORD_BREAK_ACTION.LEFTBREAK;
pub const WB_MOVEWORDLEFT = WORD_BREAK_ACTION.MOVEWORDLEFT;
pub const WB_MOVEWORDRIGHT = WORD_BREAK_ACTION.MOVEWORDRIGHT;
pub const WB_RIGHT = WORD_BREAK_ACTION.RIGHT;
pub const WB_RIGHTBREAK = WORD_BREAK_ACTION.RIGHTBREAK;
pub const DPAMM_MESSAGE = enum(u32) {
MERGE = 1,
DELETE = 2,
INSERT = 3,
};
pub const DPAMM_MERGE = DPAMM_MESSAGE.MERGE;
pub const DPAMM_DELETE = DPAMM_MESSAGE.DELETE;
pub const DPAMM_INSERT = DPAMM_MESSAGE.INSERT;
pub const IMAGE_FLAGS = enum(u32) {
CREATEDIBSECTION = 8192,
DEFAULTCOLOR = 0,
DEFAULTSIZE = 64,
LOADFROMFILE = 16,
LOADMAP3DCOLORS = 4096,
LOADTRANSPARENT = 32,
MONOCHROME = 1,
SHARED = 32768,
VGACOLOR = 128,
COPYDELETEORG = 8,
COPYFROMRESOURCE = 16384,
COPYRETURNORG = 4,
_,
pub fn initFlags(o: struct {
CREATEDIBSECTION: u1 = 0,
DEFAULTCOLOR: u1 = 0,
DEFAULTSIZE: u1 = 0,
LOADFROMFILE: u1 = 0,
LOADMAP3DCOLORS: u1 = 0,
LOADTRANSPARENT: u1 = 0,
MONOCHROME: u1 = 0,
SHARED: u1 = 0,
VGACOLOR: u1 = 0,
COPYDELETEORG: u1 = 0,
COPYFROMRESOURCE: u1 = 0,
COPYRETURNORG: u1 = 0,
}) IMAGE_FLAGS {
return @intToEnum(IMAGE_FLAGS,
(if (o.CREATEDIBSECTION == 1) @enumToInt(IMAGE_FLAGS.CREATEDIBSECTION) else 0)
| (if (o.DEFAULTCOLOR == 1) @enumToInt(IMAGE_FLAGS.DEFAULTCOLOR) else 0)
| (if (o.DEFAULTSIZE == 1) @enumToInt(IMAGE_FLAGS.DEFAULTSIZE) else 0)
| (if (o.LOADFROMFILE == 1) @enumToInt(IMAGE_FLAGS.LOADFROMFILE) else 0)
| (if (o.LOADMAP3DCOLORS == 1) @enumToInt(IMAGE_FLAGS.LOADMAP3DCOLORS) else 0)
| (if (o.LOADTRANSPARENT == 1) @enumToInt(IMAGE_FLAGS.LOADTRANSPARENT) else 0)
| (if (o.MONOCHROME == 1) @enumToInt(IMAGE_FLAGS.MONOCHROME) else 0)
| (if (o.SHARED == 1) @enumToInt(IMAGE_FLAGS.SHARED) else 0)
| (if (o.VGACOLOR == 1) @enumToInt(IMAGE_FLAGS.VGACOLOR) else 0)
| (if (o.COPYDELETEORG == 1) @enumToInt(IMAGE_FLAGS.COPYDELETEORG) else 0)
| (if (o.COPYFROMRESOURCE == 1) @enumToInt(IMAGE_FLAGS.COPYFROMRESOURCE) else 0)
| (if (o.COPYRETURNORG == 1) @enumToInt(IMAGE_FLAGS.COPYRETURNORG) else 0)
);
}
};
pub const LR_CREATEDIBSECTION = IMAGE_FLAGS.CREATEDIBSECTION;
pub const LR_DEFAULTCOLOR = IMAGE_FLAGS.DEFAULTCOLOR;
pub const LR_DEFAULTSIZE = IMAGE_FLAGS.DEFAULTSIZE;
pub const LR_LOADFROMFILE = IMAGE_FLAGS.LOADFROMFILE;
pub const LR_LOADMAP3DCOLORS = IMAGE_FLAGS.LOADMAP3DCOLORS;
pub const LR_LOADTRANSPARENT = IMAGE_FLAGS.LOADTRANSPARENT;
pub const LR_MONOCHROME = IMAGE_FLAGS.MONOCHROME;
pub const LR_SHARED = IMAGE_FLAGS.SHARED;
pub const LR_VGACOLOR = IMAGE_FLAGS.VGACOLOR;
pub const LR_COPYDELETEORG = IMAGE_FLAGS.COPYDELETEORG;
pub const LR_COPYFROMRESOURCE = IMAGE_FLAGS.COPYFROMRESOURCE;
pub const LR_COPYRETURNORG = IMAGE_FLAGS.COPYRETURNORG;
pub const DLG_DIR_LIST_FILE_TYPE = enum(u32) {
ARCHIVE = 32,
DIRECTORY = 16,
DRIVES = 16384,
EXCLUSIVE = 32768,
HIDDEN = 2,
READONLY = 1,
READWRITE = 0,
SYSTEM = 4,
POSTMSGS = 8192,
_,
pub fn initFlags(o: struct {
ARCHIVE: u1 = 0,
DIRECTORY: u1 = 0,
DRIVES: u1 = 0,
EXCLUSIVE: u1 = 0,
HIDDEN: u1 = 0,
READONLY: u1 = 0,
READWRITE: u1 = 0,
SYSTEM: u1 = 0,
POSTMSGS: u1 = 0,
}) DLG_DIR_LIST_FILE_TYPE {
return @intToEnum(DLG_DIR_LIST_FILE_TYPE,
(if (o.ARCHIVE == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.ARCHIVE) else 0)
| (if (o.DIRECTORY == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.DIRECTORY) else 0)
| (if (o.DRIVES == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.DRIVES) else 0)
| (if (o.EXCLUSIVE == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.EXCLUSIVE) else 0)
| (if (o.HIDDEN == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.HIDDEN) else 0)
| (if (o.READONLY == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.READONLY) else 0)
| (if (o.READWRITE == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.READWRITE) else 0)
| (if (o.SYSTEM == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.SYSTEM) else 0)
| (if (o.POSTMSGS == 1) @enumToInt(DLG_DIR_LIST_FILE_TYPE.POSTMSGS) else 0)
);
}
};
pub const DDL_ARCHIVE = DLG_DIR_LIST_FILE_TYPE.ARCHIVE;
pub const DDL_DIRECTORY = DLG_DIR_LIST_FILE_TYPE.DIRECTORY;
pub const DDL_DRIVES = DLG_DIR_LIST_FILE_TYPE.DRIVES;
pub const DDL_EXCLUSIVE = DLG_DIR_LIST_FILE_TYPE.EXCLUSIVE;
pub const DDL_HIDDEN = DLG_DIR_LIST_FILE_TYPE.HIDDEN;
pub const DDL_READONLY = DLG_DIR_LIST_FILE_TYPE.READONLY;
pub const DDL_READWRITE = DLG_DIR_LIST_FILE_TYPE.READWRITE;
pub const DDL_SYSTEM = DLG_DIR_LIST_FILE_TYPE.SYSTEM;
pub const DDL_POSTMSGS = DLG_DIR_LIST_FILE_TYPE.POSTMSGS;
pub const OPEN_THEME_DATA_FLAGS = enum(u32) {
FORCE_RECT_SIZING = 1,
NONCLIENT = 2,
_,
pub fn initFlags(o: struct {
FORCE_RECT_SIZING: u1 = 0,
NONCLIENT: u1 = 0,
}) OPEN_THEME_DATA_FLAGS {
return @intToEnum(OPEN_THEME_DATA_FLAGS,
(if (o.FORCE_RECT_SIZING == 1) @enumToInt(OPEN_THEME_DATA_FLAGS.FORCE_RECT_SIZING) else 0)
| (if (o.NONCLIENT == 1) @enumToInt(OPEN_THEME_DATA_FLAGS.NONCLIENT) else 0)
);
}
};
pub const OTD_FORCE_RECT_SIZING = OPEN_THEME_DATA_FLAGS.FORCE_RECT_SIZING;
pub const OTD_NONCLIENT = OPEN_THEME_DATA_FLAGS.NONCLIENT;
pub const GET_THEME_BITMAP_FLAGS = enum(u32) {
DIRECT = 1,
COPY = 2,
VALIDBITS = 3,
};
pub const GBF_DIRECT = GET_THEME_BITMAP_FLAGS.DIRECT;
pub const GBF_COPY = GET_THEME_BITMAP_FLAGS.COPY;
pub const GBF_VALIDBITS = GET_THEME_BITMAP_FLAGS.VALIDBITS;
pub const ENABLE_SCROLL_BAR_ARROWS = enum(u32) {
DISABLE_BOTH = 3,
DISABLE_DOWN = 2,
DISABLE_LEFT = 1,
// DISABLE_LTUP = 1, this enum value conflicts with DISABLE_LEFT
// DISABLE_RIGHT = 2, this enum value conflicts with DISABLE_DOWN
// DISABLE_RTDN = 2, this enum value conflicts with DISABLE_DOWN
// DISABLE_UP = 1, this enum value conflicts with DISABLE_LEFT
ENABLE_BOTH = 0,
};
pub const ESB_DISABLE_BOTH = ENABLE_SCROLL_BAR_ARROWS.DISABLE_BOTH;
pub const ESB_DISABLE_DOWN = ENABLE_SCROLL_BAR_ARROWS.DISABLE_DOWN;
pub const ESB_DISABLE_LEFT = ENABLE_SCROLL_BAR_ARROWS.DISABLE_LEFT;
pub const ESB_DISABLE_LTUP = ENABLE_SCROLL_BAR_ARROWS.DISABLE_LEFT;
pub const ESB_DISABLE_RIGHT = ENABLE_SCROLL_BAR_ARROWS.DISABLE_DOWN;
pub const ESB_DISABLE_RTDN = ENABLE_SCROLL_BAR_ARROWS.DISABLE_DOWN;
pub const ESB_DISABLE_UP = ENABLE_SCROLL_BAR_ARROWS.DISABLE_LEFT;
pub const ESB_ENABLE_BOTH = ENABLE_SCROLL_BAR_ARROWS.ENABLE_BOTH;
pub const IMAGE_LIST_DRAW_STYLE = enum(u32) {
BLEND = 4,
// BLEND50 = 4, this enum value conflicts with BLEND
FOCUS = 2,
MASK = 16,
NORMAL = 0,
// SELECTED = 4, this enum value conflicts with BLEND
_,
pub fn initFlags(o: struct {
BLEND: u1 = 0,
FOCUS: u1 = 0,
MASK: u1 = 0,
NORMAL: u1 = 0,
}) IMAGE_LIST_DRAW_STYLE {
return @intToEnum(IMAGE_LIST_DRAW_STYLE,
(if (o.BLEND == 1) @enumToInt(IMAGE_LIST_DRAW_STYLE.BLEND) else 0)
| (if (o.FOCUS == 1) @enumToInt(IMAGE_LIST_DRAW_STYLE.FOCUS) else 0)
| (if (o.MASK == 1) @enumToInt(IMAGE_LIST_DRAW_STYLE.MASK) else 0)
| (if (o.NORMAL == 1) @enumToInt(IMAGE_LIST_DRAW_STYLE.NORMAL) else 0)
);
}
};
pub const ILD_BLEND = IMAGE_LIST_DRAW_STYLE.BLEND;
pub const ILD_BLEND50 = IMAGE_LIST_DRAW_STYLE.BLEND;
pub const ILD_FOCUS = IMAGE_LIST_DRAW_STYLE.FOCUS;
pub const ILD_MASK = IMAGE_LIST_DRAW_STYLE.MASK;
pub const ILD_NORMAL = IMAGE_LIST_DRAW_STYLE.NORMAL;
pub const ILD_SELECTED = IMAGE_LIST_DRAW_STYLE.BLEND;
pub const WSB_PROP = enum(i32) {
CXHSCROLL = 2,
CXHTHUMB = 16,
CXVSCROLL = 8,
CYHSCROLL = 4,
CYVSCROLL = 1,
CYVTHUMB = 32,
HBKGCOLOR = 128,
HSTYLE = 512,
PALETTE = 2048,
VBKGCOLOR = 64,
VSTYLE = 256,
WINSTYLE = 1024,
};
pub const WSB_PROP_CXHSCROLL = WSB_PROP.CXHSCROLL;
pub const WSB_PROP_CXHTHUMB = WSB_PROP.CXHTHUMB;
pub const WSB_PROP_CXVSCROLL = WSB_PROP.CXVSCROLL;
pub const WSB_PROP_CYHSCROLL = WSB_PROP.CYHSCROLL;
pub const WSB_PROP_CYVSCROLL = WSB_PROP.CYVSCROLL;
pub const WSB_PROP_CYVTHUMB = WSB_PROP.CYVTHUMB;
pub const WSB_PROP_HBKGCOLOR = WSB_PROP.HBKGCOLOR;
pub const WSB_PROP_HSTYLE = WSB_PROP.HSTYLE;
pub const WSB_PROP_PALETTE = WSB_PROP.PALETTE;
pub const WSB_PROP_VBKGCOLOR = WSB_PROP.VBKGCOLOR;
pub const WSB_PROP_VSTYLE = WSB_PROP.VSTYLE;
pub const WSB_PROP_WINSTYLE = WSB_PROP.WINSTYLE;
pub const PSPCB_MESSAGE = enum(u32) {
ADDREF = 0,
CREATE = 2,
RELEASE = 1,
SI_INITDIALOG = 1025,
};
pub const PSPCB_ADDREF = PSPCB_MESSAGE.ADDREF;
pub const PSPCB_CREATE = PSPCB_MESSAGE.CREATE;
pub const PSPCB_RELEASE = PSPCB_MESSAGE.RELEASE;
pub const PSPCB_SI_INITDIALOG = PSPCB_MESSAGE.SI_INITDIALOG;
pub const HEADER_CONTROL_NOTIFICATION_BUTTON = enum(u32) {
LEFT = 0,
RIGHT = 1,
MIDDLE = 2,
};
pub const HEADER_CONTROL_NOTIFICATION_BUTTON_LEFT = HEADER_CONTROL_NOTIFICATION_BUTTON.LEFT;
pub const HEADER_CONTROL_NOTIFICATION_BUTTON_RIGHT = HEADER_CONTROL_NOTIFICATION_BUTTON.RIGHT;
pub const HEADER_CONTROL_NOTIFICATION_BUTTON_MIDDLE = HEADER_CONTROL_NOTIFICATION_BUTTON.MIDDLE;
pub const IMAGE_LIST_COPY_FLAGS = enum(u32) {
MOVE = 0,
SWAP = 1,
};
pub const ILCF_MOVE = IMAGE_LIST_COPY_FLAGS.MOVE;
pub const ILCF_SWAP = IMAGE_LIST_COPY_FLAGS.SWAP;
pub const DLG_BUTTON_CHECK_STATE = enum(u32) {
CHECKED = 1,
INDETERMINATE = 2,
UNCHECKED = 0,
};
pub const BST_CHECKED = DLG_BUTTON_CHECK_STATE.CHECKED;
pub const BST_INDETERMINATE = DLG_BUTTON_CHECK_STATE.INDETERMINATE;
pub const BST_UNCHECKED = DLG_BUTTON_CHECK_STATE.UNCHECKED;
pub const DRAW_THEME_PARENT_BACKGROUND_FLAGS = enum(u32) {
WINDOWDC = 1,
USECTLCOLORSTATIC = 2,
USEERASEBKGND = 4,
_,
pub fn initFlags(o: struct {
WINDOWDC: u1 = 0,
USECTLCOLORSTATIC: u1 = 0,
USEERASEBKGND: u1 = 0,
}) DRAW_THEME_PARENT_BACKGROUND_FLAGS {
return @intToEnum(DRAW_THEME_PARENT_BACKGROUND_FLAGS,
(if (o.WINDOWDC == 1) @enumToInt(DRAW_THEME_PARENT_BACKGROUND_FLAGS.WINDOWDC) else 0)
| (if (o.USECTLCOLORSTATIC == 1) @enumToInt(DRAW_THEME_PARENT_BACKGROUND_FLAGS.USECTLCOLORSTATIC) else 0)
| (if (o.USEERASEBKGND == 1) @enumToInt(DRAW_THEME_PARENT_BACKGROUND_FLAGS.USEERASEBKGND) else 0)
);
}
};
pub const DTPB_WINDOWDC = DRAW_THEME_PARENT_BACKGROUND_FLAGS.WINDOWDC;
pub const DTPB_USECTLCOLORSTATIC = DRAW_THEME_PARENT_BACKGROUND_FLAGS.USECTLCOLORSTATIC;
pub const DTPB_USEERASEBKGND = DRAW_THEME_PARENT_BACKGROUND_FLAGS.USEERASEBKGND;
pub const RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE = enum(u16) {
SEL_EMPTY = 0,
SEL_TEXT = 1,
SEL_OBJECT = 2,
SEL_MULTICHAR = 4,
SEL_MULTIOBJECT = 8,
GCM_RIGHTMOUSEDROP = 32768,
_,
pub fn initFlags(o: struct {
SEL_EMPTY: u1 = 0,
SEL_TEXT: u1 = 0,
SEL_OBJECT: u1 = 0,
SEL_MULTICHAR: u1 = 0,
SEL_MULTIOBJECT: u1 = 0,
GCM_RIGHTMOUSEDROP: u1 = 0,
}) RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE {
return @intToEnum(RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE,
(if (o.SEL_EMPTY == 1) @enumToInt(RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_EMPTY) else 0)
| (if (o.SEL_TEXT == 1) @enumToInt(RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_TEXT) else 0)
| (if (o.SEL_OBJECT == 1) @enumToInt(RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_OBJECT) else 0)
| (if (o.SEL_MULTICHAR == 1) @enumToInt(RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_MULTICHAR) else 0)
| (if (o.SEL_MULTIOBJECT == 1) @enumToInt(RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_MULTIOBJECT) else 0)
| (if (o.GCM_RIGHTMOUSEDROP == 1) @enumToInt(RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.GCM_RIGHTMOUSEDROP) else 0)
);
}
};
pub const SEL_EMPTY = RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_EMPTY;
pub const SEL_TEXT = RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_TEXT;
pub const SEL_OBJECT = RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_OBJECT;
pub const SEL_MULTICHAR = RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_MULTICHAR;
pub const SEL_MULTIOBJECT = RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.SEL_MULTIOBJECT;
pub const GCM_RIGHTMOUSEDROP = RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE.GCM_RIGHTMOUSEDROP;
pub const IMAGE_LIST_ITEM_FLAGS = enum(u32) {
ALPHA = 1,
LOWQUALITY = 2,
};
pub const ILIF_ALPHA = IMAGE_LIST_ITEM_FLAGS.ALPHA;
pub const ILIF_LOWQUALITY = IMAGE_LIST_ITEM_FLAGS.LOWQUALITY;
pub const RICH_EDIT_GET_OBJECT_FLAGS = enum(u32) {
POLEOBJ = 1,
PSTG = 2,
POLESITE = 4,
NO_INTERFACES = 0,
ALL_INTERFACES = 7,
_,
pub fn initFlags(o: struct {
POLEOBJ: u1 = 0,
PSTG: u1 = 0,
POLESITE: u1 = 0,
NO_INTERFACES: u1 = 0,
ALL_INTERFACES: u1 = 0,
}) RICH_EDIT_GET_OBJECT_FLAGS {
return @intToEnum(RICH_EDIT_GET_OBJECT_FLAGS,
(if (o.POLEOBJ == 1) @enumToInt(RICH_EDIT_GET_OBJECT_FLAGS.POLEOBJ) else 0)
| (if (o.PSTG == 1) @enumToInt(RICH_EDIT_GET_OBJECT_FLAGS.PSTG) else 0)
| (if (o.POLESITE == 1) @enumToInt(RICH_EDIT_GET_OBJECT_FLAGS.POLESITE) else 0)
| (if (o.NO_INTERFACES == 1) @enumToInt(RICH_EDIT_GET_OBJECT_FLAGS.NO_INTERFACES) else 0)
| (if (o.ALL_INTERFACES == 1) @enumToInt(RICH_EDIT_GET_OBJECT_FLAGS.ALL_INTERFACES) else 0)
);
}
};
pub const REO_GETOBJ_POLEOBJ = RICH_EDIT_GET_OBJECT_FLAGS.POLEOBJ;
pub const REO_GETOBJ_PSTG = RICH_EDIT_GET_OBJECT_FLAGS.PSTG;
pub const REO_GETOBJ_POLESITE = RICH_EDIT_GET_OBJECT_FLAGS.POLESITE;
pub const REO_GETOBJ_NO_INTERFACES = RICH_EDIT_GET_OBJECT_FLAGS.NO_INTERFACES;
pub const REO_GETOBJ_ALL_INTERFACES = RICH_EDIT_GET_OBJECT_FLAGS.ALL_INTERFACES;
pub const HDI_MASK = enum(u32) {
WIDTH = 1,
// HEIGHT = 1, this enum value conflicts with WIDTH
TEXT = 2,
FORMAT = 4,
LPARAM = 8,
BITMAP = 16,
IMAGE = 32,
DI_SETITEM = 64,
ORDER = 128,
FILTER = 256,
STATE = 512,
_,
pub fn initFlags(o: struct {
WIDTH: u1 = 0,
TEXT: u1 = 0,
FORMAT: u1 = 0,
LPARAM: u1 = 0,
BITMAP: u1 = 0,
IMAGE: u1 = 0,
DI_SETITEM: u1 = 0,
ORDER: u1 = 0,
FILTER: u1 = 0,
STATE: u1 = 0,
}) HDI_MASK {
return @intToEnum(HDI_MASK,
(if (o.WIDTH == 1) @enumToInt(HDI_MASK.WIDTH) else 0)
| (if (o.TEXT == 1) @enumToInt(HDI_MASK.TEXT) else 0)
| (if (o.FORMAT == 1) @enumToInt(HDI_MASK.FORMAT) else 0)
| (if (o.LPARAM == 1) @enumToInt(HDI_MASK.LPARAM) else 0)
| (if (o.BITMAP == 1) @enumToInt(HDI_MASK.BITMAP) else 0)
| (if (o.IMAGE == 1) @enumToInt(HDI_MASK.IMAGE) else 0)
| (if (o.DI_SETITEM == 1) @enumToInt(HDI_MASK.DI_SETITEM) else 0)
| (if (o.ORDER == 1) @enumToInt(HDI_MASK.ORDER) else 0)
| (if (o.FILTER == 1) @enumToInt(HDI_MASK.FILTER) else 0)
| (if (o.STATE == 1) @enumToInt(HDI_MASK.STATE) else 0)
);
}
};
pub const HDI_WIDTH = HDI_MASK.WIDTH;
pub const HDI_HEIGHT = HDI_MASK.WIDTH;
pub const HDI_TEXT = HDI_MASK.TEXT;
pub const HDI_FORMAT = HDI_MASK.FORMAT;
pub const HDI_LPARAM = HDI_MASK.LPARAM;
pub const HDI_BITMAP = HDI_MASK.BITMAP;
pub const HDI_IMAGE = HDI_MASK.IMAGE;
pub const HDI_DI_SETITEM = HDI_MASK.DI_SETITEM;
pub const HDI_ORDER = HDI_MASK.ORDER;
pub const HDI_FILTER = HDI_MASK.FILTER;
pub const HDI_STATE = HDI_MASK.STATE;
pub const NMREBAR_MASK_FLAGS = enum(u32) {
ID = 1,
LPARAM = 4,
STYLE = 2,
_,
pub fn initFlags(o: struct {
ID: u1 = 0,
LPARAM: u1 = 0,
STYLE: u1 = 0,
}) NMREBAR_MASK_FLAGS {
return @intToEnum(NMREBAR_MASK_FLAGS,
(if (o.ID == 1) @enumToInt(NMREBAR_MASK_FLAGS.ID) else 0)
| (if (o.LPARAM == 1) @enumToInt(NMREBAR_MASK_FLAGS.LPARAM) else 0)
| (if (o.STYLE == 1) @enumToInt(NMREBAR_MASK_FLAGS.STYLE) else 0)
);
}
};
pub const RBNM_ID = NMREBAR_MASK_FLAGS.ID;
pub const RBNM_LPARAM = NMREBAR_MASK_FLAGS.LPARAM;
pub const RBNM_STYLE = NMREBAR_MASK_FLAGS.STYLE;
pub const EDITBALLOONTIP_ICON = enum(u32) {
ERROR = 3,
INFO = 1,
NONE = 0,
WARNING = 2,
INFO_LARGE = 4,
WARNING_LARGE = 5,
ERROR_LARGE = 6,
};
pub const TTI_ERROR = EDITBALLOONTIP_ICON.ERROR;
pub const TTI_INFO = EDITBALLOONTIP_ICON.INFO;
pub const TTI_NONE = EDITBALLOONTIP_ICON.NONE;
pub const TTI_WARNING = EDITBALLOONTIP_ICON.WARNING;
pub const TTI_INFO_LARGE = EDITBALLOONTIP_ICON.INFO_LARGE;
pub const TTI_WARNING_LARGE = EDITBALLOONTIP_ICON.WARNING_LARGE;
pub const TTI_ERROR_LARGE = EDITBALLOONTIP_ICON.ERROR_LARGE;
pub const LVCOLUMNW_FORMAT = enum(u32) {
LEFT = 0,
RIGHT = 1,
CENTER = 2,
JUSTIFYMASK = 3,
IMAGE = 2048,
BITMAP_ON_RIGHT = 4096,
COL_HAS_IMAGES = 32768,
FIXED_WIDTH = 256,
NO_DPI_SCALE = 262144,
FIXED_RATIO = 524288,
SPLITBUTTON = 16777216,
_,
pub fn initFlags(o: struct {
LEFT: u1 = 0,
RIGHT: u1 = 0,
CENTER: u1 = 0,
JUSTIFYMASK: u1 = 0,
IMAGE: u1 = 0,
BITMAP_ON_RIGHT: u1 = 0,
COL_HAS_IMAGES: u1 = 0,
FIXED_WIDTH: u1 = 0,
NO_DPI_SCALE: u1 = 0,
FIXED_RATIO: u1 = 0,
SPLITBUTTON: u1 = 0,
}) LVCOLUMNW_FORMAT {
return @intToEnum(LVCOLUMNW_FORMAT,
(if (o.LEFT == 1) @enumToInt(LVCOLUMNW_FORMAT.LEFT) else 0)
| (if (o.RIGHT == 1) @enumToInt(LVCOLUMNW_FORMAT.RIGHT) else 0)
| (if (o.CENTER == 1) @enumToInt(LVCOLUMNW_FORMAT.CENTER) else 0)
| (if (o.JUSTIFYMASK == 1) @enumToInt(LVCOLUMNW_FORMAT.JUSTIFYMASK) else 0)
| (if (o.IMAGE == 1) @enumToInt(LVCOLUMNW_FORMAT.IMAGE) else 0)
| (if (o.BITMAP_ON_RIGHT == 1) @enumToInt(LVCOLUMNW_FORMAT.BITMAP_ON_RIGHT) else 0)
| (if (o.COL_HAS_IMAGES == 1) @enumToInt(LVCOLUMNW_FORMAT.COL_HAS_IMAGES) else 0)
| (if (o.FIXED_WIDTH == 1) @enumToInt(LVCOLUMNW_FORMAT.FIXED_WIDTH) else 0)
| (if (o.NO_DPI_SCALE == 1) @enumToInt(LVCOLUMNW_FORMAT.NO_DPI_SCALE) else 0)
| (if (o.FIXED_RATIO == 1) @enumToInt(LVCOLUMNW_FORMAT.FIXED_RATIO) else 0)
| (if (o.SPLITBUTTON == 1) @enumToInt(LVCOLUMNW_FORMAT.SPLITBUTTON) else 0)
);
}
};
pub const LVCFMT_LEFT = LVCOLUMNW_FORMAT.LEFT;
pub const LVCFMT_RIGHT = LVCOLUMNW_FORMAT.RIGHT;
pub const LVCFMT_CENTER = LVCOLUMNW_FORMAT.CENTER;
pub const LVCFMT_JUSTIFYMASK = LVCOLUMNW_FORMAT.JUSTIFYMASK;
pub const LVCFMT_IMAGE = LVCOLUMNW_FORMAT.IMAGE;
pub const LVCFMT_BITMAP_ON_RIGHT = LVCOLUMNW_FORMAT.BITMAP_ON_RIGHT;
pub const LVCFMT_COL_HAS_IMAGES = LVCOLUMNW_FORMAT.COL_HAS_IMAGES;
pub const LVCFMT_FIXED_WIDTH = LVCOLUMNW_FORMAT.FIXED_WIDTH;
pub const LVCFMT_NO_DPI_SCALE = LVCOLUMNW_FORMAT.NO_DPI_SCALE;
pub const LVCFMT_FIXED_RATIO = LVCOLUMNW_FORMAT.FIXED_RATIO;
pub const LVCFMT_SPLITBUTTON = LVCOLUMNW_FORMAT.SPLITBUTTON;
pub const NMPGSCROLL_KEYS = enum(u16) {
NONE = 0,
SHIFT = 1,
CONTROL = 2,
MENU = 4,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
SHIFT: u1 = 0,
CONTROL: u1 = 0,
MENU: u1 = 0,
}) NMPGSCROLL_KEYS {
return @intToEnum(NMPGSCROLL_KEYS,
(if (o.NONE == 1) @enumToInt(NMPGSCROLL_KEYS.NONE) else 0)
| (if (o.SHIFT == 1) @enumToInt(NMPGSCROLL_KEYS.SHIFT) else 0)
| (if (o.CONTROL == 1) @enumToInt(NMPGSCROLL_KEYS.CONTROL) else 0)
| (if (o.MENU == 1) @enumToInt(NMPGSCROLL_KEYS.MENU) else 0)
);
}
};
pub const PGK_NONE = NMPGSCROLL_KEYS.NONE;
pub const PGK_SHIFT = NMPGSCROLL_KEYS.SHIFT;
pub const PGK_CONTROL = NMPGSCROLL_KEYS.CONTROL;
pub const PGK_MENU = NMPGSCROLL_KEYS.MENU;
pub const COMBOBOX_EX_ITEM_FLAGS = enum(u32) {
DI_SETITEM = 268435456,
IMAGE = 2,
INDENT = 16,
LPARAM = 32,
OVERLAY = 8,
SELECTEDIMAGE = 4,
TEXT = 1,
_,
pub fn initFlags(o: struct {
DI_SETITEM: u1 = 0,
IMAGE: u1 = 0,
INDENT: u1 = 0,
LPARAM: u1 = 0,
OVERLAY: u1 = 0,
SELECTEDIMAGE: u1 = 0,
TEXT: u1 = 0,
}) COMBOBOX_EX_ITEM_FLAGS {
return @intToEnum(COMBOBOX_EX_ITEM_FLAGS,
(if (o.DI_SETITEM == 1) @enumToInt(COMBOBOX_EX_ITEM_FLAGS.DI_SETITEM) else 0)
| (if (o.IMAGE == 1) @enumToInt(COMBOBOX_EX_ITEM_FLAGS.IMAGE) else 0)
| (if (o.INDENT == 1) @enumToInt(COMBOBOX_EX_ITEM_FLAGS.INDENT) else 0)
| (if (o.LPARAM == 1) @enumToInt(COMBOBOX_EX_ITEM_FLAGS.LPARAM) else 0)
| (if (o.OVERLAY == 1) @enumToInt(COMBOBOX_EX_ITEM_FLAGS.OVERLAY) else 0)
| (if (o.SELECTEDIMAGE == 1) @enumToInt(COMBOBOX_EX_ITEM_FLAGS.SELECTEDIMAGE) else 0)
| (if (o.TEXT == 1) @enumToInt(COMBOBOX_EX_ITEM_FLAGS.TEXT) else 0)
);
}
};
pub const CBEIF_DI_SETITEM = COMBOBOX_EX_ITEM_FLAGS.DI_SETITEM;
pub const CBEIF_IMAGE = COMBOBOX_EX_ITEM_FLAGS.IMAGE;
pub const CBEIF_INDENT = COMBOBOX_EX_ITEM_FLAGS.INDENT;
pub const CBEIF_LPARAM = COMBOBOX_EX_ITEM_FLAGS.LPARAM;
pub const CBEIF_OVERLAY = COMBOBOX_EX_ITEM_FLAGS.OVERLAY;
pub const CBEIF_SELECTEDIMAGE = COMBOBOX_EX_ITEM_FLAGS.SELECTEDIMAGE;
pub const CBEIF_TEXT = COMBOBOX_EX_ITEM_FLAGS.TEXT;
pub const TVITEMEXW_CHILDREN = enum(i32) {
ZERO = 0,
ONE_OR_MORE = 1,
CHILDRENCALLBACK = -1,
CHILDRENAUTO = -2,
};
pub const I_ZERO = TVITEMEXW_CHILDREN.ZERO;
pub const I_ONE_OR_MORE = TVITEMEXW_CHILDREN.ONE_OR_MORE;
pub const I_CHILDRENCALLBACK = TVITEMEXW_CHILDREN.CHILDRENCALLBACK;
pub const I_CHILDRENAUTO = TVITEMEXW_CHILDREN.CHILDRENAUTO;
pub const TVITEM_MASK = enum(u32) {
CHILDREN = 64,
DI_SETITEM = 4096,
HANDLE = 16,
IMAGE = 2,
PARAM = 4,
SELECTEDIMAGE = 32,
STATE = 8,
TEXT = 1,
EXPANDEDIMAGE = 512,
INTEGRAL = 128,
STATEEX = 256,
_,
pub fn initFlags(o: struct {
CHILDREN: u1 = 0,
DI_SETITEM: u1 = 0,
HANDLE: u1 = 0,
IMAGE: u1 = 0,
PARAM: u1 = 0,
SELECTEDIMAGE: u1 = 0,
STATE: u1 = 0,
TEXT: u1 = 0,
EXPANDEDIMAGE: u1 = 0,
INTEGRAL: u1 = 0,
STATEEX: u1 = 0,
}) TVITEM_MASK {
return @intToEnum(TVITEM_MASK,
(if (o.CHILDREN == 1) @enumToInt(TVITEM_MASK.CHILDREN) else 0)
| (if (o.DI_SETITEM == 1) @enumToInt(TVITEM_MASK.DI_SETITEM) else 0)
| (if (o.HANDLE == 1) @enumToInt(TVITEM_MASK.HANDLE) else 0)
| (if (o.IMAGE == 1) @enumToInt(TVITEM_MASK.IMAGE) else 0)
| (if (o.PARAM == 1) @enumToInt(TVITEM_MASK.PARAM) else 0)
| (if (o.SELECTEDIMAGE == 1) @enumToInt(TVITEM_MASK.SELECTEDIMAGE) else 0)
| (if (o.STATE == 1) @enumToInt(TVITEM_MASK.STATE) else 0)
| (if (o.TEXT == 1) @enumToInt(TVITEM_MASK.TEXT) else 0)
| (if (o.EXPANDEDIMAGE == 1) @enumToInt(TVITEM_MASK.EXPANDEDIMAGE) else 0)
| (if (o.INTEGRAL == 1) @enumToInt(TVITEM_MASK.INTEGRAL) else 0)
| (if (o.STATEEX == 1) @enumToInt(TVITEM_MASK.STATEEX) else 0)
);
}
};
pub const TVIF_CHILDREN = TVITEM_MASK.CHILDREN;
pub const TVIF_DI_SETITEM = TVITEM_MASK.DI_SETITEM;
pub const TVIF_HANDLE = TVITEM_MASK.HANDLE;
pub const TVIF_IMAGE = TVITEM_MASK.IMAGE;
pub const TVIF_PARAM = TVITEM_MASK.PARAM;
pub const TVIF_SELECTEDIMAGE = TVITEM_MASK.SELECTEDIMAGE;
pub const TVIF_STATE = TVITEM_MASK.STATE;
pub const TVIF_TEXT = TVITEM_MASK.TEXT;
pub const TVIF_EXPANDEDIMAGE = TVITEM_MASK.EXPANDEDIMAGE;
pub const TVIF_INTEGRAL = TVITEM_MASK.INTEGRAL;
pub const TVIF_STATEEX = TVITEM_MASK.STATEEX;
pub const TCITEMHEADERA_MASK = enum(u32) {
IMAGE = 2,
RTLREADING = 4,
TEXT = 1,
PARAM = 8,
STATE = 16,
_,
pub fn initFlags(o: struct {
IMAGE: u1 = 0,
RTLREADING: u1 = 0,
TEXT: u1 = 0,
PARAM: u1 = 0,
STATE: u1 = 0,
}) TCITEMHEADERA_MASK {
return @intToEnum(TCITEMHEADERA_MASK,
(if (o.IMAGE == 1) @enumToInt(TCITEMHEADERA_MASK.IMAGE) else 0)
| (if (o.RTLREADING == 1) @enumToInt(TCITEMHEADERA_MASK.RTLREADING) else 0)
| (if (o.TEXT == 1) @enumToInt(TCITEMHEADERA_MASK.TEXT) else 0)
| (if (o.PARAM == 1) @enumToInt(TCITEMHEADERA_MASK.PARAM) else 0)
| (if (o.STATE == 1) @enumToInt(TCITEMHEADERA_MASK.STATE) else 0)
);
}
};
pub const TCIF_IMAGE = TCITEMHEADERA_MASK.IMAGE;
pub const TCIF_RTLREADING = TCITEMHEADERA_MASK.RTLREADING;
pub const TCIF_TEXT = TCITEMHEADERA_MASK.TEXT;
pub const TCIF_PARAM = TCITEMHEADERA_MASK.PARAM;
pub const TCIF_STATE = TCITEMHEADERA_MASK.STATE;
pub const TCHITTESTINFO_FLAGS = enum(u32) {
NOWHERE = 1,
ONITEM = 6,
ONITEMICON = 2,
ONITEMLABEL = 4,
};
pub const TCHT_NOWHERE = TCHITTESTINFO_FLAGS.NOWHERE;
pub const TCHT_ONITEM = TCHITTESTINFO_FLAGS.ONITEM;
pub const TCHT_ONITEMICON = TCHITTESTINFO_FLAGS.ONITEMICON;
pub const TCHT_ONITEMLABEL = TCHITTESTINFO_FLAGS.ONITEMLABEL;
pub const COMBOBOXINFO_BUTTON_STATE = enum(u32) {
INVISIBLE = 32768,
PRESSED = 8,
FOCUSABLE = 1048576,
OFFSCREEN = 65536,
UNAVAILABLE = 1,
};
pub const STATE_SYSTEM_INVISIBLE = COMBOBOXINFO_BUTTON_STATE.INVISIBLE;
pub const STATE_SYSTEM_PRESSED = COMBOBOXINFO_BUTTON_STATE.PRESSED;
pub const STATE_SYSTEM_FOCUSABLE = COMBOBOXINFO_BUTTON_STATE.FOCUSABLE;
pub const STATE_SYSTEM_OFFSCREEN = COMBOBOXINFO_BUTTON_STATE.OFFSCREEN;
pub const STATE_SYSTEM_UNAVAILABLE = COMBOBOXINFO_BUTTON_STATE.UNAVAILABLE;
pub const NMCUSTOMDRAW_DRAW_STAGE = enum(u32) {
POSTPAINT = 2,
PREERASE = 3,
PREPAINT = 1,
ITEMPOSTERASE = 65540,
ITEMPOSTPAINT = 65538,
ITEMPREERASE = 65539,
ITEMPREPAINT = 65537,
SUBITEM = 131072,
};
pub const CDDS_POSTPAINT = NMCUSTOMDRAW_DRAW_STAGE.POSTPAINT;
pub const CDDS_PREERASE = NMCUSTOMDRAW_DRAW_STAGE.PREERASE;
pub const CDDS_PREPAINT = NMCUSTOMDRAW_DRAW_STAGE.PREPAINT;
pub const CDDS_ITEMPOSTERASE = NMCUSTOMDRAW_DRAW_STAGE.ITEMPOSTERASE;
pub const CDDS_ITEMPOSTPAINT = NMCUSTOMDRAW_DRAW_STAGE.ITEMPOSTPAINT;
pub const CDDS_ITEMPREERASE = NMCUSTOMDRAW_DRAW_STAGE.ITEMPREERASE;
pub const CDDS_ITEMPREPAINT = NMCUSTOMDRAW_DRAW_STAGE.ITEMPREPAINT;
pub const CDDS_SUBITEM = NMCUSTOMDRAW_DRAW_STAGE.SUBITEM;
pub const MCGRIDINFO_PART = enum(u32) {
CALENDARCONTROL = 0,
NEXT = 1,
PREV = 2,
FOOTER = 3,
CALENDAR = 4,
CALENDARHEADER = 5,
CALENDARBODY = 6,
CALENDARROW = 7,
CALENDARCELL = 8,
};
pub const MCGIP_CALENDARCONTROL = MCGRIDINFO_PART.CALENDARCONTROL;
pub const MCGIP_NEXT = MCGRIDINFO_PART.NEXT;
pub const MCGIP_PREV = MCGRIDINFO_PART.PREV;
pub const MCGIP_FOOTER = MCGRIDINFO_PART.FOOTER;
pub const MCGIP_CALENDAR = MCGRIDINFO_PART.CALENDAR;
pub const MCGIP_CALENDARHEADER = MCGRIDINFO_PART.CALENDARHEADER;
pub const MCGIP_CALENDARBODY = MCGRIDINFO_PART.CALENDARBODY;
pub const MCGIP_CALENDARROW = MCGRIDINFO_PART.CALENDARROW;
pub const MCGIP_CALENDARCELL = MCGRIDINFO_PART.CALENDARCELL;
pub const PARAFORMAT_BORDERS = enum(u16) {
LEFT = 1,
RIGHT = 2,
TOP = 4,
BOTTOM = 8,
INSIDE = 16,
OUTSIDE = 32,
AUTOCOLOR = 64,
_,
pub fn initFlags(o: struct {
LEFT: u1 = 0,
RIGHT: u1 = 0,
TOP: u1 = 0,
BOTTOM: u1 = 0,
INSIDE: u1 = 0,
OUTSIDE: u1 = 0,
AUTOCOLOR: u1 = 0,
}) PARAFORMAT_BORDERS {
return @intToEnum(PARAFORMAT_BORDERS,
(if (o.LEFT == 1) @enumToInt(PARAFORMAT_BORDERS.LEFT) else 0)
| (if (o.RIGHT == 1) @enumToInt(PARAFORMAT_BORDERS.RIGHT) else 0)
| (if (o.TOP == 1) @enumToInt(PARAFORMAT_BORDERS.TOP) else 0)
| (if (o.BOTTOM == 1) @enumToInt(PARAFORMAT_BORDERS.BOTTOM) else 0)
| (if (o.INSIDE == 1) @enumToInt(PARAFORMAT_BORDERS.INSIDE) else 0)
| (if (o.OUTSIDE == 1) @enumToInt(PARAFORMAT_BORDERS.OUTSIDE) else 0)
| (if (o.AUTOCOLOR == 1) @enumToInt(PARAFORMAT_BORDERS.AUTOCOLOR) else 0)
);
}
};
pub const PARAFORMAT_BORDERS_LEFT = PARAFORMAT_BORDERS.LEFT;
pub const PARAFORMAT_BORDERS_RIGHT = PARAFORMAT_BORDERS.RIGHT;
pub const PARAFORMAT_BORDERS_TOP = PARAFORMAT_BORDERS.TOP;
pub const PARAFORMAT_BORDERS_BOTTOM = PARAFORMAT_BORDERS.BOTTOM;
pub const PARAFORMAT_BORDERS_INSIDE = PARAFORMAT_BORDERS.INSIDE;
pub const PARAFORMAT_BORDERS_OUTSIDE = PARAFORMAT_BORDERS.OUTSIDE;
pub const PARAFORMAT_BORDERS_AUTOCOLOR = PARAFORMAT_BORDERS.AUTOCOLOR;
pub const LVITEMA_GROUP_ID = enum(i32) {
CALLBACK = -1,
NONE = -2,
};
pub const I_GROUPIDCALLBACK = LVITEMA_GROUP_ID.CALLBACK;
pub const I_GROUPIDNONE = LVITEMA_GROUP_ID.NONE;
pub const NMTBHOTITEM_FLAGS = enum(u32) {
ACCELERATOR = 4,
ARROWKEYS = 2,
DUPACCEL = 8,
ENTERING = 16,
LEAVING = 32,
LMOUSE = 128,
MOUSE = 1,
OTHER = 0,
RESELECT = 64,
TOGGLEDROPDOWN = 256,
_,
pub fn initFlags(o: struct {
ACCELERATOR: u1 = 0,
ARROWKEYS: u1 = 0,
DUPACCEL: u1 = 0,
ENTERING: u1 = 0,
LEAVING: u1 = 0,
LMOUSE: u1 = 0,
MOUSE: u1 = 0,
OTHER: u1 = 0,
RESELECT: u1 = 0,
TOGGLEDROPDOWN: u1 = 0,
}) NMTBHOTITEM_FLAGS {
return @intToEnum(NMTBHOTITEM_FLAGS,
(if (o.ACCELERATOR == 1) @enumToInt(NMTBHOTITEM_FLAGS.ACCELERATOR) else 0)
| (if (o.ARROWKEYS == 1) @enumToInt(NMTBHOTITEM_FLAGS.ARROWKEYS) else 0)
| (if (o.DUPACCEL == 1) @enumToInt(NMTBHOTITEM_FLAGS.DUPACCEL) else 0)
| (if (o.ENTERING == 1) @enumToInt(NMTBHOTITEM_FLAGS.ENTERING) else 0)
| (if (o.LEAVING == 1) @enumToInt(NMTBHOTITEM_FLAGS.LEAVING) else 0)
| (if (o.LMOUSE == 1) @enumToInt(NMTBHOTITEM_FLAGS.LMOUSE) else 0)
| (if (o.MOUSE == 1) @enumToInt(NMTBHOTITEM_FLAGS.MOUSE) else 0)
| (if (o.OTHER == 1) @enumToInt(NMTBHOTITEM_FLAGS.OTHER) else 0)
| (if (o.RESELECT == 1) @enumToInt(NMTBHOTITEM_FLAGS.RESELECT) else 0)
| (if (o.TOGGLEDROPDOWN == 1) @enumToInt(NMTBHOTITEM_FLAGS.TOGGLEDROPDOWN) else 0)
);
}
};
pub const HICF_ACCELERATOR = NMTBHOTITEM_FLAGS.ACCELERATOR;
pub const HICF_ARROWKEYS = NMTBHOTITEM_FLAGS.ARROWKEYS;
pub const HICF_DUPACCEL = NMTBHOTITEM_FLAGS.DUPACCEL;
pub const HICF_ENTERING = NMTBHOTITEM_FLAGS.ENTERING;
pub const HICF_LEAVING = NMTBHOTITEM_FLAGS.LEAVING;
pub const HICF_LMOUSE = NMTBHOTITEM_FLAGS.LMOUSE;
pub const HICF_MOUSE = NMTBHOTITEM_FLAGS.MOUSE;
pub const HICF_OTHER = NMTBHOTITEM_FLAGS.OTHER;
pub const HICF_RESELECT = NMTBHOTITEM_FLAGS.RESELECT;
pub const HICF_TOGGLEDROPDOWN = NMTBHOTITEM_FLAGS.TOGGLEDROPDOWN;
pub const LVTILEVIEWINFO_FLAGS = enum(u32) {
D = 4,
};
pub const LVTVIF_EXTENDED = LVTILEVIEWINFO_FLAGS.D;
pub const NMPGSCROLL_DIR = enum(u32) {
DOWN = 2,
LEFT = 4,
RIGHT = 8,
UP = 1,
};
pub const PGF_SCROLLDOWN = NMPGSCROLL_DIR.DOWN;
pub const PGF_SCROLLLEFT = NMPGSCROLL_DIR.LEFT;
pub const PGF_SCROLLRIGHT = NMPGSCROLL_DIR.RIGHT;
pub const PGF_SCROLLUP = NMPGSCROLL_DIR.UP;
pub const PARAFORMAT_SHADING_STYLE = enum(u16) {
NONE = 0,
DARK_HORIZ = 1,
DARK_VERT = 2,
DARK_DOWN_DIAG = 3,
DARK_UP_DIAG = 4,
DARK_GRID = 5,
DARK_TRELLIS = 6,
LIGHT_HORZ = 7,
LIGHT_VERT = 8,
LIGHT_DOWN_DIAG = 9,
LIGHT_UP_DIAG = 10,
LIGHT_GRID = 11,
LIGHT_TRELLIS = 12,
};
pub const PARAFORMAT_SHADING_STYLE_NONE = PARAFORMAT_SHADING_STYLE.NONE;
pub const PARAFORMAT_SHADING_STYLE_DARK_HORIZ = PARAFORMAT_SHADING_STYLE.DARK_HORIZ;
pub const PARAFORMAT_SHADING_STYLE_DARK_VERT = PARAFORMAT_SHADING_STYLE.DARK_VERT;
pub const PARAFORMAT_SHADING_STYLE_DARK_DOWN_DIAG = PARAFORMAT_SHADING_STYLE.DARK_DOWN_DIAG;
pub const PARAFORMAT_SHADING_STYLE_DARK_UP_DIAG = PARAFORMAT_SHADING_STYLE.DARK_UP_DIAG;
pub const PARAFORMAT_SHADING_STYLE_DARK_GRID = PARAFORMAT_SHADING_STYLE.DARK_GRID;
pub const PARAFORMAT_SHADING_STYLE_DARK_TRELLIS = PARAFORMAT_SHADING_STYLE.DARK_TRELLIS;
pub const PARAFORMAT_SHADING_STYLE_LIGHT_HORZ = PARAFORMAT_SHADING_STYLE.LIGHT_HORZ;
pub const PARAFORMAT_SHADING_STYLE_LIGHT_VERT = PARAFORMAT_SHADING_STYLE.LIGHT_VERT;
pub const PARAFORMAT_SHADING_STYLE_LIGHT_DOWN_DIAG = PARAFORMAT_SHADING_STYLE.LIGHT_DOWN_DIAG;
pub const PARAFORMAT_SHADING_STYLE_LIGHT_UP_DIAG = PARAFORMAT_SHADING_STYLE.LIGHT_UP_DIAG;
pub const PARAFORMAT_SHADING_STYLE_LIGHT_GRID = PARAFORMAT_SHADING_STYLE.LIGHT_GRID;
pub const PARAFORMAT_SHADING_STYLE_LIGHT_TRELLIS = PARAFORMAT_SHADING_STYLE.LIGHT_TRELLIS;
pub const LVCOLUMNW_MASK = enum(u32) {
FMT = 1,
WIDTH = 2,
TEXT = 4,
SUBITEM = 8,
IMAGE = 16,
ORDER = 32,
MINWIDTH = 64,
DEFAULTWIDTH = 128,
IDEALWIDTH = 256,
_,
pub fn initFlags(o: struct {
FMT: u1 = 0,
WIDTH: u1 = 0,
TEXT: u1 = 0,
SUBITEM: u1 = 0,
IMAGE: u1 = 0,
ORDER: u1 = 0,
MINWIDTH: u1 = 0,
DEFAULTWIDTH: u1 = 0,
IDEALWIDTH: u1 = 0,
}) LVCOLUMNW_MASK {
return @intToEnum(LVCOLUMNW_MASK,
(if (o.FMT == 1) @enumToInt(LVCOLUMNW_MASK.FMT) else 0)
| (if (o.WIDTH == 1) @enumToInt(LVCOLUMNW_MASK.WIDTH) else 0)
| (if (o.TEXT == 1) @enumToInt(LVCOLUMNW_MASK.TEXT) else 0)
| (if (o.SUBITEM == 1) @enumToInt(LVCOLUMNW_MASK.SUBITEM) else 0)
| (if (o.IMAGE == 1) @enumToInt(LVCOLUMNW_MASK.IMAGE) else 0)
| (if (o.ORDER == 1) @enumToInt(LVCOLUMNW_MASK.ORDER) else 0)
| (if (o.MINWIDTH == 1) @enumToInt(LVCOLUMNW_MASK.MINWIDTH) else 0)
| (if (o.DEFAULTWIDTH == 1) @enumToInt(LVCOLUMNW_MASK.DEFAULTWIDTH) else 0)
| (if (o.IDEALWIDTH == 1) @enumToInt(LVCOLUMNW_MASK.IDEALWIDTH) else 0)
);
}
};
pub const LVCF_FMT = LVCOLUMNW_MASK.FMT;
pub const LVCF_WIDTH = LVCOLUMNW_MASK.WIDTH;
pub const LVCF_TEXT = LVCOLUMNW_MASK.TEXT;
pub const LVCF_SUBITEM = LVCOLUMNW_MASK.SUBITEM;
pub const LVCF_IMAGE = LVCOLUMNW_MASK.IMAGE;
pub const LVCF_ORDER = LVCOLUMNW_MASK.ORDER;
pub const LVCF_MINWIDTH = LVCOLUMNW_MASK.MINWIDTH;
pub const LVCF_DEFAULTWIDTH = LVCOLUMNW_MASK.DEFAULTWIDTH;
pub const LVCF_IDEALWIDTH = LVCOLUMNW_MASK.IDEALWIDTH;
pub const GETTEXTEX_FLAGS = enum(u32) {
DEFAULT = 0,
NOHIDDENTEXT = 8,
RAWTEXT = 4,
SELECTION = 2,
USECRLF = 1,
};
pub const GT_DEFAULT = GETTEXTEX_FLAGS.DEFAULT;
pub const GT_NOHIDDENTEXT = GETTEXTEX_FLAGS.NOHIDDENTEXT;
pub const GT_RAWTEXT = GETTEXTEX_FLAGS.RAWTEXT;
pub const GT_SELECTION = GETTEXTEX_FLAGS.SELECTION;
pub const GT_USECRLF = GETTEXTEX_FLAGS.USECRLF;
pub const LVFINDINFOW_FLAGS = enum(u32) {
PARAM = 1,
PARTIAL = 8,
STRING = 2,
SUBSTRING = 4,
WRAP = 32,
NEARESTXY = 64,
_,
pub fn initFlags(o: struct {
PARAM: u1 = 0,
PARTIAL: u1 = 0,
STRING: u1 = 0,
SUBSTRING: u1 = 0,
WRAP: u1 = 0,
NEARESTXY: u1 = 0,
}) LVFINDINFOW_FLAGS {
return @intToEnum(LVFINDINFOW_FLAGS,
(if (o.PARAM == 1) @enumToInt(LVFINDINFOW_FLAGS.PARAM) else 0)
| (if (o.PARTIAL == 1) @enumToInt(LVFINDINFOW_FLAGS.PARTIAL) else 0)
| (if (o.STRING == 1) @enumToInt(LVFINDINFOW_FLAGS.STRING) else 0)
| (if (o.SUBSTRING == 1) @enumToInt(LVFINDINFOW_FLAGS.SUBSTRING) else 0)
| (if (o.WRAP == 1) @enumToInt(LVFINDINFOW_FLAGS.WRAP) else 0)
| (if (o.NEARESTXY == 1) @enumToInt(LVFINDINFOW_FLAGS.NEARESTXY) else 0)
);
}
};
pub const LVFI_PARAM = LVFINDINFOW_FLAGS.PARAM;
pub const LVFI_PARTIAL = LVFINDINFOW_FLAGS.PARTIAL;
pub const LVFI_STRING = LVFINDINFOW_FLAGS.STRING;
pub const LVFI_SUBSTRING = LVFINDINFOW_FLAGS.SUBSTRING;
pub const LVFI_WRAP = LVFINDINFOW_FLAGS.WRAP;
pub const LVFI_NEARESTXY = LVFINDINFOW_FLAGS.NEARESTXY;
pub const BUTTON_IMAGELIST_ALIGN = enum(u32) {
LEFT = 0,
RIGHT = 1,
TOP = 2,
BOTTOM = 3,
CENTER = 4,
};
pub const BUTTON_IMAGELIST_ALIGN_LEFT = BUTTON_IMAGELIST_ALIGN.LEFT;
pub const BUTTON_IMAGELIST_ALIGN_RIGHT = BUTTON_IMAGELIST_ALIGN.RIGHT;
pub const BUTTON_IMAGELIST_ALIGN_TOP = BUTTON_IMAGELIST_ALIGN.TOP;
pub const BUTTON_IMAGELIST_ALIGN_BOTTOM = BUTTON_IMAGELIST_ALIGN.BOTTOM;
pub const BUTTON_IMAGELIST_ALIGN_CENTER = BUTTON_IMAGELIST_ALIGN.CENTER;
pub const TBBUTTONINFOW_MASK = enum(u32) {
BYINDEX = 2147483648,
COMMAND = 32,
IMAGE = 1,
LPARAM = 16,
SIZE = 64,
STATE = 4,
STYLE = 8,
TEXT = 2,
_,
pub fn initFlags(o: struct {
BYINDEX: u1 = 0,
COMMAND: u1 = 0,
IMAGE: u1 = 0,
LPARAM: u1 = 0,
SIZE: u1 = 0,
STATE: u1 = 0,
STYLE: u1 = 0,
TEXT: u1 = 0,
}) TBBUTTONINFOW_MASK {
return @intToEnum(TBBUTTONINFOW_MASK,
(if (o.BYINDEX == 1) @enumToInt(TBBUTTONINFOW_MASK.BYINDEX) else 0)
| (if (o.COMMAND == 1) @enumToInt(TBBUTTONINFOW_MASK.COMMAND) else 0)
| (if (o.IMAGE == 1) @enumToInt(TBBUTTONINFOW_MASK.IMAGE) else 0)
| (if (o.LPARAM == 1) @enumToInt(TBBUTTONINFOW_MASK.LPARAM) else 0)
| (if (o.SIZE == 1) @enumToInt(TBBUTTONINFOW_MASK.SIZE) else 0)
| (if (o.STATE == 1) @enumToInt(TBBUTTONINFOW_MASK.STATE) else 0)
| (if (o.STYLE == 1) @enumToInt(TBBUTTONINFOW_MASK.STYLE) else 0)
| (if (o.TEXT == 1) @enumToInt(TBBUTTONINFOW_MASK.TEXT) else 0)
);
}
};
pub const TBIF_BYINDEX = TBBUTTONINFOW_MASK.BYINDEX;
pub const TBIF_COMMAND = TBBUTTONINFOW_MASK.COMMAND;
pub const TBIF_IMAGE = TBBUTTONINFOW_MASK.IMAGE;
pub const TBIF_LPARAM = TBBUTTONINFOW_MASK.LPARAM;
pub const TBIF_SIZE = TBBUTTONINFOW_MASK.SIZE;
pub const TBIF_STATE = TBBUTTONINFOW_MASK.STATE;
pub const TBIF_STYLE = TBBUTTONINFOW_MASK.STYLE;
pub const TBIF_TEXT = TBBUTTONINFOW_MASK.TEXT;
pub const TBINSERTMARK_FLAGS = enum(u32) {
NONE = 0,
AFTER = 1,
BACKGROUND = 2,
};
pub const TBIMHT_NONE = TBINSERTMARK_FLAGS.NONE;
pub const TBIMHT_AFTER = TBINSERTMARK_FLAGS.AFTER;
pub const TBIMHT_BACKGROUND = TBINSERTMARK_FLAGS.BACKGROUND;
pub const LVGROUP_MASK = enum(u32) {
NONE = 0,
HEADER = 1,
FOOTER = 2,
STATE = 4,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
HEADER: u1 = 0,
FOOTER: u1 = 0,
STATE: u1 = 0,
}) LVGROUP_MASK {
return @intToEnum(LVGROUP_MASK,
(if (o.NONE == 1) @enumToInt(LVGROUP_MASK.NONE) else 0)
| (if (o.HEADER == 1) @enumToInt(LVGROUP_MASK.HEADER) else 0)
| (if (o.FOOTER == 1) @enumToInt(LVGROUP_MASK.FOOTER) else 0)
| (if (o.STATE == 1) @enumToInt(LVGROUP_MASK.STATE) else 0)
);
}
};
pub const LVGF_NONE = LVGROUP_MASK.NONE;
pub const LVGF_HEADER = LVGROUP_MASK.HEADER;
pub const LVGF_FOOTER = LVGROUP_MASK.FOOTER;
pub const LVGF_STATE = LVGROUP_MASK.STATE;
pub const BP_PAINTPARAMS_FLAGS = enum(u32) {
ERASE = 1,
NOCLIP = 2,
NONCLIENT = 4,
_,
pub fn initFlags(o: struct {
ERASE: u1 = 0,
NOCLIP: u1 = 0,
NONCLIENT: u1 = 0,
}) BP_PAINTPARAMS_FLAGS {
return @intToEnum(BP_PAINTPARAMS_FLAGS,
(if (o.ERASE == 1) @enumToInt(BP_PAINTPARAMS_FLAGS.ERASE) else 0)
| (if (o.NOCLIP == 1) @enumToInt(BP_PAINTPARAMS_FLAGS.NOCLIP) else 0)
| (if (o.NONCLIENT == 1) @enumToInt(BP_PAINTPARAMS_FLAGS.NONCLIENT) else 0)
);
}
};
pub const BPPF_ERASE = BP_PAINTPARAMS_FLAGS.ERASE;
pub const BPPF_NOCLIP = BP_PAINTPARAMS_FLAGS.NOCLIP;
pub const BPPF_NONCLIENT = BP_PAINTPARAMS_FLAGS.NONCLIENT;
pub const TVHITTESTINFO_FLAGS = enum(u32) {
ABOVE = 256,
BELOW = 512,
NOWHERE = 1,
ONITEM = 70,
ONITEMBUTTON = 16,
ONITEMICON = 2,
ONITEMINDENT = 8,
ONITEMLABEL = 4,
ONITEMRIGHT = 32,
ONITEMSTATEICON = 64,
TOLEFT = 2048,
TORIGHT = 1024,
_,
pub fn initFlags(o: struct {
ABOVE: u1 = 0,
BELOW: u1 = 0,
NOWHERE: u1 = 0,
ONITEM: u1 = 0,
ONITEMBUTTON: u1 = 0,
ONITEMICON: u1 = 0,
ONITEMINDENT: u1 = 0,
ONITEMLABEL: u1 = 0,
ONITEMRIGHT: u1 = 0,
ONITEMSTATEICON: u1 = 0,
TOLEFT: u1 = 0,
TORIGHT: u1 = 0,
}) TVHITTESTINFO_FLAGS {
return @intToEnum(TVHITTESTINFO_FLAGS,
(if (o.ABOVE == 1) @enumToInt(TVHITTESTINFO_FLAGS.ABOVE) else 0)
| (if (o.BELOW == 1) @enumToInt(TVHITTESTINFO_FLAGS.BELOW) else 0)
| (if (o.NOWHERE == 1) @enumToInt(TVHITTESTINFO_FLAGS.NOWHERE) else 0)
| (if (o.ONITEM == 1) @enumToInt(TVHITTESTINFO_FLAGS.ONITEM) else 0)
| (if (o.ONITEMBUTTON == 1) @enumToInt(TVHITTESTINFO_FLAGS.ONITEMBUTTON) else 0)
| (if (o.ONITEMICON == 1) @enumToInt(TVHITTESTINFO_FLAGS.ONITEMICON) else 0)
| (if (o.ONITEMINDENT == 1) @enumToInt(TVHITTESTINFO_FLAGS.ONITEMINDENT) else 0)
| (if (o.ONITEMLABEL == 1) @enumToInt(TVHITTESTINFO_FLAGS.ONITEMLABEL) else 0)
| (if (o.ONITEMRIGHT == 1) @enumToInt(TVHITTESTINFO_FLAGS.ONITEMRIGHT) else 0)
| (if (o.ONITEMSTATEICON == 1) @enumToInt(TVHITTESTINFO_FLAGS.ONITEMSTATEICON) else 0)
| (if (o.TOLEFT == 1) @enumToInt(TVHITTESTINFO_FLAGS.TOLEFT) else 0)
| (if (o.TORIGHT == 1) @enumToInt(TVHITTESTINFO_FLAGS.TORIGHT) else 0)
);
}
};
pub const TVHT_ABOVE = TVHITTESTINFO_FLAGS.ABOVE;
pub const TVHT_BELOW = TVHITTESTINFO_FLAGS.BELOW;
pub const TVHT_NOWHERE = TVHITTESTINFO_FLAGS.NOWHERE;
pub const TVHT_ONITEM = TVHITTESTINFO_FLAGS.ONITEM;
pub const TVHT_ONITEMBUTTON = TVHITTESTINFO_FLAGS.ONITEMBUTTON;
pub const TVHT_ONITEMICON = TVHITTESTINFO_FLAGS.ONITEMICON;
pub const TVHT_ONITEMINDENT = TVHITTESTINFO_FLAGS.ONITEMINDENT;
pub const TVHT_ONITEMLABEL = TVHITTESTINFO_FLAGS.ONITEMLABEL;
pub const TVHT_ONITEMRIGHT = TVHITTESTINFO_FLAGS.ONITEMRIGHT;
pub const TVHT_ONITEMSTATEICON = TVHITTESTINFO_FLAGS.ONITEMSTATEICON;
pub const TVHT_TOLEFT = TVHITTESTINFO_FLAGS.TOLEFT;
pub const TVHT_TORIGHT = TVHITTESTINFO_FLAGS.TORIGHT;
pub const DRAWITEMSTRUCT_CTL_TYPE = enum(u32) {
BUTTON = 4,
COMBOBOX = 3,
LISTBOX = 2,
LISTVIEW = 102,
MENU = 1,
STATIC = 5,
TAB = 101,
};
pub const ODT_BUTTON = DRAWITEMSTRUCT_CTL_TYPE.BUTTON;
pub const ODT_COMBOBOX = DRAWITEMSTRUCT_CTL_TYPE.COMBOBOX;
pub const ODT_LISTBOX = DRAWITEMSTRUCT_CTL_TYPE.LISTBOX;
pub const ODT_LISTVIEW = DRAWITEMSTRUCT_CTL_TYPE.LISTVIEW;
pub const ODT_MENU = DRAWITEMSTRUCT_CTL_TYPE.MENU;
pub const ODT_STATIC = DRAWITEMSTRUCT_CTL_TYPE.STATIC;
pub const ODT_TAB = DRAWITEMSTRUCT_CTL_TYPE.TAB;
pub const NMPGCALCSIZE_FLAGS = enum(u32) {
HEIGHT = 2,
WIDTH = 1,
};
pub const PGF_CALCHEIGHT = NMPGCALCSIZE_FLAGS.HEIGHT;
pub const PGF_CALCWIDTH = NMPGCALCSIZE_FLAGS.WIDTH;
pub const ENDCOMPOSITIONNOTIFY_CODE = enum(u32) {
ENDCOMPOSITION = 1,
NEWTEXT = 2,
};
pub const ECN_ENDCOMPOSITION = ENDCOMPOSITIONNOTIFY_CODE.ENDCOMPOSITION;
pub const ECN_NEWTEXT = ENDCOMPOSITIONNOTIFY_CODE.NEWTEXT;
pub const NMLVCUSTOMDRAW_ALIGN = enum(u32) {
CENTER = 2,
LEFT = 1,
RIGHT = 4,
};
pub const LVGA_HEADER_CENTER = NMLVCUSTOMDRAW_ALIGN.CENTER;
pub const LVGA_HEADER_LEFT = NMLVCUSTOMDRAW_ALIGN.LEFT;
pub const LVGA_HEADER_RIGHT = NMLVCUSTOMDRAW_ALIGN.RIGHT;
pub const IMECOMPTEXT_FLAGS = enum(u32) {
R = 1,
};
pub const ICT_RESULTREADSTR = IMECOMPTEXT_FLAGS.R;
pub const MCGRIDINFO_FLAGS = enum(u32) {
DATE = 1,
RECT = 2,
NAME = 4,
_,
pub fn initFlags(o: struct {
DATE: u1 = 0,
RECT: u1 = 0,
NAME: u1 = 0,
}) MCGRIDINFO_FLAGS {
return @intToEnum(MCGRIDINFO_FLAGS,
(if (o.DATE == 1) @enumToInt(MCGRIDINFO_FLAGS.DATE) else 0)
| (if (o.RECT == 1) @enumToInt(MCGRIDINFO_FLAGS.RECT) else 0)
| (if (o.NAME == 1) @enumToInt(MCGRIDINFO_FLAGS.NAME) else 0)
);
}
};
pub const MCGIF_DATE = MCGRIDINFO_FLAGS.DATE;
pub const MCGIF_RECT = MCGRIDINFO_FLAGS.RECT;
pub const MCGIF_NAME = MCGRIDINFO_FLAGS.NAME;
pub const GETTEXTLENGTHEX_FLAGS = enum(u32) {
DEFAULT = 0,
USECRLF = 1,
PRECISE = 2,
CLOSE = 4,
NUMCHARS = 8,
NUMBYTES = 16,
_,
pub fn initFlags(o: struct {
DEFAULT: u1 = 0,
USECRLF: u1 = 0,
PRECISE: u1 = 0,
CLOSE: u1 = 0,
NUMCHARS: u1 = 0,
NUMBYTES: u1 = 0,
}) GETTEXTLENGTHEX_FLAGS {
return @intToEnum(GETTEXTLENGTHEX_FLAGS,
(if (o.DEFAULT == 1) @enumToInt(GETTEXTLENGTHEX_FLAGS.DEFAULT) else 0)
| (if (o.USECRLF == 1) @enumToInt(GETTEXTLENGTHEX_FLAGS.USECRLF) else 0)
| (if (o.PRECISE == 1) @enumToInt(GETTEXTLENGTHEX_FLAGS.PRECISE) else 0)
| (if (o.CLOSE == 1) @enumToInt(GETTEXTLENGTHEX_FLAGS.CLOSE) else 0)
| (if (o.NUMCHARS == 1) @enumToInt(GETTEXTLENGTHEX_FLAGS.NUMCHARS) else 0)
| (if (o.NUMBYTES == 1) @enumToInt(GETTEXTLENGTHEX_FLAGS.NUMBYTES) else 0)
);
}
};
pub const GTL_DEFAULT = GETTEXTLENGTHEX_FLAGS.DEFAULT;
pub const GTL_USECRLF = GETTEXTLENGTHEX_FLAGS.USECRLF;
pub const GTL_PRECISE = GETTEXTLENGTHEX_FLAGS.PRECISE;
pub const GTL_CLOSE = GETTEXTLENGTHEX_FLAGS.CLOSE;
pub const GTL_NUMCHARS = GETTEXTLENGTHEX_FLAGS.NUMCHARS;
pub const GTL_NUMBYTES = GETTEXTLENGTHEX_FLAGS.NUMBYTES;
pub const LVHITTESTINFO_FLAGS = enum(u32) {
ABOVE = 8,
BELOW = 16,
NOWHERE = 1,
ONITEMICON = 2,
ONITEMLABEL = 4,
// ONITEMSTATEICON = 8, this enum value conflicts with ABOVE
TOLEFT = 64,
TORIGHT = 32,
EX_GROUP_HEADER = 268435456,
EX_GROUP_FOOTER = 536870912,
EX_GROUP_COLLAPSE = 1073741824,
EX_GROUP_BACKGROUND = 2147483648,
EX_GROUP_STATEICON = 16777216,
EX_GROUP_SUBSETLINK = 33554432,
EX_GROUP = 4076863488,
EX_ONCONTENTS = 67108864,
EX_FOOTER = 134217728,
_,
pub fn initFlags(o: struct {
ABOVE: u1 = 0,
BELOW: u1 = 0,
NOWHERE: u1 = 0,
ONITEMICON: u1 = 0,
ONITEMLABEL: u1 = 0,
TOLEFT: u1 = 0,
TORIGHT: u1 = 0,
EX_GROUP_HEADER: u1 = 0,
EX_GROUP_FOOTER: u1 = 0,
EX_GROUP_COLLAPSE: u1 = 0,
EX_GROUP_BACKGROUND: u1 = 0,
EX_GROUP_STATEICON: u1 = 0,
EX_GROUP_SUBSETLINK: u1 = 0,
EX_GROUP: u1 = 0,
EX_ONCONTENTS: u1 = 0,
EX_FOOTER: u1 = 0,
}) LVHITTESTINFO_FLAGS {
return @intToEnum(LVHITTESTINFO_FLAGS,
(if (o.ABOVE == 1) @enumToInt(LVHITTESTINFO_FLAGS.ABOVE) else 0)
| (if (o.BELOW == 1) @enumToInt(LVHITTESTINFO_FLAGS.BELOW) else 0)
| (if (o.NOWHERE == 1) @enumToInt(LVHITTESTINFO_FLAGS.NOWHERE) else 0)
| (if (o.ONITEMICON == 1) @enumToInt(LVHITTESTINFO_FLAGS.ONITEMICON) else 0)
| (if (o.ONITEMLABEL == 1) @enumToInt(LVHITTESTINFO_FLAGS.ONITEMLABEL) else 0)
| (if (o.TOLEFT == 1) @enumToInt(LVHITTESTINFO_FLAGS.TOLEFT) else 0)
| (if (o.TORIGHT == 1) @enumToInt(LVHITTESTINFO_FLAGS.TORIGHT) else 0)
| (if (o.EX_GROUP_HEADER == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_GROUP_HEADER) else 0)
| (if (o.EX_GROUP_FOOTER == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_GROUP_FOOTER) else 0)
| (if (o.EX_GROUP_COLLAPSE == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_GROUP_COLLAPSE) else 0)
| (if (o.EX_GROUP_BACKGROUND == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_GROUP_BACKGROUND) else 0)
| (if (o.EX_GROUP_STATEICON == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_GROUP_STATEICON) else 0)
| (if (o.EX_GROUP_SUBSETLINK == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_GROUP_SUBSETLINK) else 0)
| (if (o.EX_GROUP == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_GROUP) else 0)
| (if (o.EX_ONCONTENTS == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_ONCONTENTS) else 0)
| (if (o.EX_FOOTER == 1) @enumToInt(LVHITTESTINFO_FLAGS.EX_FOOTER) else 0)
);
}
};
pub const LVHT_ABOVE = LVHITTESTINFO_FLAGS.ABOVE;
pub const LVHT_BELOW = LVHITTESTINFO_FLAGS.BELOW;
pub const LVHT_NOWHERE = LVHITTESTINFO_FLAGS.NOWHERE;
pub const LVHT_ONITEMICON = LVHITTESTINFO_FLAGS.ONITEMICON;
pub const LVHT_ONITEMLABEL = LVHITTESTINFO_FLAGS.ONITEMLABEL;
pub const LVHT_ONITEMSTATEICON = LVHITTESTINFO_FLAGS.ABOVE;
pub const LVHT_TOLEFT = LVHITTESTINFO_FLAGS.TOLEFT;
pub const LVHT_TORIGHT = LVHITTESTINFO_FLAGS.TORIGHT;
pub const LVHT_EX_GROUP_HEADER = LVHITTESTINFO_FLAGS.EX_GROUP_HEADER;
pub const LVHT_EX_GROUP_FOOTER = LVHITTESTINFO_FLAGS.EX_GROUP_FOOTER;
pub const LVHT_EX_GROUP_COLLAPSE = LVHITTESTINFO_FLAGS.EX_GROUP_COLLAPSE;
pub const LVHT_EX_GROUP_BACKGROUND = LVHITTESTINFO_FLAGS.EX_GROUP_BACKGROUND;
pub const LVHT_EX_GROUP_STATEICON = LVHITTESTINFO_FLAGS.EX_GROUP_STATEICON;
pub const LVHT_EX_GROUP_SUBSETLINK = LVHITTESTINFO_FLAGS.EX_GROUP_SUBSETLINK;
pub const LVHT_EX_GROUP = LVHITTESTINFO_FLAGS.EX_GROUP;
pub const LVHT_EX_ONCONTENTS = LVHITTESTINFO_FLAGS.EX_ONCONTENTS;
pub const LVHT_EX_FOOTER = LVHITTESTINFO_FLAGS.EX_FOOTER;
pub const INITCOMMONCONTROLSEX_ICC = enum(u32) {
ANIMATE_CLASS = 128,
BAR_CLASSES = 4,
COOL_CLASSES = 1024,
DATE_CLASSES = 256,
HOTKEY_CLASS = 64,
INTERNET_CLASSES = 2048,
LINK_CLASS = 32768,
LISTVIEW_CLASSES = 1,
NATIVEFNTCTL_CLASS = 8192,
PAGESCROLLER_CLASS = 4096,
PROGRESS_CLASS = 32,
STANDARD_CLASSES = 16384,
TAB_CLASSES = 8,
TREEVIEW_CLASSES = 2,
UPDOWN_CLASS = 16,
USEREX_CLASSES = 512,
WIN95_CLASSES = 255,
_,
pub fn initFlags(o: struct {
ANIMATE_CLASS: u1 = 0,
BAR_CLASSES: u1 = 0,
COOL_CLASSES: u1 = 0,
DATE_CLASSES: u1 = 0,
HOTKEY_CLASS: u1 = 0,
INTERNET_CLASSES: u1 = 0,
LINK_CLASS: u1 = 0,
LISTVIEW_CLASSES: u1 = 0,
NATIVEFNTCTL_CLASS: u1 = 0,
PAGESCROLLER_CLASS: u1 = 0,
PROGRESS_CLASS: u1 = 0,
STANDARD_CLASSES: u1 = 0,
TAB_CLASSES: u1 = 0,
TREEVIEW_CLASSES: u1 = 0,
UPDOWN_CLASS: u1 = 0,
USEREX_CLASSES: u1 = 0,
WIN95_CLASSES: u1 = 0,
}) INITCOMMONCONTROLSEX_ICC {
return @intToEnum(INITCOMMONCONTROLSEX_ICC,
(if (o.ANIMATE_CLASS == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.ANIMATE_CLASS) else 0)
| (if (o.BAR_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.BAR_CLASSES) else 0)
| (if (o.COOL_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.COOL_CLASSES) else 0)
| (if (o.DATE_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.DATE_CLASSES) else 0)
| (if (o.HOTKEY_CLASS == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.HOTKEY_CLASS) else 0)
| (if (o.INTERNET_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.INTERNET_CLASSES) else 0)
| (if (o.LINK_CLASS == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.LINK_CLASS) else 0)
| (if (o.LISTVIEW_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.LISTVIEW_CLASSES) else 0)
| (if (o.NATIVEFNTCTL_CLASS == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.NATIVEFNTCTL_CLASS) else 0)
| (if (o.PAGESCROLLER_CLASS == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.PAGESCROLLER_CLASS) else 0)
| (if (o.PROGRESS_CLASS == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.PROGRESS_CLASS) else 0)
| (if (o.STANDARD_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.STANDARD_CLASSES) else 0)
| (if (o.TAB_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.TAB_CLASSES) else 0)
| (if (o.TREEVIEW_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.TREEVIEW_CLASSES) else 0)
| (if (o.UPDOWN_CLASS == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.UPDOWN_CLASS) else 0)
| (if (o.USEREX_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.USEREX_CLASSES) else 0)
| (if (o.WIN95_CLASSES == 1) @enumToInt(INITCOMMONCONTROLSEX_ICC.WIN95_CLASSES) else 0)
);
}
};
pub const ICC_ANIMATE_CLASS = INITCOMMONCONTROLSEX_ICC.ANIMATE_CLASS;
pub const ICC_BAR_CLASSES = INITCOMMONCONTROLSEX_ICC.BAR_CLASSES;
pub const ICC_COOL_CLASSES = INITCOMMONCONTROLSEX_ICC.COOL_CLASSES;
pub const ICC_DATE_CLASSES = INITCOMMONCONTROLSEX_ICC.DATE_CLASSES;
pub const ICC_HOTKEY_CLASS = INITCOMMONCONTROLSEX_ICC.HOTKEY_CLASS;
pub const ICC_INTERNET_CLASSES = INITCOMMONCONTROLSEX_ICC.INTERNET_CLASSES;
pub const ICC_LINK_CLASS = INITCOMMONCONTROLSEX_ICC.LINK_CLASS;
pub const ICC_LISTVIEW_CLASSES = INITCOMMONCONTROLSEX_ICC.LISTVIEW_CLASSES;
pub const ICC_NATIVEFNTCTL_CLASS = INITCOMMONCONTROLSEX_ICC.NATIVEFNTCTL_CLASS;
pub const ICC_PAGESCROLLER_CLASS = INITCOMMONCONTROLSEX_ICC.PAGESCROLLER_CLASS;
pub const ICC_PROGRESS_CLASS = INITCOMMONCONTROLSEX_ICC.PROGRESS_CLASS;
pub const ICC_STANDARD_CLASSES = INITCOMMONCONTROLSEX_ICC.STANDARD_CLASSES;
pub const ICC_TAB_CLASSES = INITCOMMONCONTROLSEX_ICC.TAB_CLASSES;
pub const ICC_TREEVIEW_CLASSES = INITCOMMONCONTROLSEX_ICC.TREEVIEW_CLASSES;
pub const ICC_UPDOWN_CLASS = INITCOMMONCONTROLSEX_ICC.UPDOWN_CLASS;
pub const ICC_USEREX_CLASSES = INITCOMMONCONTROLSEX_ICC.USEREX_CLASSES;
pub const ICC_WIN95_CLASSES = INITCOMMONCONTROLSEX_ICC.WIN95_CLASSES;
pub const NMLVCUSTOMDRAW_ITEM_TYPE = enum(u32) {
ITEM = 0,
GROUP = 1,
ITEMSLIST = 2,
};
pub const LVCDI_ITEM = NMLVCUSTOMDRAW_ITEM_TYPE.ITEM;
pub const LVCDI_GROUP = NMLVCUSTOMDRAW_ITEM_TYPE.GROUP;
pub const LVCDI_ITEMSLIST = NMLVCUSTOMDRAW_ITEM_TYPE.ITEMSLIST;
pub const NMTBDISPINFOW_MASK = enum(u32) {
IMAGE = 1,
TEXT = 2,
DI_SETITEM = 268435456,
_,
pub fn initFlags(o: struct {
IMAGE: u1 = 0,
TEXT: u1 = 0,
DI_SETITEM: u1 = 0,
}) NMTBDISPINFOW_MASK {
return @intToEnum(NMTBDISPINFOW_MASK,
(if (o.IMAGE == 1) @enumToInt(NMTBDISPINFOW_MASK.IMAGE) else 0)
| (if (o.TEXT == 1) @enumToInt(NMTBDISPINFOW_MASK.TEXT) else 0)
| (if (o.DI_SETITEM == 1) @enumToInt(NMTBDISPINFOW_MASK.DI_SETITEM) else 0)
);
}
};
pub const TBNF_IMAGE = NMTBDISPINFOW_MASK.IMAGE;
pub const TBNF_TEXT = NMTBDISPINFOW_MASK.TEXT;
pub const TBNF_DI_SETITEM = NMTBDISPINFOW_MASK.DI_SETITEM;
pub const SCROLLINFO_MASK = enum(u32) {
ALL = 23,
DISABLENOSCROLL = 8,
PAGE = 2,
POS = 4,
RANGE = 1,
TRACKPOS = 16,
_,
pub fn initFlags(o: struct {
ALL: u1 = 0,
DISABLENOSCROLL: u1 = 0,
PAGE: u1 = 0,
POS: u1 = 0,
RANGE: u1 = 0,
TRACKPOS: u1 = 0,
}) SCROLLINFO_MASK {
return @intToEnum(SCROLLINFO_MASK,
(if (o.ALL == 1) @enumToInt(SCROLLINFO_MASK.ALL) else 0)
| (if (o.DISABLENOSCROLL == 1) @enumToInt(SCROLLINFO_MASK.DISABLENOSCROLL) else 0)
| (if (o.PAGE == 1) @enumToInt(SCROLLINFO_MASK.PAGE) else 0)
| (if (o.POS == 1) @enumToInt(SCROLLINFO_MASK.POS) else 0)
| (if (o.RANGE == 1) @enumToInt(SCROLLINFO_MASK.RANGE) else 0)
| (if (o.TRACKPOS == 1) @enumToInt(SCROLLINFO_MASK.TRACKPOS) else 0)
);
}
};
pub const SIF_ALL = SCROLLINFO_MASK.ALL;
pub const SIF_DISABLENOSCROLL = SCROLLINFO_MASK.DISABLENOSCROLL;
pub const SIF_PAGE = SCROLLINFO_MASK.PAGE;
pub const SIF_POS = SCROLLINFO_MASK.POS;
pub const SIF_RANGE = SCROLLINFO_MASK.RANGE;
pub const SIF_TRACKPOS = SCROLLINFO_MASK.TRACKPOS;
pub const REOBJECT_FLAGS = enum(u32) {
ALIGNTORIGHT = 256,
BELOWBASELINE = 2,
BLANK = 16,
CANROTATE = 128,
DONTNEEDPALETTE = 32,
DYNAMICSIZE = 8,
GETMETAFILE = 4194304,
HILITED = 16777216,
INPLACEACTIVE = 33554432,
INVERTEDSELECT = 4,
LINK = 2147483648,
LINKAVAILABLE = 8388608,
OPEN = 67108864,
OWNERDRAWSELECT = 64,
RESIZABLE = 1,
SELECTED = 134217728,
STATIC = 1073741824,
USEASBACKGROUND = 1024,
WRAPTEXTAROUND = 512,
_,
pub fn initFlags(o: struct {
ALIGNTORIGHT: u1 = 0,
BELOWBASELINE: u1 = 0,
BLANK: u1 = 0,
CANROTATE: u1 = 0,
DONTNEEDPALETTE: u1 = 0,
DYNAMICSIZE: u1 = 0,
GETMETAFILE: u1 = 0,
HILITED: u1 = 0,
INPLACEACTIVE: u1 = 0,
INVERTEDSELECT: u1 = 0,
LINK: u1 = 0,
LINKAVAILABLE: u1 = 0,
OPEN: u1 = 0,
OWNERDRAWSELECT: u1 = 0,
RESIZABLE: u1 = 0,
SELECTED: u1 = 0,
STATIC: u1 = 0,
USEASBACKGROUND: u1 = 0,
WRAPTEXTAROUND: u1 = 0,
}) REOBJECT_FLAGS {
return @intToEnum(REOBJECT_FLAGS,
(if (o.ALIGNTORIGHT == 1) @enumToInt(REOBJECT_FLAGS.ALIGNTORIGHT) else 0)
| (if (o.BELOWBASELINE == 1) @enumToInt(REOBJECT_FLAGS.BELOWBASELINE) else 0)
| (if (o.BLANK == 1) @enumToInt(REOBJECT_FLAGS.BLANK) else 0)
| (if (o.CANROTATE == 1) @enumToInt(REOBJECT_FLAGS.CANROTATE) else 0)
| (if (o.DONTNEEDPALETTE == 1) @enumToInt(REOBJECT_FLAGS.DONTNEEDPALETTE) else 0)
| (if (o.DYNAMICSIZE == 1) @enumToInt(REOBJECT_FLAGS.DYNAMICSIZE) else 0)
| (if (o.GETMETAFILE == 1) @enumToInt(REOBJECT_FLAGS.GETMETAFILE) else 0)
| (if (o.HILITED == 1) @enumToInt(REOBJECT_FLAGS.HILITED) else 0)
| (if (o.INPLACEACTIVE == 1) @enumToInt(REOBJECT_FLAGS.INPLACEACTIVE) else 0)
| (if (o.INVERTEDSELECT == 1) @enumToInt(REOBJECT_FLAGS.INVERTEDSELECT) else 0)
| (if (o.LINK == 1) @enumToInt(REOBJECT_FLAGS.LINK) else 0)
| (if (o.LINKAVAILABLE == 1) @enumToInt(REOBJECT_FLAGS.LINKAVAILABLE) else 0)
| (if (o.OPEN == 1) @enumToInt(REOBJECT_FLAGS.OPEN) else 0)
| (if (o.OWNERDRAWSELECT == 1) @enumToInt(REOBJECT_FLAGS.OWNERDRAWSELECT) else 0)
| (if (o.RESIZABLE == 1) @enumToInt(REOBJECT_FLAGS.RESIZABLE) else 0)
| (if (o.SELECTED == 1) @enumToInt(REOBJECT_FLAGS.SELECTED) else 0)
| (if (o.STATIC == 1) @enumToInt(REOBJECT_FLAGS.STATIC) else 0)
| (if (o.USEASBACKGROUND == 1) @enumToInt(REOBJECT_FLAGS.USEASBACKGROUND) else 0)
| (if (o.WRAPTEXTAROUND == 1) @enumToInt(REOBJECT_FLAGS.WRAPTEXTAROUND) else 0)
);
}
};
pub const REO_ALIGNTORIGHT = REOBJECT_FLAGS.ALIGNTORIGHT;
pub const REO_BELOWBASELINE = REOBJECT_FLAGS.BELOWBASELINE;
pub const REO_BLANK = REOBJECT_FLAGS.BLANK;
pub const REO_CANROTATE = REOBJECT_FLAGS.CANROTATE;
pub const REO_DONTNEEDPALETTE = REOBJECT_FLAGS.DONTNEEDPALETTE;
pub const REO_DYNAMICSIZE = REOBJECT_FLAGS.DYNAMICSIZE;
pub const REO_GETMETAFILE = REOBJECT_FLAGS.GETMETAFILE;
pub const REO_HILITED = REOBJECT_FLAGS.HILITED;
pub const REO_INPLACEACTIVE = REOBJECT_FLAGS.INPLACEACTIVE;
pub const REO_INVERTEDSELECT = REOBJECT_FLAGS.INVERTEDSELECT;
pub const REO_LINK = REOBJECT_FLAGS.LINK;
pub const REO_LINKAVAILABLE = REOBJECT_FLAGS.LINKAVAILABLE;
pub const REO_OPEN = REOBJECT_FLAGS.OPEN;
pub const REO_OWNERDRAWSELECT = REOBJECT_FLAGS.OWNERDRAWSELECT;
pub const REO_RESIZABLE = REOBJECT_FLAGS.RESIZABLE;
pub const REO_SELECTED = REOBJECT_FLAGS.SELECTED;
pub const REO_STATIC = REOBJECT_FLAGS.STATIC;
pub const REO_USEASBACKGROUND = REOBJECT_FLAGS.USEASBACKGROUND;
pub const REO_WRAPTEXTAROUND = REOBJECT_FLAGS.WRAPTEXTAROUND;
pub const NMLVEMPTYMARKUP_FLAGS = enum(u32) {
D = 1,
};
pub const EMF_CENTERED = NMLVEMPTYMARKUP_FLAGS.D;
pub const PARAFORMAT_NUMBERING_STYLE = enum(u16) {
PAREN = 0,
PARENS = 256,
PERIOD = 512,
PLAIN = 768,
NONUMBER = 1024,
NEWNUMBER = 32768,
};
pub const PFNS_PAREN = PARAFORMAT_NUMBERING_STYLE.PAREN;
pub const PFNS_PARENS = PARAFORMAT_NUMBERING_STYLE.PARENS;
pub const PFNS_PERIOD = PARAFORMAT_NUMBERING_STYLE.PERIOD;
pub const PFNS_PLAIN = PARAFORMAT_NUMBERING_STYLE.PLAIN;
pub const PFNS_NONUMBER = PARAFORMAT_NUMBERING_STYLE.NONUMBER;
pub const PFNS_NEWNUMBER = PARAFORMAT_NUMBERING_STYLE.NEWNUMBER;
pub const LVFOOTERITEM_MASK = enum(u32) {
TEXT = 1,
STATE = 2,
};
pub const LVFIF_TEXT = LVFOOTERITEM_MASK.TEXT;
pub const LVFIF_STATE = LVFOOTERITEM_MASK.STATE;
pub const PARAFORMAT_ALIGNMENT = enum(u16) {
CENTER = 3,
LEFT = 1,
RIGHT = 2,
};
pub const PFA_CENTER = PARAFORMAT_ALIGNMENT.CENTER;
pub const PFA_LEFT = PARAFORMAT_ALIGNMENT.LEFT;
pub const PFA_RIGHT = PARAFORMAT_ALIGNMENT.RIGHT;
pub const IMAGELIST_CREATION_FLAGS = enum(u32) {
MASK = 1,
COLOR = 0,
COLORDDB = 254,
COLOR4 = 4,
COLOR8 = 8,
COLOR16 = 16,
COLOR24 = 24,
COLOR32 = 32,
PALETTE = 2048,
MIRROR = 8192,
PERITEMMIRROR = 32768,
ORIGINALSIZE = 65536,
HIGHQUALITYSCALE = 131072,
_,
pub fn initFlags(o: struct {
MASK: u1 = 0,
COLOR: u1 = 0,
COLORDDB: u1 = 0,
COLOR4: u1 = 0,
COLOR8: u1 = 0,
COLOR16: u1 = 0,
COLOR24: u1 = 0,
COLOR32: u1 = 0,
PALETTE: u1 = 0,
MIRROR: u1 = 0,
PERITEMMIRROR: u1 = 0,
ORIGINALSIZE: u1 = 0,
HIGHQUALITYSCALE: u1 = 0,
}) IMAGELIST_CREATION_FLAGS {
return @intToEnum(IMAGELIST_CREATION_FLAGS,
(if (o.MASK == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.MASK) else 0)
| (if (o.COLOR == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.COLOR) else 0)
| (if (o.COLORDDB == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.COLORDDB) else 0)
| (if (o.COLOR4 == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.COLOR4) else 0)
| (if (o.COLOR8 == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.COLOR8) else 0)
| (if (o.COLOR16 == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.COLOR16) else 0)
| (if (o.COLOR24 == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.COLOR24) else 0)
| (if (o.COLOR32 == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.COLOR32) else 0)
| (if (o.PALETTE == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.PALETTE) else 0)
| (if (o.MIRROR == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.MIRROR) else 0)
| (if (o.PERITEMMIRROR == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.PERITEMMIRROR) else 0)
| (if (o.ORIGINALSIZE == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.ORIGINALSIZE) else 0)
| (if (o.HIGHQUALITYSCALE == 1) @enumToInt(IMAGELIST_CREATION_FLAGS.HIGHQUALITYSCALE) else 0)
);
}
};
pub const ILC_MASK = IMAGELIST_CREATION_FLAGS.MASK;
pub const ILC_COLOR = IMAGELIST_CREATION_FLAGS.COLOR;
pub const ILC_COLORDDB = IMAGELIST_CREATION_FLAGS.COLORDDB;
pub const ILC_COLOR4 = IMAGELIST_CREATION_FLAGS.COLOR4;
pub const ILC_COLOR8 = IMAGELIST_CREATION_FLAGS.COLOR8;
pub const ILC_COLOR16 = IMAGELIST_CREATION_FLAGS.COLOR16;
pub const ILC_COLOR24 = IMAGELIST_CREATION_FLAGS.COLOR24;
pub const ILC_COLOR32 = IMAGELIST_CREATION_FLAGS.COLOR32;
pub const ILC_PALETTE = IMAGELIST_CREATION_FLAGS.PALETTE;
pub const ILC_MIRROR = IMAGELIST_CREATION_FLAGS.MIRROR;
pub const ILC_PERITEMMIRROR = IMAGELIST_CREATION_FLAGS.PERITEMMIRROR;
pub const ILC_ORIGINALSIZE = IMAGELIST_CREATION_FLAGS.ORIGINALSIZE;
pub const ILC_HIGHQUALITYSCALE = IMAGELIST_CREATION_FLAGS.HIGHQUALITYSCALE;
pub const _IMAGELIST = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const _TREEITEM = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const _DSA = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
pub const _DPA = extern struct {
placeholder: usize, // TODO: why is this type empty?
};
// TODO: this type has a FreeFunc 'DestroyPropertySheetPage', what can Zig do with this information?
pub const HPROPSHEETPAGE = *opaque{};
// TODO: this type has a FreeFunc 'ImageList_Destroy', what can Zig do with this information?
pub const HIMAGELIST = *opaque{};
pub const HSYNTHETICPOINTERDEVICE = *opaque{};
pub const HTREEITEM = *opaque{};
pub const LPFNPSPCALLBACKA = fn(
hwnd: ?HWND,
uMsg: PSPCB_MESSAGE,
ppsp: ?*PROPSHEETPAGEA,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const LPFNPSPCALLBACKW = fn(
hwnd: ?HWND,
uMsg: PSPCB_MESSAGE,
ppsp: ?*PROPSHEETPAGEW,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PROPSHEETPAGEA_V1 = extern struct {
dwSize: u32,
dwFlags: u32,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
pszTemplate: ?[*:0]const u8,
pResource: ?*DLGTEMPLATE,
},
Anonymous2: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u8,
},
pszTitle: ?[*:0]const u8,
pfnDlgProc: ?DLGPROC,
lParam: LPARAM,
pfnCallback: ?LPFNPSPCALLBACKA,
pcRefParent: ?*u32,
};
pub const PROPSHEETPAGEA_V2 = extern struct {
dwSize: u32,
dwFlags: u32,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
pszTemplate: ?[*:0]const u8,
pResource: ?*DLGTEMPLATE,
},
Anonymous2: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u8,
},
pszTitle: ?[*:0]const u8,
pfnDlgProc: ?DLGPROC,
lParam: LPARAM,
pfnCallback: ?LPFNPSPCALLBACKA,
pcRefParent: ?*u32,
pszHeaderTitle: ?[*:0]const u8,
pszHeaderSubTitle: ?[*:0]const u8,
};
pub const PROPSHEETPAGEA_V3 = extern struct {
dwSize: u32,
dwFlags: u32,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
pszTemplate: ?[*:0]const u8,
pResource: ?*DLGTEMPLATE,
},
Anonymous2: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u8,
},
pszTitle: ?[*:0]const u8,
pfnDlgProc: ?DLGPROC,
lParam: LPARAM,
pfnCallback: ?LPFNPSPCALLBACKA,
pcRefParent: ?*u32,
pszHeaderTitle: ?[*:0]const u8,
pszHeaderSubTitle: ?[*:0]const u8,
hActCtx: ?HANDLE,
};
pub const PROPSHEETPAGEA = extern struct {
dwSize: u32,
dwFlags: u32,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
pszTemplate: ?[*:0]const u8,
pResource: ?*DLGTEMPLATE,
},
Anonymous2: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u8,
},
pszTitle: ?[*:0]const u8,
pfnDlgProc: ?DLGPROC,
lParam: LPARAM,
pfnCallback: ?LPFNPSPCALLBACKA,
pcRefParent: ?*u32,
pszHeaderTitle: ?[*:0]const u8,
pszHeaderSubTitle: ?[*:0]const u8,
hActCtx: ?HANDLE,
Anonymous3: extern union {
hbmHeader: ?HBITMAP,
pszbmHeader: ?[*:0]const u8,
},
};
pub const PROPSHEETPAGEW_V1 = extern struct {
dwSize: u32,
dwFlags: u32,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
pszTemplate: ?[*:0]const u16,
pResource: ?*DLGTEMPLATE,
},
Anonymous2: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u16,
},
pszTitle: ?[*:0]const u16,
pfnDlgProc: ?DLGPROC,
lParam: LPARAM,
pfnCallback: ?LPFNPSPCALLBACKW,
pcRefParent: ?*u32,
};
pub const PROPSHEETPAGEW_V2 = extern struct {
dwSize: u32,
dwFlags: u32,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
pszTemplate: ?[*:0]const u16,
pResource: ?*DLGTEMPLATE,
},
Anonymous2: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u16,
},
pszTitle: ?[*:0]const u16,
pfnDlgProc: ?DLGPROC,
lParam: LPARAM,
pfnCallback: ?LPFNPSPCALLBACKW,
pcRefParent: ?*u32,
pszHeaderTitle: ?[*:0]const u16,
pszHeaderSubTitle: ?[*:0]const u16,
};
pub const PROPSHEETPAGEW_V3 = extern struct {
dwSize: u32,
dwFlags: u32,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
pszTemplate: ?[*:0]const u16,
pResource: ?*DLGTEMPLATE,
},
Anonymous2: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u16,
},
pszTitle: ?[*:0]const u16,
pfnDlgProc: ?DLGPROC,
lParam: LPARAM,
pfnCallback: ?LPFNPSPCALLBACKW,
pcRefParent: ?*u32,
pszHeaderTitle: ?[*:0]const u16,
pszHeaderSubTitle: ?[*:0]const u16,
hActCtx: ?HANDLE,
};
pub const PROPSHEETPAGEW = extern struct {
dwSize: u32,
dwFlags: u32,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
pszTemplate: ?[*:0]const u16,
pResource: ?*DLGTEMPLATE,
},
Anonymous2: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u16,
},
pszTitle: ?[*:0]const u16,
pfnDlgProc: ?DLGPROC,
lParam: LPARAM,
pfnCallback: ?LPFNPSPCALLBACKW,
pcRefParent: ?*u32,
pszHeaderTitle: ?[*:0]const u16,
pszHeaderSubTitle: ?[*:0]const u16,
hActCtx: ?HANDLE,
Anonymous3: extern union {
hbmHeader: ?HBITMAP,
pszbmHeader: ?[*:0]const u16,
},
};
pub const PFNPROPSHEETCALLBACK = fn(
param0: ?HWND,
param1: u32,
param2: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PROPSHEETHEADERA_V1 = extern struct {
dwSize: u32,
dwFlags: u32,
hwndParent: ?HWND,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u8,
},
pszCaption: ?[*:0]const u8,
nPages: u32,
Anonymous2: extern union {
nStartPage: u32,
pStartPage: ?[*:0]const u8,
},
Anonymous3: extern union {
ppsp: ?*PROPSHEETPAGEA,
phpage: ?*?HPROPSHEETPAGE,
},
pfnCallback: ?PFNPROPSHEETCALLBACK,
};
pub const PROPSHEETHEADERA_V2 = extern struct {
dwSize: u32,
dwFlags: u32,
hwndParent: ?HWND,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u8,
},
pszCaption: ?[*:0]const u8,
nPages: u32,
Anonymous2: extern union {
nStartPage: u32,
pStartPage: ?[*:0]const u8,
},
Anonymous3: extern union {
ppsp: ?*PROPSHEETPAGEA,
phpage: ?*?HPROPSHEETPAGE,
},
pfnCallback: ?PFNPROPSHEETCALLBACK,
Anonymous4: extern union {
hbmWatermark: ?HBITMAP,
pszbmWatermark: ?[*:0]const u8,
},
hplWatermark: ?HPALETTE,
Anonymous5: extern union {
hbmHeader: ?HBITMAP,
pszbmHeader: ?[*:0]const u8,
},
};
pub const PROPSHEETHEADERW_V1 = extern struct {
dwSize: u32,
dwFlags: u32,
hwndParent: ?HWND,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u16,
},
pszCaption: ?[*:0]const u16,
nPages: u32,
Anonymous2: extern union {
nStartPage: u32,
pStartPage: ?[*:0]const u16,
},
Anonymous3: extern union {
ppsp: ?*PROPSHEETPAGEW,
phpage: ?*?HPROPSHEETPAGE,
},
pfnCallback: ?PFNPROPSHEETCALLBACK,
};
pub const PROPSHEETHEADERW_V2 = extern struct {
dwSize: u32,
dwFlags: u32,
hwndParent: ?HWND,
hInstance: ?HINSTANCE,
Anonymous1: extern union {
hIcon: ?HICON,
pszIcon: ?[*:0]const u16,
},
pszCaption: ?[*:0]const u16,
nPages: u32,
Anonymous2: extern union {
nStartPage: u32,
pStartPage: ?[*:0]const u16,
},
Anonymous3: extern union {
ppsp: ?*PROPSHEETPAGEW,
phpage: ?*?HPROPSHEETPAGE,
},
pfnCallback: ?PFNPROPSHEETCALLBACK,
Anonymous4: extern union {
hbmWatermark: ?HBITMAP,
pszbmWatermark: ?[*:0]const u16,
},
hplWatermark: ?HPALETTE,
Anonymous5: extern union {
hbmHeader: ?HBITMAP,
pszbmHeader: ?[*:0]const u16,
},
};
pub const LPFNSVADDPROPSHEETPAGE = fn(
param0: ?HPROPSHEETPAGE,
param1: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const LPFNADDPROPSHEETPAGES = fn(
param0: ?*c_void,
param1: ?LPFNSVADDPROPSHEETPAGE,
param2: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const PSHNOTIFY = extern struct {
hdr: NMHDR,
lParam: LPARAM,
};
pub const INITCOMMONCONTROLSEX = extern struct {
dwSize: u32,
dwICC: INITCOMMONCONTROLSEX_ICC,
};
pub const COLORSCHEME = extern struct {
dwSize: u32,
clrBtnHighlight: u32,
clrBtnShadow: u32,
};
pub const NMTOOLTIPSCREATED = extern struct {
hdr: NMHDR,
hwndToolTips: ?HWND,
};
pub const NMMOUSE = extern struct {
hdr: NMHDR,
dwItemSpec: usize,
dwItemData: usize,
pt: POINT,
dwHitInfo: LPARAM,
};
pub const NMOBJECTNOTIFY = extern struct {
hdr: NMHDR,
iItem: i32,
piid: ?*const Guid,
pObject: ?*c_void,
hResult: HRESULT,
dwFlags: u32,
};
pub const NMKEY = extern struct {
hdr: NMHDR,
nVKey: u32,
uFlags: u32,
};
pub const NMCHAR = extern struct {
hdr: NMHDR,
ch: u32,
dwItemPrev: u32,
dwItemNext: u32,
};
pub const NMCUSTOMTEXT = extern struct {
hdr: NMHDR,
hDC: ?HDC,
lpString: ?[*:0]const u16,
nCount: i32,
lpRect: ?*RECT,
uFormat: u32,
fLink: BOOL,
};
pub const NMCUSTOMDRAW = extern struct {
hdr: NMHDR,
dwDrawStage: NMCUSTOMDRAW_DRAW_STAGE,
hdc: ?HDC,
rc: RECT,
dwItemSpec: usize,
uItemState: u32,
lItemlParam: LPARAM,
};
pub const NMTTCUSTOMDRAW = extern struct {
nmcd: NMCUSTOMDRAW,
uDrawFlags: u32,
};
pub const NMCUSTOMSPLITRECTINFO = extern struct {
hdr: NMHDR,
rcClient: RECT,
rcButton: RECT,
rcSplit: RECT,
};
pub const IMAGELISTDRAWPARAMS = extern struct {
cbSize: u32,
himl: ?HIMAGELIST,
i: i32,
hdcDst: ?HDC,
x: i32,
y: i32,
cx: i32,
cy: i32,
xBitmap: i32,
yBitmap: i32,
rgbBk: u32,
rgbFg: u32,
fStyle: u32,
dwRop: u32,
fState: u32,
Frame: u32,
crEffect: u32,
};
pub const IMAGEINFO = extern struct {
hbmImage: ?HBITMAP,
hbmMask: ?HBITMAP,
Unused1: i32,
Unused2: i32,
rcImage: RECT,
};
pub const HD_TEXTFILTERA = extern struct {
pszText: ?PSTR,
cchTextMax: i32,
};
pub const HD_TEXTFILTERW = extern struct {
pszText: ?PWSTR,
cchTextMax: i32,
};
pub const HDITEMA = extern struct {
mask: HDI_MASK,
cxy: i32,
pszText: ?PSTR,
hbm: ?HBITMAP,
cchTextMax: i32,
fmt: i32,
lParam: LPARAM,
iImage: i32,
iOrder: i32,
type: u32,
pvFilter: ?*c_void,
state: u32,
};
pub const HDITEMW = extern struct {
mask: HDI_MASK,
cxy: i32,
pszText: ?PWSTR,
hbm: ?HBITMAP,
cchTextMax: i32,
fmt: i32,
lParam: LPARAM,
iImage: i32,
iOrder: i32,
type: u32,
pvFilter: ?*c_void,
state: u32,
};
pub const HDLAYOUT = extern struct {
prc: ?*RECT,
pwpos: ?*WINDOWPOS,
};
pub const HDHITTESTINFO = extern struct {
pt: POINT,
flags: u32,
iItem: i32,
};
pub const NMHEADERA = extern struct {
hdr: NMHDR,
iItem: i32,
iButton: HEADER_CONTROL_NOTIFICATION_BUTTON,
pitem: ?*HDITEMA,
};
pub const NMHEADERW = extern struct {
hdr: NMHDR,
iItem: i32,
iButton: HEADER_CONTROL_NOTIFICATION_BUTTON,
pitem: ?*HDITEMW,
};
pub const NMHDDISPINFOW = extern struct {
hdr: NMHDR,
iItem: i32,
mask: HDI_MASK,
pszText: ?PWSTR,
cchTextMax: i32,
iImage: i32,
lParam: LPARAM,
};
pub const NMHDDISPINFOA = extern struct {
hdr: NMHDR,
iItem: i32,
mask: HDI_MASK,
pszText: ?PSTR,
cchTextMax: i32,
iImage: i32,
lParam: LPARAM,
};
pub const NMHDFILTERBTNCLICK = extern struct {
hdr: NMHDR,
iItem: i32,
rc: RECT,
};
pub const COLORMAP = extern struct {
from: u32,
to: u32,
};
pub const NMTBCUSTOMDRAW = extern struct {
nmcd: NMCUSTOMDRAW,
hbrMonoDither: ?HBRUSH,
hbrLines: ?HBRUSH,
hpenLines: ?HPEN,
clrText: u32,
clrMark: u32,
clrTextHighlight: u32,
clrBtnFace: u32,
clrBtnHighlight: u32,
clrHighlightHotTrack: u32,
rcText: RECT,
nStringBkMode: i32,
nHLStringBkMode: i32,
iListGap: i32,
};
pub const TBADDBITMAP = extern struct {
hInst: ?HINSTANCE,
nID: usize,
};
pub const TBSAVEPARAMSA = extern struct {
hkr: ?HKEY,
pszSubKey: ?[*:0]const u8,
pszValueName: ?[*:0]const u8,
};
pub const TBSAVEPARAMSW = extern struct {
hkr: ?HKEY,
pszSubKey: ?[*:0]const u16,
pszValueName: ?[*:0]const u16,
};
pub const TBINSERTMARK = extern struct {
iButton: i32,
dwFlags: TBINSERTMARK_FLAGS,
};
pub const TBREPLACEBITMAP = extern struct {
hInstOld: ?HINSTANCE,
nIDOld: usize,
hInstNew: ?HINSTANCE,
nIDNew: usize,
nButtons: i32,
};
pub const TBBUTTONINFOA = extern struct {
cbSize: u32,
dwMask: TBBUTTONINFOW_MASK,
idCommand: i32,
iImage: i32,
fsState: u8,
fsStyle: u8,
cx: u16,
lParam: usize,
pszText: ?PSTR,
cchText: i32,
};
pub const TBBUTTONINFOW = extern struct {
cbSize: u32,
dwMask: TBBUTTONINFOW_MASK,
idCommand: i32,
iImage: i32,
fsState: u8,
fsStyle: u8,
cx: u16,
lParam: usize,
pszText: ?PWSTR,
cchText: i32,
};
pub const TBMETRICS = extern struct {
cbSize: u32,
dwMask: u32,
cxPad: i32,
cyPad: i32,
cxBarPad: i32,
cyBarPad: i32,
cxButtonSpacing: i32,
cyButtonSpacing: i32,
};
pub const NMTBHOTITEM = extern struct {
hdr: NMHDR,
idOld: i32,
idNew: i32,
dwFlags: NMTBHOTITEM_FLAGS,
};
pub const NMTBSAVE = extern struct {
hdr: NMHDR,
pData: ?*u32,
pCurrent: ?*u32,
cbData: u32,
iItem: i32,
cButtons: i32,
tbButton: TBBUTTON,
};
pub const NMTBRESTORE = extern struct {
hdr: NMHDR,
pData: ?*u32,
pCurrent: ?*u32,
cbData: u32,
iItem: i32,
cButtons: i32,
cbBytesPerRecord: i32,
tbButton: TBBUTTON,
};
pub const NMTBGETINFOTIPA = extern struct {
hdr: NMHDR,
pszText: ?PSTR,
cchTextMax: i32,
iItem: i32,
lParam: LPARAM,
};
pub const NMTBGETINFOTIPW = extern struct {
hdr: NMHDR,
pszText: ?PWSTR,
cchTextMax: i32,
iItem: i32,
lParam: LPARAM,
};
pub const NMTBDISPINFOA = extern struct {
hdr: NMHDR,
dwMask: NMTBDISPINFOW_MASK,
idCommand: i32,
lParam: usize,
iImage: i32,
pszText: ?PSTR,
cchText: i32,
};
pub const NMTBDISPINFOW = extern struct {
hdr: NMHDR,
dwMask: NMTBDISPINFOW_MASK,
idCommand: i32,
lParam: usize,
iImage: i32,
pszText: ?PWSTR,
cchText: i32,
};
pub const NMTOOLBARA = extern struct {
hdr: NMHDR,
iItem: i32,
tbButton: TBBUTTON,
cchText: i32,
pszText: ?PSTR,
rcButton: RECT,
};
pub const NMTOOLBARW = extern struct {
hdr: NMHDR,
iItem: i32,
tbButton: TBBUTTON,
cchText: i32,
pszText: ?PWSTR,
rcButton: RECT,
};
pub const REBARINFO = extern struct {
cbSize: u32,
fMask: u32,
himl: ?HIMAGELIST,
};
pub const REBARBANDINFOA = extern struct {
cbSize: u32,
fMask: u32,
fStyle: u32,
clrFore: u32,
clrBack: u32,
lpText: ?PSTR,
cch: u32,
iImage: i32,
hwndChild: ?HWND,
cxMinChild: u32,
cyMinChild: u32,
cx: u32,
hbmBack: ?HBITMAP,
wID: u32,
cyChild: u32,
cyMaxChild: u32,
cyIntegral: u32,
cxIdeal: u32,
lParam: LPARAM,
cxHeader: u32,
rcChevronLocation: RECT,
uChevronState: u32,
};
pub const REBARBANDINFOW = extern struct {
cbSize: u32,
fMask: u32,
fStyle: u32,
clrFore: u32,
clrBack: u32,
lpText: ?PWSTR,
cch: u32,
iImage: i32,
hwndChild: ?HWND,
cxMinChild: u32,
cyMinChild: u32,
cx: u32,
hbmBack: ?HBITMAP,
wID: u32,
cyChild: u32,
cyMaxChild: u32,
cyIntegral: u32,
cxIdeal: u32,
lParam: LPARAM,
cxHeader: u32,
rcChevronLocation: RECT,
uChevronState: u32,
};
pub const NMREBARCHILDSIZE = extern struct {
hdr: NMHDR,
uBand: u32,
wID: u32,
rcChild: RECT,
rcBand: RECT,
};
pub const NMREBAR = extern struct {
hdr: NMHDR,
dwMask: NMREBAR_MASK_FLAGS,
uBand: u32,
fStyle: u32,
wID: u32,
lParam: LPARAM,
};
pub const NMRBAUTOSIZE = extern struct {
hdr: NMHDR,
fChanged: BOOL,
rcTarget: RECT,
rcActual: RECT,
};
pub const NMREBARCHEVRON = extern struct {
hdr: NMHDR,
uBand: u32,
wID: u32,
lParam: LPARAM,
rc: RECT,
lParamNM: LPARAM,
};
pub const NMREBARSPLITTER = extern struct {
hdr: NMHDR,
rcSizing: RECT,
};
pub const NMREBARAUTOBREAK = extern struct {
hdr: NMHDR,
uBand: u32,
wID: u32,
lParam: LPARAM,
uMsg: u32,
fStyleCurrent: u32,
fAutoBreak: BOOL,
};
pub const RBHITTESTINFO = extern struct {
pt: POINT,
flags: u32,
iBand: i32,
};
pub const TTTOOLINFOA = extern struct {
cbSize: u32,
uFlags: TTTOOLINFO_FLAGS,
hwnd: ?HWND,
uId: usize,
rect: RECT,
hinst: ?HINSTANCE,
lpszText: ?PSTR,
lParam: LPARAM,
lpReserved: ?*c_void,
};
pub const TTTOOLINFOW = extern struct {
cbSize: u32,
uFlags: TTTOOLINFO_FLAGS,
hwnd: ?HWND,
uId: usize,
rect: RECT,
hinst: ?HINSTANCE,
lpszText: ?PWSTR,
lParam: LPARAM,
lpReserved: ?*c_void,
};
pub const TTGETTITLE = extern struct {
dwSize: u32,
uTitleBitmap: u32,
cch: u32,
pszTitle: ?PWSTR,
};
pub const TTHITTESTINFOA = extern struct {
hwnd: ?HWND,
pt: POINT,
ti: TTTOOLINFOA,
};
pub const TTHITTESTINFOW = extern struct {
hwnd: ?HWND,
pt: POINT,
ti: TTTOOLINFOW,
};
pub const NMTTDISPINFOA = extern struct {
hdr: NMHDR,
lpszText: ?PSTR,
szText: [80]CHAR,
hinst: ?HINSTANCE,
uFlags: u32,
lParam: LPARAM,
};
pub const NMTTDISPINFOW = extern struct {
hdr: NMHDR,
lpszText: ?PWSTR,
szText: [80]u16,
hinst: ?HINSTANCE,
uFlags: u32,
lParam: LPARAM,
};
pub const NMTRBTHUMBPOSCHANGING = extern struct {
hdr: NMHDR,
dwPos: u32,
nReason: i32,
};
pub const DRAGLISTINFO = extern struct {
uNotification: DRAGLISTINFO_NOTIFICATION_FLAGS,
hWnd: ?HWND,
ptCursor: POINT,
};
pub const UDACCEL = extern struct {
nSec: u32,
nInc: u32,
};
pub const NMUPDOWN = extern struct {
hdr: NMHDR,
iPos: i32,
iDelta: i32,
};
pub const PBRANGE = extern struct {
iLow: i32,
iHigh: i32,
};
pub const LITEM = extern struct {
mask: u32,
iLink: i32,
state: u32,
stateMask: u32,
szID: [48]u16,
szUrl: [2084]u16,
};
pub const LHITTESTINFO = extern struct {
pt: POINT,
item: LITEM,
};
pub const NMLINK = extern struct {
hdr: NMHDR,
item: LITEM,
};
pub const LVITEMA = extern struct {
mask: u32,
iItem: i32,
iSubItem: i32,
state: u32,
stateMask: u32,
pszText: ?PSTR,
cchTextMax: i32,
iImage: i32,
lParam: LPARAM,
iIndent: i32,
iGroupId: LVITEMA_GROUP_ID,
cColumns: u32,
puColumns: ?*u32,
piColFmt: ?*i32,
iGroup: i32,
};
pub const LVITEMW = extern struct {
mask: u32,
iItem: i32,
iSubItem: i32,
state: u32,
stateMask: u32,
pszText: ?PWSTR,
cchTextMax: i32,
iImage: i32,
lParam: LPARAM,
iIndent: i32,
iGroupId: LVITEMA_GROUP_ID,
cColumns: u32,
puColumns: ?*u32,
piColFmt: ?*i32,
iGroup: i32,
};
pub const LVFINDINFOA = extern struct {
flags: LVFINDINFOW_FLAGS,
psz: ?[*:0]const u8,
lParam: LPARAM,
pt: POINT,
vkDirection: u32,
};
pub const LVFINDINFOW = extern struct {
flags: LVFINDINFOW_FLAGS,
psz: ?[*:0]const u16,
lParam: LPARAM,
pt: POINT,
vkDirection: u32,
};
pub const LVHITTESTINFO = extern struct {
pt: POINT,
flags: LVHITTESTINFO_FLAGS,
iItem: i32,
iSubItem: i32,
iGroup: i32,
};
pub const LVCOLUMNA = extern struct {
mask: LVCOLUMNW_MASK,
fmt: LVCOLUMNW_FORMAT,
cx: i32,
pszText: ?PSTR,
cchTextMax: i32,
iSubItem: i32,
iImage: i32,
iOrder: i32,
cxMin: i32,
cxDefault: i32,
cxIdeal: i32,
};
pub const LVCOLUMNW = extern struct {
mask: LVCOLUMNW_MASK,
fmt: LVCOLUMNW_FORMAT,
cx: i32,
pszText: ?PWSTR,
cchTextMax: i32,
iSubItem: i32,
iImage: i32,
iOrder: i32,
cxMin: i32,
cxDefault: i32,
cxIdeal: i32,
};
pub const PFNLVCOMPARE = fn(
param0: LPARAM,
param1: LPARAM,
param2: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const LVBKIMAGEA = extern struct {
ulFlags: u32,
hbm: ?HBITMAP,
pszImage: ?PSTR,
cchImageMax: u32,
xOffsetPercent: i32,
yOffsetPercent: i32,
};
pub const LVBKIMAGEW = extern struct {
ulFlags: u32,
hbm: ?HBITMAP,
pszImage: ?PWSTR,
cchImageMax: u32,
xOffsetPercent: i32,
yOffsetPercent: i32,
};
pub const LVGROUP = extern struct {
cbSize: u32,
mask: LVGROUP_MASK,
pszHeader: ?PWSTR,
cchHeader: i32,
pszFooter: ?PWSTR,
cchFooter: i32,
iGroupId: i32,
stateMask: u32,
state: u32,
uAlign: u32,
pszSubtitle: ?PWSTR,
cchSubtitle: u32,
pszTask: ?PWSTR,
cchTask: u32,
pszDescriptionTop: ?PWSTR,
cchDescriptionTop: u32,
pszDescriptionBottom: ?PWSTR,
cchDescriptionBottom: u32,
iTitleImage: i32,
iExtendedImage: i32,
iFirstItem: i32,
cItems: u32,
pszSubsetTitle: ?PWSTR,
cchSubsetTitle: u32,
};
pub const LVGROUPMETRICS = extern struct {
cbSize: u32,
mask: u32,
Left: u32,
Top: u32,
Right: u32,
Bottom: u32,
crLeft: u32,
crTop: u32,
crRight: u32,
crBottom: u32,
crHeader: u32,
crFooter: u32,
};
pub const PFNLVGROUPCOMPARE = fn(
param0: i32,
param1: i32,
param2: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const LVINSERTGROUPSORTED = extern struct {
pfnGroupCompare: ?PFNLVGROUPCOMPARE,
pvData: ?*c_void,
lvGroup: LVGROUP,
};
pub const LVTILEVIEWINFO = extern struct {
cbSize: u32,
dwMask: u32,
dwFlags: LVTILEVIEWINFO_FLAGS,
sizeTile: SIZE,
cLines: i32,
rcLabelMargin: RECT,
};
pub const LVTILEINFO = extern struct {
cbSize: u32,
iItem: i32,
cColumns: u32,
puColumns: ?*u32,
piColFmt: ?*i32,
};
pub const LVINSERTMARK = extern struct {
cbSize: u32,
dwFlags: u32,
iItem: i32,
dwReserved: u32,
};
pub const LVSETINFOTIP = extern struct {
cbSize: u32,
dwFlags: u32,
pszText: ?PWSTR,
iItem: i32,
iSubItem: i32,
};
pub const LVFOOTERINFO = extern struct {
mask: u32,
pszText: ?PWSTR,
cchTextMax: i32,
cItems: u32,
};
pub const LVFOOTERITEM = extern struct {
mask: LVFOOTERITEM_MASK,
iItem: i32,
pszText: ?PWSTR,
cchTextMax: i32,
state: u32,
stateMask: u32,
};
pub const LVITEMINDEX = extern struct {
iItem: i32,
iGroup: i32,
};
pub const NMLISTVIEW = extern struct {
hdr: NMHDR,
iItem: i32,
iSubItem: i32,
uNewState: u32,
uOldState: u32,
uChanged: u32,
ptAction: POINT,
lParam: LPARAM,
};
pub const NMITEMACTIVATE = extern struct {
hdr: NMHDR,
iItem: i32,
iSubItem: i32,
uNewState: u32,
uOldState: u32,
uChanged: u32,
ptAction: POINT,
lParam: LPARAM,
uKeyFlags: u32,
};
pub const NMLVCUSTOMDRAW = extern struct {
nmcd: NMCUSTOMDRAW,
clrText: u32,
clrTextBk: u32,
iSubItem: i32,
dwItemType: NMLVCUSTOMDRAW_ITEM_TYPE,
clrFace: u32,
iIconEffect: i32,
iIconPhase: i32,
iPartId: i32,
iStateId: i32,
rcText: RECT,
uAlign: NMLVCUSTOMDRAW_ALIGN,
};
pub const NMLVCACHEHINT = extern struct {
hdr: NMHDR,
iFrom: i32,
iTo: i32,
};
pub const NMLVFINDITEMA = extern struct {
hdr: NMHDR,
iStart: i32,
lvfi: LVFINDINFOA,
};
pub const NMLVFINDITEMW = extern struct {
hdr: NMHDR,
iStart: i32,
lvfi: LVFINDINFOW,
};
pub const NMLVODSTATECHANGE = extern struct {
hdr: NMHDR,
iFrom: i32,
iTo: i32,
uNewState: u32,
uOldState: u32,
};
pub const NMLVDISPINFOA = extern struct {
hdr: NMHDR,
item: LVITEMA,
};
pub const NMLVDISPINFOW = extern struct {
hdr: NMHDR,
item: LVITEMW,
};
pub const NMLVKEYDOWN = packed struct {
hdr: NMHDR,
wVKey: u16,
flags: u32,
};
pub const NMLVLINK = extern struct {
hdr: NMHDR,
link: LITEM,
iItem: i32,
iSubItem: i32,
};
pub const NMLVGETINFOTIPA = extern struct {
hdr: NMHDR,
dwFlags: u32,
pszText: ?PSTR,
cchTextMax: i32,
iItem: i32,
iSubItem: i32,
lParam: LPARAM,
};
pub const NMLVGETINFOTIPW = extern struct {
hdr: NMHDR,
dwFlags: u32,
pszText: ?PWSTR,
cchTextMax: i32,
iItem: i32,
iSubItem: i32,
lParam: LPARAM,
};
pub const NMLVSCROLL = extern struct {
hdr: NMHDR,
dx: i32,
dy: i32,
};
pub const NMLVEMPTYMARKUP = extern struct {
hdr: NMHDR,
dwFlags: NMLVEMPTYMARKUP_FLAGS,
szMarkup: [2084]u16,
};
pub const NMTVSTATEIMAGECHANGING = extern struct {
hdr: NMHDR,
hti: ?*_TREEITEM,
iOldStateImageIndex: i32,
iNewStateImageIndex: i32,
};
pub const TVITEMA = extern struct {
mask: TVITEM_MASK,
hItem: ?*_TREEITEM,
state: u32,
stateMask: u32,
pszText: ?PSTR,
cchTextMax: i32,
iImage: i32,
iSelectedImage: i32,
cChildren: TVITEMEXW_CHILDREN,
lParam: LPARAM,
};
pub const TVITEMW = extern struct {
mask: TVITEM_MASK,
hItem: ?*_TREEITEM,
state: u32,
stateMask: u32,
pszText: ?PWSTR,
cchTextMax: i32,
iImage: i32,
iSelectedImage: i32,
cChildren: TVITEMEXW_CHILDREN,
lParam: LPARAM,
};
pub const TVITEMEXA = extern struct {
mask: TVITEM_MASK,
hItem: ?*_TREEITEM,
state: u32,
stateMask: u32,
pszText: ?PSTR,
cchTextMax: i32,
iImage: i32,
iSelectedImage: i32,
cChildren: TVITEMEXW_CHILDREN,
lParam: LPARAM,
iIntegral: i32,
uStateEx: u32,
hwnd: ?HWND,
iExpandedImage: i32,
iReserved: i32,
};
pub const TVITEMEXW = extern struct {
mask: TVITEM_MASK,
hItem: ?*_TREEITEM,
state: u32,
stateMask: u32,
pszText: ?PWSTR,
cchTextMax: i32,
iImage: i32,
iSelectedImage: i32,
cChildren: TVITEMEXW_CHILDREN,
lParam: LPARAM,
iIntegral: i32,
uStateEx: u32,
hwnd: ?HWND,
iExpandedImage: i32,
iReserved: i32,
};
pub const TVINSERTSTRUCTA = extern struct {
hParent: ?*_TREEITEM,
hInsertAfter: ?*_TREEITEM,
Anonymous: extern union {
itemex: TVITEMEXA,
item: TVITEMA,
},
};
pub const TVINSERTSTRUCTW = extern struct {
hParent: ?*_TREEITEM,
hInsertAfter: ?*_TREEITEM,
Anonymous: extern union {
itemex: TVITEMEXW,
item: TVITEMW,
},
};
pub const TVHITTESTINFO = extern struct {
pt: POINT,
flags: TVHITTESTINFO_FLAGS,
hItem: ?*_TREEITEM,
};
pub const TVITEMPART = enum(i32) {
N = 1,
};
pub const TVGIPR_BUTTON = TVITEMPART.N;
pub const TVGETITEMPARTRECTINFO = extern struct {
hti: ?*_TREEITEM,
prc: ?*RECT,
partID: TVITEMPART,
};
pub const PFNTVCOMPARE = fn(
lParam1: LPARAM,
lParam2: LPARAM,
lParamSort: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const TVSORTCB = extern struct {
hParent: ?*_TREEITEM,
lpfnCompare: ?PFNTVCOMPARE,
lParam: LPARAM,
};
pub const NMTREEVIEWA = extern struct {
hdr: NMHDR,
action: u32,
itemOld: TVITEMA,
itemNew: TVITEMA,
ptDrag: POINT,
};
pub const NMTREEVIEWW = extern struct {
hdr: NMHDR,
action: u32,
itemOld: TVITEMW,
itemNew: TVITEMW,
ptDrag: POINT,
};
pub const NMTVDISPINFOA = extern struct {
hdr: NMHDR,
item: TVITEMA,
};
pub const NMTVDISPINFOW = extern struct {
hdr: NMHDR,
item: TVITEMW,
};
pub const NMTVDISPINFOEXA = extern struct {
hdr: NMHDR,
item: TVITEMEXA,
};
pub const NMTVDISPINFOEXW = extern struct {
hdr: NMHDR,
item: TVITEMEXW,
};
pub const NMTVKEYDOWN = packed struct {
hdr: NMHDR,
wVKey: u16,
flags: u32,
};
pub const NMTVCUSTOMDRAW = extern struct {
nmcd: NMCUSTOMDRAW,
clrText: u32,
clrTextBk: u32,
iLevel: i32,
};
pub const NMTVGETINFOTIPA = extern struct {
hdr: NMHDR,
pszText: ?PSTR,
cchTextMax: i32,
hItem: ?*_TREEITEM,
lParam: LPARAM,
};
pub const NMTVGETINFOTIPW = extern struct {
hdr: NMHDR,
pszText: ?PWSTR,
cchTextMax: i32,
hItem: ?*_TREEITEM,
lParam: LPARAM,
};
pub const NMTVITEMCHANGE = extern struct {
hdr: NMHDR,
uChanged: u32,
hItem: ?*_TREEITEM,
uStateNew: u32,
uStateOld: u32,
lParam: LPARAM,
};
pub const NMTVASYNCDRAW = extern struct {
hdr: NMHDR,
pimldp: ?*IMAGELISTDRAWPARAMS,
hr: HRESULT,
hItem: ?*_TREEITEM,
lParam: LPARAM,
dwRetFlags: u32,
iRetImageIndex: i32,
};
pub const COMBOBOXEXITEMA = extern struct {
mask: COMBOBOX_EX_ITEM_FLAGS,
iItem: isize,
pszText: ?PSTR,
cchTextMax: i32,
iImage: i32,
iSelectedImage: i32,
iOverlay: i32,
iIndent: i32,
lParam: LPARAM,
};
pub const COMBOBOXEXITEMW = extern struct {
mask: COMBOBOX_EX_ITEM_FLAGS,
iItem: isize,
pszText: ?PWSTR,
cchTextMax: i32,
iImage: i32,
iSelectedImage: i32,
iOverlay: i32,
iIndent: i32,
lParam: LPARAM,
};
pub const NMCOMBOBOXEXA = extern struct {
hdr: NMHDR,
ceItem: COMBOBOXEXITEMA,
};
pub const NMCOMBOBOXEXW = extern struct {
hdr: NMHDR,
ceItem: COMBOBOXEXITEMW,
};
pub const NMCBEDRAGBEGINW = extern struct {
hdr: NMHDR,
iItemid: i32,
szText: [260]u16,
};
pub const NMCBEDRAGBEGINA = extern struct {
hdr: NMHDR,
iItemid: i32,
szText: [260]CHAR,
};
pub const NMCBEENDEDITW = extern struct {
hdr: NMHDR,
fChanged: BOOL,
iNewSelection: i32,
szText: [260]u16,
iWhy: i32,
};
pub const NMCBEENDEDITA = extern struct {
hdr: NMHDR,
fChanged: BOOL,
iNewSelection: i32,
szText: [260]CHAR,
iWhy: i32,
};
pub const TCITEMHEADERA = extern struct {
mask: TCITEMHEADERA_MASK,
lpReserved1: u32,
lpReserved2: u32,
pszText: ?PSTR,
cchTextMax: i32,
iImage: i32,
};
pub const TCITEMHEADERW = extern struct {
mask: TCITEMHEADERA_MASK,
lpReserved1: u32,
lpReserved2: u32,
pszText: ?PWSTR,
cchTextMax: i32,
iImage: i32,
};
pub const TCITEMA = extern struct {
mask: TCITEMHEADERA_MASK,
dwState: u32,
dwStateMask: u32,
pszText: ?PSTR,
cchTextMax: i32,
iImage: i32,
lParam: LPARAM,
};
pub const TCITEMW = extern struct {
mask: TCITEMHEADERA_MASK,
dwState: u32,
dwStateMask: u32,
pszText: ?PWSTR,
cchTextMax: i32,
iImage: i32,
lParam: LPARAM,
};
pub const TCHITTESTINFO = extern struct {
pt: POINT,
flags: TCHITTESTINFO_FLAGS,
};
pub const NMTCKEYDOWN = packed struct {
hdr: NMHDR,
wVKey: u16,
flags: u32,
};
pub const MCHITTESTINFO = extern struct {
cbSize: u32,
pt: POINT,
uHit: u32,
st: SYSTEMTIME,
rc: RECT,
iOffset: i32,
iRow: i32,
iCol: i32,
};
pub const MCGRIDINFO = extern struct {
cbSize: u32,
dwPart: MCGRIDINFO_PART,
dwFlags: MCGRIDINFO_FLAGS,
iCalendar: i32,
iRow: i32,
iCol: i32,
bSelected: BOOL,
stStart: SYSTEMTIME,
stEnd: SYSTEMTIME,
rc: RECT,
pszName: ?PWSTR,
cchName: usize,
};
pub const NMSELCHANGE = extern struct {
nmhdr: NMHDR,
stSelStart: SYSTEMTIME,
stSelEnd: SYSTEMTIME,
};
pub const NMDAYSTATE = extern struct {
nmhdr: NMHDR,
stStart: SYSTEMTIME,
cDayState: i32,
prgDayState: ?*u32,
};
pub const NMVIEWCHANGE = extern struct {
nmhdr: NMHDR,
dwOldView: u32,
dwNewView: u32,
};
pub const DATETIMEPICKERINFO = extern struct {
cbSize: u32,
rcCheck: RECT,
stateCheck: u32,
rcButton: RECT,
stateButton: u32,
hwndEdit: ?HWND,
hwndUD: ?HWND,
hwndDropDown: ?HWND,
};
pub const NMDATETIMECHANGE = extern struct {
nmhdr: NMHDR,
dwFlags: u32,
st: SYSTEMTIME,
};
pub const NMDATETIMESTRINGA = extern struct {
nmhdr: NMHDR,
pszUserString: ?[*:0]const u8,
st: SYSTEMTIME,
dwFlags: u32,
};
pub const NMDATETIMESTRINGW = extern struct {
nmhdr: NMHDR,
pszUserString: ?[*:0]const u16,
st: SYSTEMTIME,
dwFlags: u32,
};
pub const NMDATETIMEWMKEYDOWNA = extern struct {
nmhdr: NMHDR,
nVirtKey: i32,
pszFormat: ?[*:0]const u8,
st: SYSTEMTIME,
};
pub const NMDATETIMEWMKEYDOWNW = extern struct {
nmhdr: NMHDR,
nVirtKey: i32,
pszFormat: ?[*:0]const u16,
st: SYSTEMTIME,
};
pub const NMDATETIMEFORMATA = extern struct {
nmhdr: NMHDR,
pszFormat: ?[*:0]const u8,
st: SYSTEMTIME,
pszDisplay: ?[*:0]const u8,
szDisplay: [64]CHAR,
};
pub const NMDATETIMEFORMATW = extern struct {
nmhdr: NMHDR,
pszFormat: ?[*:0]const u16,
st: SYSTEMTIME,
pszDisplay: ?[*:0]const u16,
szDisplay: [64]u16,
};
pub const NMDATETIMEFORMATQUERYA = extern struct {
nmhdr: NMHDR,
pszFormat: ?[*:0]const u8,
szMax: SIZE,
};
pub const NMDATETIMEFORMATQUERYW = extern struct {
nmhdr: NMHDR,
pszFormat: ?[*:0]const u16,
szMax: SIZE,
};
pub const NMIPADDRESS = extern struct {
hdr: NMHDR,
iField: i32,
iValue: i32,
};
pub const NMPGSCROLL = packed struct {
hdr: NMHDR,
fwKeys: NMPGSCROLL_KEYS,
rcParent: RECT,
iDir: NMPGSCROLL_DIR,
iXpos: i32,
iYpos: i32,
iScroll: i32,
};
pub const NMPGCALCSIZE = extern struct {
hdr: NMHDR,
dwFlag: NMPGCALCSIZE_FLAGS,
iWidth: i32,
iHeight: i32,
};
pub const NMPGHOTITEM = extern struct {
hdr: NMHDR,
idOld: i32,
idNew: i32,
dwFlags: u32,
};
pub const BUTTON_IMAGELIST = extern struct {
himl: ?HIMAGELIST,
margin: RECT,
uAlign: BUTTON_IMAGELIST_ALIGN,
};
pub const NMBCHOTITEM = extern struct {
hdr: NMHDR,
dwFlags: NMTBHOTITEM_FLAGS,
};
pub const BUTTON_SPLITINFO = extern struct {
mask: u32,
himlGlyph: ?HIMAGELIST,
uSplitStyle: u32,
size: SIZE,
};
pub const NMBCDROPDOWN = extern struct {
hdr: NMHDR,
rcButton: RECT,
};
pub const EDITBALLOONTIP = extern struct {
cbStruct: u32,
pszTitle: ?[*:0]const u16,
pszText: ?[*:0]const u16,
ttiIcon: EDITBALLOONTIP_ICON,
};
pub const EC_ENDOFLINE = enum(i32) {
DETECTFROMCONTENT = 0,
CRLF = 1,
CR = 2,
LF = 3,
};
pub const EC_ENDOFLINE_DETECTFROMCONTENT = EC_ENDOFLINE.DETECTFROMCONTENT;
pub const EC_ENDOFLINE_CRLF = EC_ENDOFLINE.CRLF;
pub const EC_ENDOFLINE_CR = EC_ENDOFLINE.CR;
pub const EC_ENDOFLINE_LF = EC_ENDOFLINE.LF;
pub const EC_SEARCHWEB_ENTRYPOINT = enum(i32) {
EXTERNAL = 0,
CONTEXTMENU = 1,
};
pub const EC_SEARCHWEB_ENTRYPOINT_EXTERNAL = EC_SEARCHWEB_ENTRYPOINT.EXTERNAL;
pub const EC_SEARCHWEB_ENTRYPOINT_CONTEXTMENU = EC_SEARCHWEB_ENTRYPOINT.CONTEXTMENU;
pub const NMSEARCHWEB = extern struct {
hdr: NMHDR,
entrypoint: EC_SEARCHWEB_ENTRYPOINT,
hasQueryText: BOOL,
invokeSucceeded: BOOL,
};
pub const PFTASKDIALOGCALLBACK = fn(
hwnd: ?HWND,
msg: u32,
wParam: WPARAM,
lParam: LPARAM,
lpRefData: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const TASKDIALOG_FLAGS = enum(i32) {
ENABLE_HYPERLINKS = 1,
USE_HICON_MAIN = 2,
USE_HICON_FOOTER = 4,
ALLOW_DIALOG_CANCELLATION = 8,
USE_COMMAND_LINKS = 16,
USE_COMMAND_LINKS_NO_ICON = 32,
EXPAND_FOOTER_AREA = 64,
EXPANDED_BY_DEFAULT = 128,
VERIFICATION_FLAG_CHECKED = 256,
SHOW_PROGRESS_BAR = 512,
SHOW_MARQUEE_PROGRESS_BAR = 1024,
CALLBACK_TIMER = 2048,
POSITION_RELATIVE_TO_WINDOW = 4096,
RTL_LAYOUT = 8192,
NO_DEFAULT_RADIO_BUTTON = 16384,
CAN_BE_MINIMIZED = 32768,
NO_SET_FOREGROUND = 65536,
SIZE_TO_CONTENT = 16777216,
};
pub const TDF_ENABLE_HYPERLINKS = TASKDIALOG_FLAGS.ENABLE_HYPERLINKS;
pub const TDF_USE_HICON_MAIN = TASKDIALOG_FLAGS.USE_HICON_MAIN;
pub const TDF_USE_HICON_FOOTER = TASKDIALOG_FLAGS.USE_HICON_FOOTER;
pub const TDF_ALLOW_DIALOG_CANCELLATION = TASKDIALOG_FLAGS.ALLOW_DIALOG_CANCELLATION;
pub const TDF_USE_COMMAND_LINKS = TASKDIALOG_FLAGS.USE_COMMAND_LINKS;
pub const TDF_USE_COMMAND_LINKS_NO_ICON = TASKDIALOG_FLAGS.USE_COMMAND_LINKS_NO_ICON;
pub const TDF_EXPAND_FOOTER_AREA = TASKDIALOG_FLAGS.EXPAND_FOOTER_AREA;
pub const TDF_EXPANDED_BY_DEFAULT = TASKDIALOG_FLAGS.EXPANDED_BY_DEFAULT;
pub const TDF_VERIFICATION_FLAG_CHECKED = TASKDIALOG_FLAGS.VERIFICATION_FLAG_CHECKED;
pub const TDF_SHOW_PROGRESS_BAR = TASKDIALOG_FLAGS.SHOW_PROGRESS_BAR;
pub const TDF_SHOW_MARQUEE_PROGRESS_BAR = TASKDIALOG_FLAGS.SHOW_MARQUEE_PROGRESS_BAR;
pub const TDF_CALLBACK_TIMER = TASKDIALOG_FLAGS.CALLBACK_TIMER;
pub const TDF_POSITION_RELATIVE_TO_WINDOW = TASKDIALOG_FLAGS.POSITION_RELATIVE_TO_WINDOW;
pub const TDF_RTL_LAYOUT = TASKDIALOG_FLAGS.RTL_LAYOUT;
pub const TDF_NO_DEFAULT_RADIO_BUTTON = TASKDIALOG_FLAGS.NO_DEFAULT_RADIO_BUTTON;
pub const TDF_CAN_BE_MINIMIZED = TASKDIALOG_FLAGS.CAN_BE_MINIMIZED;
pub const TDF_NO_SET_FOREGROUND = TASKDIALOG_FLAGS.NO_SET_FOREGROUND;
pub const TDF_SIZE_TO_CONTENT = TASKDIALOG_FLAGS.SIZE_TO_CONTENT;
pub const TASKDIALOG_MESSAGES = enum(i32) {
NAVIGATE_PAGE = 1125,
CLICK_BUTTON = 1126,
SET_MARQUEE_PROGRESS_BAR = 1127,
SET_PROGRESS_BAR_STATE = 1128,
SET_PROGRESS_BAR_RANGE = 1129,
SET_PROGRESS_BAR_POS = 1130,
SET_PROGRESS_BAR_MARQUEE = 1131,
SET_ELEMENT_TEXT = 1132,
CLICK_RADIO_BUTTON = 1134,
ENABLE_BUTTON = 1135,
ENABLE_RADIO_BUTTON = 1136,
CLICK_VERIFICATION = 1137,
UPDATE_ELEMENT_TEXT = 1138,
SET_BUTTON_ELEVATION_REQUIRED_STATE = 1139,
UPDATE_ICON = 1140,
};
pub const TDM_NAVIGATE_PAGE = TASKDIALOG_MESSAGES.NAVIGATE_PAGE;
pub const TDM_CLICK_BUTTON = TASKDIALOG_MESSAGES.CLICK_BUTTON;
pub const TDM_SET_MARQUEE_PROGRESS_BAR = TASKDIALOG_MESSAGES.SET_MARQUEE_PROGRESS_BAR;
pub const TDM_SET_PROGRESS_BAR_STATE = TASKDIALOG_MESSAGES.SET_PROGRESS_BAR_STATE;
pub const TDM_SET_PROGRESS_BAR_RANGE = TASKDIALOG_MESSAGES.SET_PROGRESS_BAR_RANGE;
pub const TDM_SET_PROGRESS_BAR_POS = TASKDIALOG_MESSAGES.SET_PROGRESS_BAR_POS;
pub const TDM_SET_PROGRESS_BAR_MARQUEE = TASKDIALOG_MESSAGES.SET_PROGRESS_BAR_MARQUEE;
pub const TDM_SET_ELEMENT_TEXT = TASKDIALOG_MESSAGES.SET_ELEMENT_TEXT;
pub const TDM_CLICK_RADIO_BUTTON = TASKDIALOG_MESSAGES.CLICK_RADIO_BUTTON;
pub const TDM_ENABLE_BUTTON = TASKDIALOG_MESSAGES.ENABLE_BUTTON;
pub const TDM_ENABLE_RADIO_BUTTON = TASKDIALOG_MESSAGES.ENABLE_RADIO_BUTTON;
pub const TDM_CLICK_VERIFICATION = TASKDIALOG_MESSAGES.CLICK_VERIFICATION;
pub const TDM_UPDATE_ELEMENT_TEXT = TASKDIALOG_MESSAGES.UPDATE_ELEMENT_TEXT;
pub const TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = TASKDIALOG_MESSAGES.SET_BUTTON_ELEVATION_REQUIRED_STATE;
pub const TDM_UPDATE_ICON = TASKDIALOG_MESSAGES.UPDATE_ICON;
pub const TASKDIALOG_NOTIFICATIONS = enum(i32) {
CREATED = 0,
NAVIGATED = 1,
BUTTON_CLICKED = 2,
HYPERLINK_CLICKED = 3,
TIMER = 4,
DESTROYED = 5,
RADIO_BUTTON_CLICKED = 6,
DIALOG_CONSTRUCTED = 7,
VERIFICATION_CLICKED = 8,
HELP = 9,
EXPANDO_BUTTON_CLICKED = 10,
};
pub const TDN_CREATED = TASKDIALOG_NOTIFICATIONS.CREATED;
pub const TDN_NAVIGATED = TASKDIALOG_NOTIFICATIONS.NAVIGATED;
pub const TDN_BUTTON_CLICKED = TASKDIALOG_NOTIFICATIONS.BUTTON_CLICKED;
pub const TDN_HYPERLINK_CLICKED = TASKDIALOG_NOTIFICATIONS.HYPERLINK_CLICKED;
pub const TDN_TIMER = TASKDIALOG_NOTIFICATIONS.TIMER;
pub const TDN_DESTROYED = TASKDIALOG_NOTIFICATIONS.DESTROYED;
pub const TDN_RADIO_BUTTON_CLICKED = TASKDIALOG_NOTIFICATIONS.RADIO_BUTTON_CLICKED;
pub const TDN_DIALOG_CONSTRUCTED = TASKDIALOG_NOTIFICATIONS.DIALOG_CONSTRUCTED;
pub const TDN_VERIFICATION_CLICKED = TASKDIALOG_NOTIFICATIONS.VERIFICATION_CLICKED;
pub const TDN_HELP = TASKDIALOG_NOTIFICATIONS.HELP;
pub const TDN_EXPANDO_BUTTON_CLICKED = TASKDIALOG_NOTIFICATIONS.EXPANDO_BUTTON_CLICKED;
pub const TASKDIALOG_BUTTON = packed struct {
nButtonID: i32,
pszButtonText: ?[*:0]const u16,
};
pub const TASKDIALOG_ELEMENTS = enum(i32) {
CONTENT = 0,
EXPANDED_INFORMATION = 1,
FOOTER = 2,
MAIN_INSTRUCTION = 3,
};
pub const TDE_CONTENT = TASKDIALOG_ELEMENTS.CONTENT;
pub const TDE_EXPANDED_INFORMATION = TASKDIALOG_ELEMENTS.EXPANDED_INFORMATION;
pub const TDE_FOOTER = TASKDIALOG_ELEMENTS.FOOTER;
pub const TDE_MAIN_INSTRUCTION = TASKDIALOG_ELEMENTS.MAIN_INSTRUCTION;
pub const TASKDIALOG_ICON_ELEMENTS = enum(i32) {
MAIN = 0,
FOOTER = 1,
};
pub const TDIE_ICON_MAIN = TASKDIALOG_ICON_ELEMENTS.MAIN;
pub const TDIE_ICON_FOOTER = TASKDIALOG_ICON_ELEMENTS.FOOTER;
pub const TASKDIALOG_COMMON_BUTTON_FLAGS = enum(i32) {
OK_BUTTON = 1,
YES_BUTTON = 2,
NO_BUTTON = 4,
CANCEL_BUTTON = 8,
RETRY_BUTTON = 16,
CLOSE_BUTTON = 32,
};
pub const TDCBF_OK_BUTTON = TASKDIALOG_COMMON_BUTTON_FLAGS.OK_BUTTON;
pub const TDCBF_YES_BUTTON = TASKDIALOG_COMMON_BUTTON_FLAGS.YES_BUTTON;
pub const TDCBF_NO_BUTTON = TASKDIALOG_COMMON_BUTTON_FLAGS.NO_BUTTON;
pub const TDCBF_CANCEL_BUTTON = TASKDIALOG_COMMON_BUTTON_FLAGS.CANCEL_BUTTON;
pub const TDCBF_RETRY_BUTTON = TASKDIALOG_COMMON_BUTTON_FLAGS.RETRY_BUTTON;
pub const TDCBF_CLOSE_BUTTON = TASKDIALOG_COMMON_BUTTON_FLAGS.CLOSE_BUTTON;
pub const TASKDIALOGCONFIG = packed struct {
cbSize: u32,
hwndParent: ?HWND,
hInstance: ?HINSTANCE,
dwFlags: TASKDIALOG_FLAGS,
dwCommonButtons: TASKDIALOG_COMMON_BUTTON_FLAGS,
pszWindowTitle: ?[*:0]const u16,
Anonymous1: packed union {
hMainIcon: ?HICON,
pszMainIcon: ?[*:0]const u16,
},
pszMainInstruction: ?[*:0]const u16,
pszContent: ?[*:0]const u16,
cButtons: u32,
pButtons: ?*const TASKDIALOG_BUTTON,
nDefaultButton: i32,
cRadioButtons: u32,
pRadioButtons: ?*const TASKDIALOG_BUTTON,
nDefaultRadioButton: i32,
pszVerificationText: ?[*:0]const u16,
pszExpandedInformation: ?[*:0]const u16,
pszExpandedControlText: ?[*:0]const u16,
pszCollapsedControlText: ?[*:0]const u16,
Anonymous2: packed union {
hFooterIcon: ?HICON,
pszFooterIcon: ?[*:0]const u16,
},
pszFooter: ?[*:0]const u16,
pfCallback: ?PFTASKDIALOGCALLBACK,
lpCallbackData: isize,
cxWidth: u32,
};
pub const PFNDAENUMCALLBACK = fn(
p: ?*c_void,
pData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFNDAENUMCALLBACKCONST = fn(
p: ?*const c_void,
pData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFNDACOMPARE = fn(
p1: ?*c_void,
p2: ?*c_void,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const PFNDACOMPARECONST = fn(
p1: ?*const c_void,
p2: ?*const c_void,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const DPASTREAMINFO = extern struct {
iPos: i32,
pvItem: ?*c_void,
};
pub const PFNDPASTREAM = fn(
pinfo: ?*DPASTREAMINFO,
pstream: ?*IStream,
pvInstData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PFNDPAMERGE = fn(
uMsg: DPAMM_MESSAGE,
pvDest: ?*c_void,
pvSrc: ?*c_void,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub const PFNDPAMERGECONST = fn(
uMsg: DPAMM_MESSAGE,
pvDest: ?*const c_void,
pvSrc: ?*const c_void,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
pub const _LI_METRIC = enum(i32) {
SMALL = 0,
LARGE = 1,
};
pub const LIM_SMALL = _LI_METRIC.SMALL;
pub const LIM_LARGE = _LI_METRIC.LARGE;
const CLSID_ImageList_Value = @import("../zig.zig").Guid.initString("7c476ba2-02b1-48f4-8048-b24619ddc058");
pub const CLSID_ImageList = &CLSID_ImageList_Value;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IImageList_Value = @import("../zig.zig").Guid.initString("46eb5926-582e-4017-9fdf-e8998daa0950");
pub const IID_IImageList = &IID_IImageList_Value;
pub const IImageList = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Add: fn(
self: *const IImageList,
hbmImage: ?HBITMAP,
hbmMask: ?HBITMAP,
pi: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReplaceIcon: fn(
self: *const IImageList,
i: i32,
hicon: ?HICON,
pi: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetOverlayImage: fn(
self: *const IImageList,
iImage: i32,
iOverlay: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Replace: fn(
self: *const IImageList,
i: i32,
hbmImage: ?HBITMAP,
hbmMask: ?HBITMAP,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddMasked: fn(
self: *const IImageList,
hbmImage: ?HBITMAP,
crMask: u32,
pi: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Draw: fn(
self: *const IImageList,
pimldp: ?*IMAGELISTDRAWPARAMS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const IImageList,
i: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIcon: fn(
self: *const IImageList,
i: i32,
flags: u32,
picon: ?*?HICON,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetImageInfo: fn(
self: *const IImageList,
i: i32,
pImageInfo: ?*IMAGEINFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Copy: fn(
self: *const IImageList,
iDst: i32,
punkSrc: ?*IUnknown,
iSrc: i32,
uFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Merge: fn(
self: *const IImageList,
i1: i32,
punk2: ?*IUnknown,
i2: i32,
dx: i32,
dy: i32,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clone: fn(
self: *const IImageList,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetImageRect: fn(
self: *const IImageList,
i: i32,
prc: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIconSize: fn(
self: *const IImageList,
cx: ?*i32,
cy: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIconSize: fn(
self: *const IImageList,
cx: i32,
cy: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetImageCount: fn(
self: *const IImageList,
pi: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetImageCount: fn(
self: *const IImageList,
uNewCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetBkColor: fn(
self: *const IImageList,
clrBk: u32,
pclr: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBkColor: fn(
self: *const IImageList,
pclr: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BeginDrag: fn(
self: *const IImageList,
iTrack: i32,
dxHotspot: i32,
dyHotspot: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EndDrag: fn(
self: *const IImageList,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DragEnter: fn(
self: *const IImageList,
hwndLock: ?HWND,
x: i32,
y: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DragLeave: fn(
self: *const IImageList,
hwndLock: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DragMove: fn(
self: *const IImageList,
x: i32,
y: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDragCursorImage: fn(
self: *const IImageList,
punk: ?*IUnknown,
iDrag: i32,
dxHotspot: i32,
dyHotspot: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DragShowNolock: fn(
self: *const IImageList,
fShow: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDragImage: fn(
self: *const IImageList,
ppt: ?*POINT,
pptHotspot: ?*POINT,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetItemFlags: fn(
self: *const IImageList,
i: i32,
dwFlags: ?*IMAGE_LIST_ITEM_FLAGS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOverlayImage: fn(
self: *const IImageList,
iOverlay: i32,
piIndex: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_Add(self: *const T, hbmImage: ?HBITMAP, hbmMask: ?HBITMAP, pi: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).Add(@ptrCast(*const IImageList, self), hbmImage, hbmMask, pi);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_ReplaceIcon(self: *const T, i: i32, hicon: ?HICON, pi: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).ReplaceIcon(@ptrCast(*const IImageList, self), i, hicon, pi);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_SetOverlayImage(self: *const T, iImage: i32, iOverlay: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).SetOverlayImage(@ptrCast(*const IImageList, self), iImage, iOverlay);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_Replace(self: *const T, i: i32, hbmImage: ?HBITMAP, hbmMask: ?HBITMAP) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).Replace(@ptrCast(*const IImageList, self), i, hbmImage, hbmMask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_AddMasked(self: *const T, hbmImage: ?HBITMAP, crMask: u32, pi: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).AddMasked(@ptrCast(*const IImageList, self), hbmImage, crMask, pi);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_Draw(self: *const T, pimldp: ?*IMAGELISTDRAWPARAMS) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).Draw(@ptrCast(*const IImageList, self), pimldp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_Remove(self: *const T, i: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).Remove(@ptrCast(*const IImageList, self), i);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetIcon(self: *const T, i: i32, flags: u32, picon: ?*?HICON) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetIcon(@ptrCast(*const IImageList, self), i, flags, picon);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetImageInfo(self: *const T, i: i32, pImageInfo: ?*IMAGEINFO) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetImageInfo(@ptrCast(*const IImageList, self), i, pImageInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_Copy(self: *const T, iDst: i32, punkSrc: ?*IUnknown, iSrc: i32, uFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).Copy(@ptrCast(*const IImageList, self), iDst, punkSrc, iSrc, uFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_Merge(self: *const T, i1_: i32, punk2: ?*IUnknown, i2_: i32, dx: i32, dy: i32, riid: ?*const Guid, ppv: ?*?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).Merge(@ptrCast(*const IImageList, self), i1_, punk2, i2_, dx, dy, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_Clone(self: *const T, riid: ?*const Guid, ppv: ?*?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).Clone(@ptrCast(*const IImageList, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetImageRect(self: *const T, i: i32, prc: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetImageRect(@ptrCast(*const IImageList, self), i, prc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetIconSize(self: *const T, cx: ?*i32, cy: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetIconSize(@ptrCast(*const IImageList, self), cx, cy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_SetIconSize(self: *const T, cx: i32, cy: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).SetIconSize(@ptrCast(*const IImageList, self), cx, cy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetImageCount(self: *const T, pi: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetImageCount(@ptrCast(*const IImageList, self), pi);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_SetImageCount(self: *const T, uNewCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).SetImageCount(@ptrCast(*const IImageList, self), uNewCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_SetBkColor(self: *const T, clrBk: u32, pclr: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).SetBkColor(@ptrCast(*const IImageList, self), clrBk, pclr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetBkColor(self: *const T, pclr: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetBkColor(@ptrCast(*const IImageList, self), pclr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_BeginDrag(self: *const T, iTrack: i32, dxHotspot: i32, dyHotspot: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).BeginDrag(@ptrCast(*const IImageList, self), iTrack, dxHotspot, dyHotspot);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_EndDrag(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).EndDrag(@ptrCast(*const IImageList, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_DragEnter(self: *const T, hwndLock: ?HWND, x: i32, y: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).DragEnter(@ptrCast(*const IImageList, self), hwndLock, x, y);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_DragLeave(self: *const T, hwndLock: ?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).DragLeave(@ptrCast(*const IImageList, self), hwndLock);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_DragMove(self: *const T, x: i32, y: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).DragMove(@ptrCast(*const IImageList, self), x, y);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_SetDragCursorImage(self: *const T, punk: ?*IUnknown, iDrag: i32, dxHotspot: i32, dyHotspot: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).SetDragCursorImage(@ptrCast(*const IImageList, self), punk, iDrag, dxHotspot, dyHotspot);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_DragShowNolock(self: *const T, fShow: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).DragShowNolock(@ptrCast(*const IImageList, self), fShow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetDragImage(self: *const T, ppt: ?*POINT, pptHotspot: ?*POINT, riid: ?*const Guid, ppv: ?*?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetDragImage(@ptrCast(*const IImageList, self), ppt, pptHotspot, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetItemFlags(self: *const T, i: i32, dwFlags: ?*IMAGE_LIST_ITEM_FLAGS) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetItemFlags(@ptrCast(*const IImageList, self), i, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList_GetOverlayImage(self: *const T, iOverlay: i32, piIndex: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList.VTable, self.vtable).GetOverlayImage(@ptrCast(*const IImageList, self), iOverlay, piIndex);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const IMAGELISTSTATS = extern struct {
cbSize: u32,
cAlloc: i32,
cUsed: i32,
cStandby: i32,
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IImageList2_Value = @import("../zig.zig").Guid.initString("192b9d83-50fc-457b-90a0-2b82a8b5dae1");
pub const IID_IImageList2 = &IID_IImageList2_Value;
pub const IImageList2 = extern struct {
pub const VTable = extern struct {
base: IImageList.VTable,
Resize: fn(
self: *const IImageList2,
cxNewIconSize: i32,
cyNewIconSize: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOriginalSize: fn(
self: *const IImageList2,
iImage: i32,
dwFlags: u32,
pcx: ?*i32,
pcy: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetOriginalSize: fn(
self: *const IImageList2,
iImage: i32,
cx: i32,
cy: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCallback: fn(
self: *const IImageList2,
punk: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCallback: fn(
self: *const IImageList2,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ForceImagePresent: fn(
self: *const IImageList2,
iImage: i32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DiscardImages: fn(
self: *const IImageList2,
iFirstImage: i32,
iLastImage: i32,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PreloadImages: fn(
self: *const IImageList2,
pimldp: ?*IMAGELISTDRAWPARAMS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStatistics: fn(
self: *const IImageList2,
pils: ?*IMAGELISTSTATS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Initialize: fn(
self: *const IImageList2,
cx: i32,
cy: i32,
flags: IMAGELIST_CREATION_FLAGS,
cInitial: i32,
cGrow: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Replace2: fn(
self: *const IImageList2,
i: i32,
hbmImage: ?HBITMAP,
hbmMask: ?HBITMAP,
punk: ?*IUnknown,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReplaceFromImageList: fn(
self: *const IImageList2,
i: i32,
pil: ?*IImageList,
iSrc: i32,
punk: ?*IUnknown,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IImageList.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_Resize(self: *const T, cxNewIconSize: i32, cyNewIconSize: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).Resize(@ptrCast(*const IImageList2, self), cxNewIconSize, cyNewIconSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_GetOriginalSize(self: *const T, iImage: i32, dwFlags: u32, pcx: ?*i32, pcy: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).GetOriginalSize(@ptrCast(*const IImageList2, self), iImage, dwFlags, pcx, pcy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_SetOriginalSize(self: *const T, iImage: i32, cx: i32, cy: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).SetOriginalSize(@ptrCast(*const IImageList2, self), iImage, cx, cy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_SetCallback(self: *const T, punk: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).SetCallback(@ptrCast(*const IImageList2, self), punk);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_GetCallback(self: *const T, riid: ?*const Guid, ppv: ?*?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).GetCallback(@ptrCast(*const IImageList2, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_ForceImagePresent(self: *const T, iImage: i32, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).ForceImagePresent(@ptrCast(*const IImageList2, self), iImage, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_DiscardImages(self: *const T, iFirstImage: i32, iLastImage: i32, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).DiscardImages(@ptrCast(*const IImageList2, self), iFirstImage, iLastImage, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_PreloadImages(self: *const T, pimldp: ?*IMAGELISTDRAWPARAMS) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).PreloadImages(@ptrCast(*const IImageList2, self), pimldp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_GetStatistics(self: *const T, pils: ?*IMAGELISTSTATS) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).GetStatistics(@ptrCast(*const IImageList2, self), pils);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_Initialize(self: *const T, cx: i32, cy: i32, flags: IMAGELIST_CREATION_FLAGS, cInitial: i32, cGrow: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).Initialize(@ptrCast(*const IImageList2, self), cx, cy, flags, cInitial, cGrow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_Replace2(self: *const T, i: i32, hbmImage: ?HBITMAP, hbmMask: ?HBITMAP, punk: ?*IUnknown, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).Replace2(@ptrCast(*const IImageList2, self), i, hbmImage, hbmMask, punk, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IImageList2_ReplaceFromImageList(self: *const T, i: i32, pil: ?*IImageList, iSrc: i32, punk: ?*IUnknown, dwFlags: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IImageList2.VTable, self.vtable).ReplaceFromImageList(@ptrCast(*const IImageList2, self), i, pil, iSrc, punk, dwFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const TEXTMODE = enum(i32) {
PLAINTEXT = 1,
RICHTEXT = 2,
SINGLELEVELUNDO = 4,
MULTILEVELUNDO = 8,
SINGLECODEPAGE = 16,
MULTICODEPAGE = 32,
};
pub const TM_PLAINTEXT = TEXTMODE.PLAINTEXT;
pub const TM_RICHTEXT = TEXTMODE.RICHTEXT;
pub const TM_SINGLELEVELUNDO = TEXTMODE.SINGLELEVELUNDO;
pub const TM_MULTILEVELUNDO = TEXTMODE.MULTILEVELUNDO;
pub const TM_SINGLECODEPAGE = TEXTMODE.SINGLECODEPAGE;
pub const TM_MULTICODEPAGE = TEXTMODE.MULTICODEPAGE;
pub const IMECOMPTEXT = extern struct {
cb: i32,
flags: IMECOMPTEXT_FLAGS,
};
pub const TABLEROWPARMS = extern struct {
cbRow: u8,
cbCell: u8,
cCell: u8,
cRow: u8,
dxCellMargin: i32,
dxIndent: i32,
dyHeight: i32,
_bitfield: u32,
cpStartRow: i32,
bTableLevel: u8,
iCell: u8,
};
pub const TABLECELLPARMS = extern struct {
dxWidth: i32,
_bitfield: u16,
wShading: u16,
dxBrdrLeft: i16,
dyBrdrTop: i16,
dxBrdrRight: i16,
dyBrdrBottom: i16,
crBrdrLeft: u32,
crBrdrTop: u32,
crBrdrRight: u32,
crBrdrBottom: u32,
crBackPat: u32,
crForePat: u32,
};
pub const AutoCorrectProc = fn(
langid: u16,
pszBefore: ?[*:0]const u16,
pszAfter: ?PWSTR,
cchAfter: i32,
pcchReplaced: ?*i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const EDITWORDBREAKPROCEX = fn(
pchText: ?PSTR,
cchText: i32,
bCharSet: u8,
action: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const CHARFORMATA = extern struct {
cbSize: u32,
dwMask: CFM_MASK,
dwEffects: CFE_EFFECTS,
yHeight: i32,
yOffset: i32,
crTextColor: u32,
bCharSet: u8,
bPitchAndFamily: u8,
szFaceName: [32]CHAR,
};
pub const CHARFORMATW = extern struct {
cbSize: u32,
dwMask: CFM_MASK,
dwEffects: CFE_EFFECTS,
yHeight: i32,
yOffset: i32,
crTextColor: u32,
bCharSet: u8,
bPitchAndFamily: u8,
szFaceName: [32]u16,
};
pub const CHARFORMAT2W = extern struct {
__AnonymousBase_richedit_L711_C23: CHARFORMATW,
wWeight: u16,
sSpacing: i16,
crBackColor: u32,
lcid: u32,
Anonymous: extern union {
dwReserved: u32,
dwCookie: u32,
},
sStyle: i16,
wKerning: u16,
bUnderlineType: u8,
bAnimation: u8,
bRevAuthor: u8,
bUnderlineColor: u8,
};
pub const CHARFORMAT2A = extern struct {
__AnonymousBase_richedit_L736_C23: CHARFORMATA,
wWeight: u16,
sSpacing: i16,
crBackColor: u32,
lcid: u32,
Anonymous: extern union {
dwReserved: u32,
dwCookie: u32,
},
sStyle: i16,
wKerning: u16,
bUnderlineType: u8,
bAnimation: u8,
bRevAuthor: u8,
bUnderlineColor: u8,
};
pub const CHARRANGE = extern struct {
cpMin: i32,
cpMax: i32,
};
pub const EDITSTREAMCALLBACK = fn(
dwCookie: usize,
pbBuff: ?*u8,
cb: i32,
pcb: ?*i32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub const PARAFORMAT = extern struct {
cbSize: u32,
dwMask: PARAFORMAT_MASK,
wNumbering: u16,
Anonymous: extern union {
wReserved: u16,
wEffects: u16,
},
dxStartIndent: i32,
dxRightIndent: i32,
dxOffset: i32,
wAlignment: PARAFORMAT_ALIGNMENT,
cTabCount: i16,
rgxTabs: [32]u32,
};
pub const PARAFORMAT2 = extern struct {
__AnonymousBase_richedit_L1149_C22: PARAFORMAT,
dySpaceBefore: i32,
dySpaceAfter: i32,
dyLineSpacing: i32,
sStyle: i16,
bLineSpacingRule: u8,
bOutlineLevel: u8,
wShadingWeight: u16,
wShadingStyle: PARAFORMAT_SHADING_STYLE,
wNumberingStart: u16,
wNumberingStyle: PARAFORMAT_NUMBERING_STYLE,
wNumberingTab: u16,
wBorderSpace: u16,
wBorderWidth: u16,
wBorders: PARAFORMAT_BORDERS,
};
pub const COMPCOLOR = extern struct {
crText: u32,
crBackground: u32,
dwEffects: u32,
};
pub const UNDONAMEID = enum(i32) {
UNKNOWN = 0,
TYPING = 1,
DELETE = 2,
DRAGDROP = 3,
CUT = 4,
PASTE = 5,
AUTOTABLE = 6,
};
pub const UID_UNKNOWN = UNDONAMEID.UNKNOWN;
pub const UID_TYPING = UNDONAMEID.TYPING;
pub const UID_DELETE = UNDONAMEID.DELETE;
pub const UID_DRAGDROP = UNDONAMEID.DRAGDROP;
pub const UID_CUT = UNDONAMEID.CUT;
pub const UID_PASTE = UNDONAMEID.PASTE;
pub const UID_AUTOTABLE = UNDONAMEID.AUTOTABLE;
pub const SETTEXTEX = extern struct {
flags: u32,
codepage: u32,
};
pub const GETTEXTLENGTHEX = extern struct {
flags: GETTEXTLENGTHEX_FLAGS,
codepage: u32,
};
pub const BIDIOPTIONS = extern struct {
cbSize: u32,
wMask: u16,
wEffects: u16,
};
pub const KHYPH = enum(i32) {
Nil = 0,
Normal = 1,
AddBefore = 2,
ChangeBefore = 3,
DeleteBefore = 4,
ChangeAfter = 5,
DelAndChange = 6,
};
pub const khyphNil = KHYPH.Nil;
pub const khyphNormal = KHYPH.Normal;
pub const khyphAddBefore = KHYPH.AddBefore;
pub const khyphChangeBefore = KHYPH.ChangeBefore;
pub const khyphDeleteBefore = KHYPH.DeleteBefore;
pub const khyphChangeAfter = KHYPH.ChangeAfter;
pub const khyphDelAndChange = KHYPH.DelAndChange;
pub const hyphresult = extern struct {
khyph: KHYPH,
ichHyph: i32,
chHyph: u16,
};
pub const tomConstants = enum(i32) {
False = 0,
True = -1,
Undefined = -9999999,
Toggle = -9999998,
AutoColor = -9999997,
Default = -9999996,
Suspend = -9999995,
Resume = -9999994,
// ApplyNow = 0, this enum value conflicts with False
ApplyLater = 1,
TrackParms = 2,
CacheParms = 3,
ApplyTmp = 4,
DisableSmartFont = 8,
EnableSmartFont = 9,
UsePoints = 10,
UseTwips = 11,
Backward = -1073741823,
Forward = 1073741823,
// Move = 0, this enum value conflicts with False
// Extend = 1, this enum value conflicts with ApplyLater
// NoSelection = 0, this enum value conflicts with False
// SelectionIP = 1, this enum value conflicts with ApplyLater
// SelectionNormal = 2, this enum value conflicts with TrackParms
// SelectionFrame = 3, this enum value conflicts with CacheParms
// SelectionColumn = 4, this enum value conflicts with ApplyTmp
SelectionRow = 5,
SelectionBlock = 6,
SelectionInlineShape = 7,
// SelectionShape = 8, this enum value conflicts with DisableSmartFont
// SelStartActive = 1, this enum value conflicts with ApplyLater
// SelAtEOL = 2, this enum value conflicts with TrackParms
// SelOvertype = 4, this enum value conflicts with ApplyTmp
// SelActive = 8, this enum value conflicts with DisableSmartFont
SelReplace = 16,
// End = 0, this enum value conflicts with False
Start = 32,
// CollapseEnd = 0, this enum value conflicts with False
// CollapseStart = 1, this enum value conflicts with ApplyLater
ClientCoord = 256,
AllowOffClient = 512,
Transform = 1024,
ObjectArg = 2048,
AtEnd = 4096,
// None = 0, this enum value conflicts with False
// Single = 1, this enum value conflicts with ApplyLater
// Words = 2, this enum value conflicts with TrackParms
// Double = 3, this enum value conflicts with CacheParms
// Dotted = 4, this enum value conflicts with ApplyTmp
// Dash = 5, this enum value conflicts with SelectionRow
// DashDot = 6, this enum value conflicts with SelectionBlock
// DashDotDot = 7, this enum value conflicts with SelectionInlineShape
// Wave = 8, this enum value conflicts with DisableSmartFont
// Thick = 9, this enum value conflicts with EnableSmartFont
// Hair = 10, this enum value conflicts with UsePoints
// DoubleWave = 11, this enum value conflicts with UseTwips
HeavyWave = 12,
LongDash = 13,
ThickDash = 14,
ThickDashDot = 15,
// ThickDashDotDot = 16, this enum value conflicts with SelReplace
ThickDotted = 17,
ThickLongDash = 18,
// LineSpaceSingle = 0, this enum value conflicts with False
// LineSpace1pt5 = 1, this enum value conflicts with ApplyLater
// LineSpaceDouble = 2, this enum value conflicts with TrackParms
// LineSpaceAtLeast = 3, this enum value conflicts with CacheParms
// LineSpaceExactly = 4, this enum value conflicts with ApplyTmp
// LineSpaceMultiple = 5, this enum value conflicts with SelectionRow
// LineSpacePercent = 6, this enum value conflicts with SelectionBlock
// AlignLeft = 0, this enum value conflicts with False
// AlignCenter = 1, this enum value conflicts with ApplyLater
// AlignRight = 2, this enum value conflicts with TrackParms
// AlignJustify = 3, this enum value conflicts with CacheParms
// AlignDecimal = 3, this enum value conflicts with CacheParms
// AlignBar = 4, this enum value conflicts with ApplyTmp
// DefaultTab = 5, this enum value conflicts with SelectionRow
// AlignInterWord = 3, this enum value conflicts with CacheParms
// AlignNewspaper = 4, this enum value conflicts with ApplyTmp
// AlignInterLetter = 5, this enum value conflicts with SelectionRow
// AlignScaled = 6, this enum value conflicts with SelectionBlock
// Spaces = 0, this enum value conflicts with False
// Dots = 1, this enum value conflicts with ApplyLater
// Dashes = 2, this enum value conflicts with TrackParms
// Lines = 3, this enum value conflicts with CacheParms
// ThickLines = 4, this enum value conflicts with ApplyTmp
// Equals = 5, this enum value conflicts with SelectionRow
TabBack = -3,
TabNext = -2,
// TabHere = -1, this enum value conflicts with True
// ListNone = 0, this enum value conflicts with False
// ListBullet = 1, this enum value conflicts with ApplyLater
// ListNumberAsArabic = 2, this enum value conflicts with TrackParms
// ListNumberAsLCLetter = 3, this enum value conflicts with CacheParms
// ListNumberAsUCLetter = 4, this enum value conflicts with ApplyTmp
// ListNumberAsLCRoman = 5, this enum value conflicts with SelectionRow
// ListNumberAsUCRoman = 6, this enum value conflicts with SelectionBlock
// ListNumberAsSequence = 7, this enum value conflicts with SelectionInlineShape
// ListNumberedCircle = 8, this enum value conflicts with DisableSmartFont
// ListNumberedBlackCircleWingding = 9, this enum value conflicts with EnableSmartFont
// ListNumberedWhiteCircleWingding = 10, this enum value conflicts with UsePoints
// ListNumberedArabicWide = 11, this enum value conflicts with UseTwips
// ListNumberedChS = 12, this enum value conflicts with HeavyWave
// ListNumberedChT = 13, this enum value conflicts with LongDash
// ListNumberedJpnChS = 14, this enum value conflicts with ThickDash
// ListNumberedJpnKor = 15, this enum value conflicts with ThickDashDot
// ListNumberedArabic1 = 16, this enum value conflicts with SelReplace
// ListNumberedArabic2 = 17, this enum value conflicts with ThickDotted
// ListNumberedHebrew = 18, this enum value conflicts with ThickLongDash
ListNumberedThaiAlpha = 19,
ListNumberedThaiNum = 20,
ListNumberedHindiAlpha = 21,
ListNumberedHindiAlpha1 = 22,
ListNumberedHindiNum = 23,
ListParentheses = 65536,
ListPeriod = 131072,
ListPlain = 196608,
ListNoNumber = 262144,
ListMinus = 524288,
IgnoreNumberStyle = 16777216,
// ParaStyleNormal = -1, this enum value conflicts with True
// ParaStyleHeading1 = -2, this enum value conflicts with TabNext
// ParaStyleHeading2 = -3, this enum value conflicts with TabBack
ParaStyleHeading3 = -4,
ParaStyleHeading4 = -5,
ParaStyleHeading5 = -6,
ParaStyleHeading6 = -7,
ParaStyleHeading7 = -8,
ParaStyleHeading8 = -9,
ParaStyleHeading9 = -10,
// Character = 1, this enum value conflicts with ApplyLater
// Word = 2, this enum value conflicts with TrackParms
// Sentence = 3, this enum value conflicts with CacheParms
// Paragraph = 4, this enum value conflicts with ApplyTmp
// Line = 5, this enum value conflicts with SelectionRow
// Story = 6, this enum value conflicts with SelectionBlock
// Screen = 7, this enum value conflicts with SelectionInlineShape
// Section = 8, this enum value conflicts with DisableSmartFont
// TableColumn = 9, this enum value conflicts with EnableSmartFont
// Column = 9, this enum value conflicts with EnableSmartFont
// Row = 10, this enum value conflicts with UsePoints
// Window = 11, this enum value conflicts with UseTwips
// Cell = 12, this enum value conflicts with HeavyWave
// CharFormat = 13, this enum value conflicts with LongDash
// ParaFormat = 14, this enum value conflicts with ThickDash
// Table = 15, this enum value conflicts with ThickDashDot
// Object = 16, this enum value conflicts with SelReplace
// Page = 17, this enum value conflicts with ThickDotted
// HardParagraph = 18, this enum value conflicts with ThickLongDash
// Cluster = 19, this enum value conflicts with ListNumberedThaiAlpha
// InlineObject = 20, this enum value conflicts with ListNumberedThaiNum
// InlineObjectArg = 21, this enum value conflicts with ListNumberedHindiAlpha
// LeafLine = 22, this enum value conflicts with ListNumberedHindiAlpha1
// LayoutColumn = 23, this enum value conflicts with ListNumberedHindiNum
ProcessId = 1073741825,
// MatchWord = 2, this enum value conflicts with TrackParms
// MatchCase = 4, this enum value conflicts with ApplyTmp
// MatchPattern = 8, this enum value conflicts with DisableSmartFont
// UnknownStory = 0, this enum value conflicts with False
// MainTextStory = 1, this enum value conflicts with ApplyLater
// FootnotesStory = 2, this enum value conflicts with TrackParms
// EndnotesStory = 3, this enum value conflicts with CacheParms
// CommentsStory = 4, this enum value conflicts with ApplyTmp
// TextFrameStory = 5, this enum value conflicts with SelectionRow
// EvenPagesHeaderStory = 6, this enum value conflicts with SelectionBlock
// PrimaryHeaderStory = 7, this enum value conflicts with SelectionInlineShape
// EvenPagesFooterStory = 8, this enum value conflicts with DisableSmartFont
// PrimaryFooterStory = 9, this enum value conflicts with EnableSmartFont
// FirstPageHeaderStory = 10, this enum value conflicts with UsePoints
// FirstPageFooterStory = 11, this enum value conflicts with UseTwips
ScratchStory = 127,
FindStory = 128,
ReplaceStory = 129,
// StoryInactive = 0, this enum value conflicts with False
// StoryActiveDisplay = 1, this enum value conflicts with ApplyLater
// StoryActiveUI = 2, this enum value conflicts with TrackParms
// StoryActiveDisplayUI = 3, this enum value conflicts with CacheParms
// NoAnimation = 0, this enum value conflicts with False
// LasVegasLights = 1, this enum value conflicts with ApplyLater
// BlinkingBackground = 2, this enum value conflicts with TrackParms
// SparkleText = 3, this enum value conflicts with CacheParms
// MarchingBlackAnts = 4, this enum value conflicts with ApplyTmp
// MarchingRedAnts = 5, this enum value conflicts with SelectionRow
// Shimmer = 6, this enum value conflicts with SelectionBlock
// WipeDown = 7, this enum value conflicts with SelectionInlineShape
// WipeRight = 8, this enum value conflicts with DisableSmartFont
// AnimationMax = 8, this enum value conflicts with DisableSmartFont
// LowerCase = 0, this enum value conflicts with False
// UpperCase = 1, this enum value conflicts with ApplyLater
// TitleCase = 2, this enum value conflicts with TrackParms
// SentenceCase = 4, this enum value conflicts with ApplyTmp
// ToggleCase = 5, this enum value conflicts with SelectionRow
// ReadOnly = 256, this enum value conflicts with ClientCoord
// ShareDenyRead = 512, this enum value conflicts with AllowOffClient
// ShareDenyWrite = 1024, this enum value conflicts with Transform
// PasteFile = 4096, this enum value conflicts with AtEnd
// CreateNew = 16, this enum value conflicts with SelReplace
// CreateAlways = 32, this enum value conflicts with Start
OpenExisting = 48,
OpenAlways = 64,
TruncateExisting = 80,
// RTF = 1, this enum value conflicts with ApplyLater
// Text = 2, this enum value conflicts with TrackParms
// HTML = 3, this enum value conflicts with CacheParms
// WordDocument = 4, this enum value conflicts with ApplyTmp
Bold = -2147483647,
Italic = -2147483646,
Underline = -2147483644,
Strikeout = -2147483640,
Protected = -2147483632,
Link = -2147483616,
SmallCaps = -2147483584,
AllCaps = -2147483520,
Hidden = -2147483392,
Outline = -2147483136,
Shadow = -2147482624,
Emboss = -2147481600,
Imprint = -2147479552,
Disabled = -2147475456,
Revised = -2147467264,
SubscriptCF = -2147418112,
SuperscriptCF = -2147352576,
FontBound = -2146435072,
LinkProtected = -2139095040,
InlineObjectStart = -2130706432,
ExtendedChar = -2113929216,
AutoBackColor = -2080374784,
MathZoneNoBuildUp = -2013265920,
MathZone = -1879048192,
MathZoneOrdinary = -1610612736,
AutoTextColor = -1073741824,
// MathZoneDisplay = 262144, this enum value conflicts with ListNoNumber
// ParaEffectRTL = 1, this enum value conflicts with ApplyLater
// ParaEffectKeep = 2, this enum value conflicts with TrackParms
// ParaEffectKeepNext = 4, this enum value conflicts with ApplyTmp
// ParaEffectPageBreakBefore = 8, this enum value conflicts with DisableSmartFont
// ParaEffectNoLineNumber = 16, this enum value conflicts with SelReplace
// ParaEffectNoWidowControl = 32, this enum value conflicts with Start
// ParaEffectDoNotHyphen = 64, this enum value conflicts with OpenAlways
// ParaEffectSideBySide = 128, this enum value conflicts with FindStory
// ParaEffectCollapsed = 256, this enum value conflicts with ClientCoord
// ParaEffectOutlineLevel = 512, this enum value conflicts with AllowOffClient
// ParaEffectBox = 1024, this enum value conflicts with Transform
// ParaEffectTableRowDelimiter = 4096, this enum value conflicts with AtEnd
ParaEffectTable = 16384,
// ModWidthPairs = 1, this enum value conflicts with ApplyLater
// ModWidthSpace = 2, this enum value conflicts with TrackParms
// AutoSpaceAlpha = 4, this enum value conflicts with ApplyTmp
// AutoSpaceNumeric = 8, this enum value conflicts with DisableSmartFont
// AutoSpaceParens = 16, this enum value conflicts with SelReplace
// EmbeddedFont = 32, this enum value conflicts with Start
// Doublestrike = 64, this enum value conflicts with OpenAlways
// Overlapping = 128, this enum value conflicts with FindStory
// NormalCaret = 0, this enum value conflicts with False
// KoreanBlockCaret = 1, this enum value conflicts with ApplyLater
// NullCaret = 2, this enum value conflicts with TrackParms
// IncludeInset = 1, this enum value conflicts with ApplyLater
// UnicodeBiDi = 1, this enum value conflicts with ApplyLater
// MathCFCheck = 4, this enum value conflicts with ApplyTmp
// Unlink = 8, this enum value conflicts with DisableSmartFont
// Unhide = 16, this enum value conflicts with SelReplace
// CheckTextLimit = 32, this enum value conflicts with Start
// IgnoreCurrentFont = 0, this enum value conflicts with False
// MatchCharRep = 1, this enum value conflicts with ApplyLater
// MatchFontSignature = 2, this enum value conflicts with TrackParms
// MatchAscii = 4, this enum value conflicts with ApplyTmp
// GetHeightOnly = 8, this enum value conflicts with DisableSmartFont
// MatchMathFont = 16, this enum value conflicts with SelReplace
Charset = -2147483648,
CharRepFromLcid = 1073741824,
// Ansi = 0, this enum value conflicts with False
// EastEurope = 1, this enum value conflicts with ApplyLater
// Cyrillic = 2, this enum value conflicts with TrackParms
// Greek = 3, this enum value conflicts with CacheParms
// Turkish = 4, this enum value conflicts with ApplyTmp
// Hebrew = 5, this enum value conflicts with SelectionRow
// Arabic = 6, this enum value conflicts with SelectionBlock
// Baltic = 7, this enum value conflicts with SelectionInlineShape
// Vietnamese = 8, this enum value conflicts with DisableSmartFont
// DefaultCharRep = 9, this enum value conflicts with EnableSmartFont
// Symbol = 10, this enum value conflicts with UsePoints
// Thai = 11, this enum value conflicts with UseTwips
// ShiftJIS = 12, this enum value conflicts with HeavyWave
// GB2312 = 13, this enum value conflicts with LongDash
// Hangul = 14, this enum value conflicts with ThickDash
// BIG5 = 15, this enum value conflicts with ThickDashDot
// PC437 = 16, this enum value conflicts with SelReplace
// OEM = 17, this enum value conflicts with ThickDotted
// Mac = 18, this enum value conflicts with ThickLongDash
// Armenian = 19, this enum value conflicts with ListNumberedThaiAlpha
// Syriac = 20, this enum value conflicts with ListNumberedThaiNum
// Thaana = 21, this enum value conflicts with ListNumberedHindiAlpha
// Devanagari = 22, this enum value conflicts with ListNumberedHindiAlpha1
// Bengali = 23, this enum value conflicts with ListNumberedHindiNum
Gurmukhi = 24,
Gujarati = 25,
Oriya = 26,
Tamil = 27,
Telugu = 28,
Kannada = 29,
Malayalam = 30,
Sinhala = 31,
// Lao = 32, this enum value conflicts with Start
Tibetan = 33,
Myanmar = 34,
Georgian = 35,
Jamo = 36,
Ethiopic = 37,
Cherokee = 38,
Aboriginal = 39,
Ogham = 40,
Runic = 41,
Khmer = 42,
Mongolian = 43,
Braille = 44,
Yi = 45,
Limbu = 46,
TaiLe = 47,
// NewTaiLue = 48, this enum value conflicts with OpenExisting
SylotiNagri = 49,
Kharoshthi = 50,
Kayahli = 51,
Usymbol = 52,
Emoji = 53,
Glagolitic = 54,
Lisu = 55,
Vai = 56,
NKo = 57,
Osmanya = 58,
PhagsPa = 59,
Gothic = 60,
Deseret = 61,
Tifinagh = 62,
CharRepMax = 63,
// RE10Mode = 1, this enum value conflicts with ApplyLater
// UseAtFont = 2, this enum value conflicts with TrackParms
// TextFlowMask = 12, this enum value conflicts with HeavyWave
// TextFlowES = 0, this enum value conflicts with False
// TextFlowSW = 4, this enum value conflicts with ApplyTmp
// TextFlowWN = 8, this enum value conflicts with DisableSmartFont
// TextFlowNE = 12, this enum value conflicts with HeavyWave
// NoIME = 524288, this enum value conflicts with ListMinus
// SelfIME = 262144, this enum value conflicts with ListNoNumber
// NoUpScroll = 65536, this enum value conflicts with ListParentheses
// NoVpScroll = 262144, this enum value conflicts with ListNoNumber
// NoLink = 0, this enum value conflicts with False
// ClientLink = 1, this enum value conflicts with ApplyLater
// FriendlyLinkName = 2, this enum value conflicts with TrackParms
// FriendlyLinkAddress = 3, this enum value conflicts with CacheParms
// AutoLinkURL = 4, this enum value conflicts with ApplyTmp
// AutoLinkEmail = 5, this enum value conflicts with SelectionRow
// AutoLinkPhone = 6, this enum value conflicts with SelectionBlock
// AutoLinkPath = 7, this enum value conflicts with SelectionInlineShape
// CompressNone = 0, this enum value conflicts with False
// CompressPunctuation = 1, this enum value conflicts with ApplyLater
// CompressPunctuationAndKana = 2, this enum value conflicts with TrackParms
// CompressMax = 2, this enum value conflicts with TrackParms
// UnderlinePositionAuto = 0, this enum value conflicts with False
// UnderlinePositionBelow = 1, this enum value conflicts with ApplyLater
// UnderlinePositionAbove = 2, this enum value conflicts with TrackParms
// UnderlinePositionMax = 2, this enum value conflicts with TrackParms
// FontAlignmentAuto = 0, this enum value conflicts with False
// FontAlignmentTop = 1, this enum value conflicts with ApplyLater
// FontAlignmentBaseline = 2, this enum value conflicts with TrackParms
// FontAlignmentBottom = 3, this enum value conflicts with CacheParms
// FontAlignmentCenter = 4, this enum value conflicts with ApplyTmp
// FontAlignmentMax = 4, this enum value conflicts with ApplyTmp
// RubyBelow = 128, this enum value conflicts with FindStory
// RubyAlignCenter = 0, this enum value conflicts with False
// RubyAlign010 = 1, this enum value conflicts with ApplyLater
// RubyAlign121 = 2, this enum value conflicts with TrackParms
// RubyAlignLeft = 3, this enum value conflicts with CacheParms
// RubyAlignRight = 4, this enum value conflicts with ApplyTmp
// LimitsDefault = 0, this enum value conflicts with False
// LimitsUnderOver = 1, this enum value conflicts with ApplyLater
// LimitsSubSup = 2, this enum value conflicts with TrackParms
// UpperLimitAsSuperScript = 3, this enum value conflicts with CacheParms
// LimitsOpposite = 4, this enum value conflicts with ApplyTmp
// ShowLLimPlaceHldr = 8, this enum value conflicts with DisableSmartFont
// ShowULimPlaceHldr = 16, this enum value conflicts with SelReplace
// DontGrowWithContent = 64, this enum value conflicts with OpenAlways
// GrowWithContent = 128, this enum value conflicts with FindStory
// SubSupAlign = 1, this enum value conflicts with ApplyLater
// LimitAlignMask = 3, this enum value conflicts with CacheParms
// LimitAlignCenter = 0, this enum value conflicts with False
// LimitAlignLeft = 1, this enum value conflicts with ApplyLater
// LimitAlignRight = 2, this enum value conflicts with TrackParms
// ShowDegPlaceHldr = 8, this enum value conflicts with DisableSmartFont
// AlignDefault = 0, this enum value conflicts with False
// AlignMatchAscentDescent = 2, this enum value conflicts with TrackParms
// MathVariant = 32, this enum value conflicts with Start
// StyleDefault = 0, this enum value conflicts with False
// StyleScriptScriptCramped = 1, this enum value conflicts with ApplyLater
// StyleScriptScript = 2, this enum value conflicts with TrackParms
// StyleScriptCramped = 3, this enum value conflicts with CacheParms
// StyleScript = 4, this enum value conflicts with ApplyTmp
// StyleTextCramped = 5, this enum value conflicts with SelectionRow
// StyleText = 6, this enum value conflicts with SelectionBlock
// StyleDisplayCramped = 7, this enum value conflicts with SelectionInlineShape
// StyleDisplay = 8, this enum value conflicts with DisableSmartFont
// MathRelSize = 64, this enum value conflicts with OpenAlways
DecDecSize = 254,
DecSize = 255,
IncSize = 65,
IncIncSize = 66,
// GravityUI = 0, this enum value conflicts with False
// GravityBack = 1, this enum value conflicts with ApplyLater
// GravityFore = 2, this enum value conflicts with TrackParms
// GravityIn = 3, this enum value conflicts with CacheParms
// GravityOut = 4, this enum value conflicts with ApplyTmp
GravityBackward = 536870912,
// GravityForward = 1073741824, this enum value conflicts with CharRepFromLcid
// AdjustCRLF = 1, this enum value conflicts with ApplyLater
// UseCRLF = 2, this enum value conflicts with TrackParms
// Textize = 4, this enum value conflicts with ApplyTmp
// AllowFinalEOP = 8, this enum value conflicts with DisableSmartFont
// FoldMathAlpha = 16, this enum value conflicts with SelReplace
// NoHidden = 32, this enum value conflicts with Start
// IncludeNumbering = 64, this enum value conflicts with OpenAlways
// TranslateTableCell = 128, this enum value conflicts with FindStory
// NoMathZoneBrackets = 256, this enum value conflicts with ClientCoord
// ConvertMathChar = 512, this enum value conflicts with AllowOffClient
// NoUCGreekItalic = 1024, this enum value conflicts with Transform
// AllowMathBold = 2048, this enum value conflicts with ObjectArg
// LanguageTag = 4096, this enum value conflicts with AtEnd
ConvertRTF = 8192,
// ApplyRtfDocProps = 16384, this enum value conflicts with ParaEffectTable
// PhantomShow = 1, this enum value conflicts with ApplyLater
// PhantomZeroWidth = 2, this enum value conflicts with TrackParms
// PhantomZeroAscent = 4, this enum value conflicts with ApplyTmp
// PhantomZeroDescent = 8, this enum value conflicts with DisableSmartFont
// PhantomTransparent = 16, this enum value conflicts with SelReplace
// PhantomASmash = 5, this enum value conflicts with SelectionRow
// PhantomDSmash = 9, this enum value conflicts with EnableSmartFont
// PhantomHSmash = 3, this enum value conflicts with CacheParms
// PhantomSmash = 13, this enum value conflicts with LongDash
// PhantomHorz = 12, this enum value conflicts with HeavyWave
// PhantomVert = 2, this enum value conflicts with TrackParms
// BoxHideTop = 1, this enum value conflicts with ApplyLater
// BoxHideBottom = 2, this enum value conflicts with TrackParms
// BoxHideLeft = 4, this enum value conflicts with ApplyTmp
// BoxHideRight = 8, this enum value conflicts with DisableSmartFont
// BoxStrikeH = 16, this enum value conflicts with SelReplace
// BoxStrikeV = 32, this enum value conflicts with Start
// BoxStrikeTLBR = 64, this enum value conflicts with OpenAlways
// BoxStrikeBLTR = 128, this enum value conflicts with FindStory
// BoxAlignCenter = 1, this enum value conflicts with ApplyLater
// SpaceMask = 28, this enum value conflicts with Telugu
// SpaceDefault = 0, this enum value conflicts with False
// SpaceUnary = 4, this enum value conflicts with ApplyTmp
// SpaceBinary = 8, this enum value conflicts with DisableSmartFont
// SpaceRelational = 12, this enum value conflicts with HeavyWave
// SpaceSkip = 16, this enum value conflicts with SelReplace
// SpaceOrd = 20, this enum value conflicts with ListNumberedThaiNum
// SpaceDifferential = 24, this enum value conflicts with Gurmukhi
// SizeText = 32, this enum value conflicts with Start
// SizeScript = 64, this enum value conflicts with OpenAlways
SizeScriptScript = 96,
// NoBreak = 128, this enum value conflicts with FindStory
// TransparentForPositioning = 256, this enum value conflicts with ClientCoord
// TransparentForSpacing = 512, this enum value conflicts with AllowOffClient
// StretchCharBelow = 0, this enum value conflicts with False
// StretchCharAbove = 1, this enum value conflicts with ApplyLater
// StretchBaseBelow = 2, this enum value conflicts with TrackParms
// StretchBaseAbove = 3, this enum value conflicts with CacheParms
// MatrixAlignMask = 3, this enum value conflicts with CacheParms
// MatrixAlignCenter = 0, this enum value conflicts with False
// MatrixAlignTopRow = 1, this enum value conflicts with ApplyLater
// MatrixAlignBottomRow = 3, this enum value conflicts with CacheParms
// ShowMatPlaceHldr = 8, this enum value conflicts with DisableSmartFont
// EqArrayLayoutWidth = 1, this enum value conflicts with ApplyLater
// EqArrayAlignMask = 12, this enum value conflicts with HeavyWave
// EqArrayAlignCenter = 0, this enum value conflicts with False
// EqArrayAlignTopRow = 4, this enum value conflicts with ApplyTmp
// EqArrayAlignBottomRow = 12, this enum value conflicts with HeavyWave
// MathManualBreakMask = 127, this enum value conflicts with ScratchStory
MathBreakLeft = 125,
MathBreakCenter = 126,
// MathBreakRight = 127, this enum value conflicts with ScratchStory
// MathEqAlign = 128, this enum value conflicts with FindStory
MathArgShadingStart = 593,
MathArgShadingEnd = 594,
MathObjShadingStart = 595,
MathObjShadingEnd = 596,
// FunctionTypeNone = 0, this enum value conflicts with False
// FunctionTypeTakesArg = 1, this enum value conflicts with ApplyLater
// FunctionTypeTakesLim = 2, this enum value conflicts with TrackParms
// FunctionTypeTakesLim2 = 3, this enum value conflicts with CacheParms
// FunctionTypeIsLim = 4, this enum value conflicts with ApplyTmp
// MathParaAlignDefault = 0, this enum value conflicts with False
// MathParaAlignCenterGroup = 1, this enum value conflicts with ApplyLater
// MathParaAlignCenter = 2, this enum value conflicts with TrackParms
// MathParaAlignLeft = 3, this enum value conflicts with CacheParms
// MathParaAlignRight = 4, this enum value conflicts with ApplyTmp
// MathDispAlignMask = 3, this enum value conflicts with CacheParms
// MathDispAlignCenterGroup = 0, this enum value conflicts with False
// MathDispAlignCenter = 1, this enum value conflicts with ApplyLater
// MathDispAlignLeft = 2, this enum value conflicts with TrackParms
// MathDispAlignRight = 3, this enum value conflicts with CacheParms
// MathDispIntUnderOver = 4, this enum value conflicts with ApplyTmp
// MathDispFracTeX = 8, this enum value conflicts with DisableSmartFont
// MathDispNaryGrow = 16, this enum value conflicts with SelReplace
// MathDocEmptyArgMask = 96, this enum value conflicts with SizeScriptScript
// MathDocEmptyArgAuto = 0, this enum value conflicts with False
// MathDocEmptyArgAlways = 32, this enum value conflicts with Start
// MathDocEmptyArgNever = 64, this enum value conflicts with OpenAlways
// MathDocSbSpOpUnchanged = 128, this enum value conflicts with FindStory
MathDocDiffMask = 768,
// MathDocDiffDefault = 0, this enum value conflicts with False
// MathDocDiffUpright = 256, this enum value conflicts with ClientCoord
// MathDocDiffItalic = 512, this enum value conflicts with AllowOffClient
// MathDocDiffOpenItalic = 768, this enum value conflicts with MathDocDiffMask
// MathDispNarySubSup = 1024, this enum value conflicts with Transform
// MathDispDef = 2048, this enum value conflicts with ObjectArg
// MathEnableRtl = 4096, this enum value conflicts with AtEnd
// MathBrkBinMask = 196608, this enum value conflicts with ListPlain
// MathBrkBinBefore = 0, this enum value conflicts with False
// MathBrkBinAfter = 65536, this enum value conflicts with ListParentheses
// MathBrkBinDup = 131072, this enum value conflicts with ListPeriod
MathBrkBinSubMask = 786432,
// MathBrkBinSubMM = 0, this enum value conflicts with False
// MathBrkBinSubPM = 262144, this enum value conflicts with ListNoNumber
// MathBrkBinSubMP = 524288, this enum value conflicts with ListMinus
SelRange = 597,
// Hstring = 596, this enum value conflicts with MathObjShadingEnd
FontPropTeXStyle = 828,
FontPropAlign = 829,
FontStretch = 830,
FontStyle = 831,
// FontStyleUpright = 0, this enum value conflicts with False
// FontStyleOblique = 1, this enum value conflicts with ApplyLater
// FontStyleItalic = 2, this enum value conflicts with TrackParms
// FontStretchDefault = 0, this enum value conflicts with False
// FontStretchUltraCondensed = 1, this enum value conflicts with ApplyLater
// FontStretchExtraCondensed = 2, this enum value conflicts with TrackParms
// FontStretchCondensed = 3, this enum value conflicts with CacheParms
// FontStretchSemiCondensed = 4, this enum value conflicts with ApplyTmp
// FontStretchNormal = 5, this enum value conflicts with SelectionRow
// FontStretchSemiExpanded = 6, this enum value conflicts with SelectionBlock
// FontStretchExpanded = 7, this enum value conflicts with SelectionInlineShape
// FontStretchExtraExpanded = 8, this enum value conflicts with DisableSmartFont
// FontStretchUltraExpanded = 9, this enum value conflicts with EnableSmartFont
// FontWeightDefault = 0, this enum value conflicts with False
FontWeightThin = 100,
FontWeightExtraLight = 200,
FontWeightLight = 300,
FontWeightNormal = 400,
// FontWeightRegular = 400, this enum value conflicts with FontWeightNormal
FontWeightMedium = 500,
FontWeightSemiBold = 600,
FontWeightBold = 700,
FontWeightExtraBold = 800,
FontWeightBlack = 900,
// FontWeightHeavy = 900, this enum value conflicts with FontWeightBlack
FontWeightExtraBlack = 950,
ParaPropMathAlign = 1079,
// DocMathBuild = 128, this enum value conflicts with FindStory
// MathLMargin = 129, this enum value conflicts with ReplaceStory
MathRMargin = 130,
MathWrapIndent = 131,
MathWrapRight = 132,
MathPostSpace = 134,
MathPreSpace = 133,
MathInterSpace = 135,
MathIntraSpace = 136,
CanCopy = 137,
CanRedo = 138,
CanUndo = 139,
UndoLimit = 140,
DocAutoLink = 141,
EllipsisMode = 142,
EllipsisState = 143,
// EllipsisNone = 0, this enum value conflicts with False
// EllipsisEnd = 1, this enum value conflicts with ApplyLater
// EllipsisWord = 3, this enum value conflicts with CacheParms
// EllipsisPresent = 1, this enum value conflicts with ApplyLater
// VTopCell = 1, this enum value conflicts with ApplyLater
// VLowCell = 2, this enum value conflicts with TrackParms
// HStartCell = 4, this enum value conflicts with ApplyTmp
// HContCell = 8, this enum value conflicts with DisableSmartFont
// RowUpdate = 1, this enum value conflicts with ApplyLater
// RowApplyDefault = 0, this enum value conflicts with False
// CellStructureChangeOnly = 1, this enum value conflicts with ApplyLater
RowHeightActual = 2059,
};
pub const tomFalse = tomConstants.False;
pub const tomTrue = tomConstants.True;
pub const tomUndefined = tomConstants.Undefined;
pub const tomToggle = tomConstants.Toggle;
pub const tomAutoColor = tomConstants.AutoColor;
pub const tomDefault = tomConstants.Default;
pub const tomSuspend = tomConstants.Suspend;
pub const tomResume = tomConstants.Resume;
pub const tomApplyNow = tomConstants.False;
pub const tomApplyLater = tomConstants.ApplyLater;
pub const tomTrackParms = tomConstants.TrackParms;
pub const tomCacheParms = tomConstants.CacheParms;
pub const tomApplyTmp = tomConstants.ApplyTmp;
pub const tomDisableSmartFont = tomConstants.DisableSmartFont;
pub const tomEnableSmartFont = tomConstants.EnableSmartFont;
pub const tomUsePoints = tomConstants.UsePoints;
pub const tomUseTwips = tomConstants.UseTwips;
pub const tomBackward = tomConstants.Backward;
pub const tomForward = tomConstants.Forward;
pub const tomMove = tomConstants.False;
pub const tomExtend = tomConstants.ApplyLater;
pub const tomNoSelection = tomConstants.False;
pub const tomSelectionIP = tomConstants.ApplyLater;
pub const tomSelectionNormal = tomConstants.TrackParms;
pub const tomSelectionFrame = tomConstants.CacheParms;
pub const tomSelectionColumn = tomConstants.ApplyTmp;
pub const tomSelectionRow = tomConstants.SelectionRow;
pub const tomSelectionBlock = tomConstants.SelectionBlock;
pub const tomSelectionInlineShape = tomConstants.SelectionInlineShape;
pub const tomSelectionShape = tomConstants.DisableSmartFont;
pub const tomSelStartActive = tomConstants.ApplyLater;
pub const tomSelAtEOL = tomConstants.TrackParms;
pub const tomSelOvertype = tomConstants.ApplyTmp;
pub const tomSelActive = tomConstants.DisableSmartFont;
pub const tomSelReplace = tomConstants.SelReplace;
pub const tomEnd = tomConstants.False;
pub const tomStart = tomConstants.Start;
pub const tomCollapseEnd = tomConstants.False;
pub const tomCollapseStart = tomConstants.ApplyLater;
pub const tomClientCoord = tomConstants.ClientCoord;
pub const tomAllowOffClient = tomConstants.AllowOffClient;
pub const tomTransform = tomConstants.Transform;
pub const tomObjectArg = tomConstants.ObjectArg;
pub const tomAtEnd = tomConstants.AtEnd;
pub const tomNone = tomConstants.False;
pub const tomSingle = tomConstants.ApplyLater;
pub const tomWords = tomConstants.TrackParms;
pub const tomDouble = tomConstants.CacheParms;
pub const tomDotted = tomConstants.ApplyTmp;
pub const tomDash = tomConstants.SelectionRow;
pub const tomDashDot = tomConstants.SelectionBlock;
pub const tomDashDotDot = tomConstants.SelectionInlineShape;
pub const tomWave = tomConstants.DisableSmartFont;
pub const tomThick = tomConstants.EnableSmartFont;
pub const tomHair = tomConstants.UsePoints;
pub const tomDoubleWave = tomConstants.UseTwips;
pub const tomHeavyWave = tomConstants.HeavyWave;
pub const tomLongDash = tomConstants.LongDash;
pub const tomThickDash = tomConstants.ThickDash;
pub const tomThickDashDot = tomConstants.ThickDashDot;
pub const tomThickDashDotDot = tomConstants.SelReplace;
pub const tomThickDotted = tomConstants.ThickDotted;
pub const tomThickLongDash = tomConstants.ThickLongDash;
pub const tomLineSpaceSingle = tomConstants.False;
pub const tomLineSpace1pt5 = tomConstants.ApplyLater;
pub const tomLineSpaceDouble = tomConstants.TrackParms;
pub const tomLineSpaceAtLeast = tomConstants.CacheParms;
pub const tomLineSpaceExactly = tomConstants.ApplyTmp;
pub const tomLineSpaceMultiple = tomConstants.SelectionRow;
pub const tomLineSpacePercent = tomConstants.SelectionBlock;
pub const tomAlignLeft = tomConstants.False;
pub const tomAlignCenter = tomConstants.ApplyLater;
pub const tomAlignRight = tomConstants.TrackParms;
pub const tomAlignJustify = tomConstants.CacheParms;
pub const tomAlignDecimal = tomConstants.CacheParms;
pub const tomAlignBar = tomConstants.ApplyTmp;
pub const tomDefaultTab = tomConstants.SelectionRow;
pub const tomAlignInterWord = tomConstants.CacheParms;
pub const tomAlignNewspaper = tomConstants.ApplyTmp;
pub const tomAlignInterLetter = tomConstants.SelectionRow;
pub const tomAlignScaled = tomConstants.SelectionBlock;
pub const tomSpaces = tomConstants.False;
pub const tomDots = tomConstants.ApplyLater;
pub const tomDashes = tomConstants.TrackParms;
pub const tomLines = tomConstants.CacheParms;
pub const tomThickLines = tomConstants.ApplyTmp;
pub const tomEquals = tomConstants.SelectionRow;
pub const tomTabBack = tomConstants.TabBack;
pub const tomTabNext = tomConstants.TabNext;
pub const tomTabHere = tomConstants.True;
pub const tomListNone = tomConstants.False;
pub const tomListBullet = tomConstants.ApplyLater;
pub const tomListNumberAsArabic = tomConstants.TrackParms;
pub const tomListNumberAsLCLetter = tomConstants.CacheParms;
pub const tomListNumberAsUCLetter = tomConstants.ApplyTmp;
pub const tomListNumberAsLCRoman = tomConstants.SelectionRow;
pub const tomListNumberAsUCRoman = tomConstants.SelectionBlock;
pub const tomListNumberAsSequence = tomConstants.SelectionInlineShape;
pub const tomListNumberedCircle = tomConstants.DisableSmartFont;
pub const tomListNumberedBlackCircleWingding = tomConstants.EnableSmartFont;
pub const tomListNumberedWhiteCircleWingding = tomConstants.UsePoints;
pub const tomListNumberedArabicWide = tomConstants.UseTwips;
pub const tomListNumberedChS = tomConstants.HeavyWave;
pub const tomListNumberedChT = tomConstants.LongDash;
pub const tomListNumberedJpnChS = tomConstants.ThickDash;
pub const tomListNumberedJpnKor = tomConstants.ThickDashDot;
pub const tomListNumberedArabic1 = tomConstants.SelReplace;
pub const tomListNumberedArabic2 = tomConstants.ThickDotted;
pub const tomListNumberedHebrew = tomConstants.ThickLongDash;
pub const tomListNumberedThaiAlpha = tomConstants.ListNumberedThaiAlpha;
pub const tomListNumberedThaiNum = tomConstants.ListNumberedThaiNum;
pub const tomListNumberedHindiAlpha = tomConstants.ListNumberedHindiAlpha;
pub const tomListNumberedHindiAlpha1 = tomConstants.ListNumberedHindiAlpha1;
pub const tomListNumberedHindiNum = tomConstants.ListNumberedHindiNum;
pub const tomListParentheses = tomConstants.ListParentheses;
pub const tomListPeriod = tomConstants.ListPeriod;
pub const tomListPlain = tomConstants.ListPlain;
pub const tomListNoNumber = tomConstants.ListNoNumber;
pub const tomListMinus = tomConstants.ListMinus;
pub const tomIgnoreNumberStyle = tomConstants.IgnoreNumberStyle;
pub const tomParaStyleNormal = tomConstants.True;
pub const tomParaStyleHeading1 = tomConstants.TabNext;
pub const tomParaStyleHeading2 = tomConstants.TabBack;
pub const tomParaStyleHeading3 = tomConstants.ParaStyleHeading3;
pub const tomParaStyleHeading4 = tomConstants.ParaStyleHeading4;
pub const tomParaStyleHeading5 = tomConstants.ParaStyleHeading5;
pub const tomParaStyleHeading6 = tomConstants.ParaStyleHeading6;
pub const tomParaStyleHeading7 = tomConstants.ParaStyleHeading7;
pub const tomParaStyleHeading8 = tomConstants.ParaStyleHeading8;
pub const tomParaStyleHeading9 = tomConstants.ParaStyleHeading9;
pub const tomCharacter = tomConstants.ApplyLater;
pub const tomWord = tomConstants.TrackParms;
pub const tomSentence = tomConstants.CacheParms;
pub const tomParagraph = tomConstants.ApplyTmp;
pub const tomLine = tomConstants.SelectionRow;
pub const tomStory = tomConstants.SelectionBlock;
pub const tomScreen = tomConstants.SelectionInlineShape;
pub const tomSection = tomConstants.DisableSmartFont;
pub const tomTableColumn = tomConstants.EnableSmartFont;
pub const tomColumn = tomConstants.EnableSmartFont;
pub const tomRow = tomConstants.UsePoints;
pub const tomWindow = tomConstants.UseTwips;
pub const tomCell = tomConstants.HeavyWave;
pub const tomCharFormat = tomConstants.LongDash;
pub const tomParaFormat = tomConstants.ThickDash;
pub const tomTable = tomConstants.ThickDashDot;
pub const tomObject = tomConstants.SelReplace;
pub const tomPage = tomConstants.ThickDotted;
pub const tomHardParagraph = tomConstants.ThickLongDash;
pub const tomCluster = tomConstants.ListNumberedThaiAlpha;
pub const tomInlineObject = tomConstants.ListNumberedThaiNum;
pub const tomInlineObjectArg = tomConstants.ListNumberedHindiAlpha;
pub const tomLeafLine = tomConstants.ListNumberedHindiAlpha1;
pub const tomLayoutColumn = tomConstants.ListNumberedHindiNum;
pub const tomProcessId = tomConstants.ProcessId;
pub const tomMatchWord = tomConstants.TrackParms;
pub const tomMatchCase = tomConstants.ApplyTmp;
pub const tomMatchPattern = tomConstants.DisableSmartFont;
pub const tomUnknownStory = tomConstants.False;
pub const tomMainTextStory = tomConstants.ApplyLater;
pub const tomFootnotesStory = tomConstants.TrackParms;
pub const tomEndnotesStory = tomConstants.CacheParms;
pub const tomCommentsStory = tomConstants.ApplyTmp;
pub const tomTextFrameStory = tomConstants.SelectionRow;
pub const tomEvenPagesHeaderStory = tomConstants.SelectionBlock;
pub const tomPrimaryHeaderStory = tomConstants.SelectionInlineShape;
pub const tomEvenPagesFooterStory = tomConstants.DisableSmartFont;
pub const tomPrimaryFooterStory = tomConstants.EnableSmartFont;
pub const tomFirstPageHeaderStory = tomConstants.UsePoints;
pub const tomFirstPageFooterStory = tomConstants.UseTwips;
pub const tomScratchStory = tomConstants.ScratchStory;
pub const tomFindStory = tomConstants.FindStory;
pub const tomReplaceStory = tomConstants.ReplaceStory;
pub const tomStoryInactive = tomConstants.False;
pub const tomStoryActiveDisplay = tomConstants.ApplyLater;
pub const tomStoryActiveUI = tomConstants.TrackParms;
pub const tomStoryActiveDisplayUI = tomConstants.CacheParms;
pub const tomNoAnimation = tomConstants.False;
pub const tomLasVegasLights = tomConstants.ApplyLater;
pub const tomBlinkingBackground = tomConstants.TrackParms;
pub const tomSparkleText = tomConstants.CacheParms;
pub const tomMarchingBlackAnts = tomConstants.ApplyTmp;
pub const tomMarchingRedAnts = tomConstants.SelectionRow;
pub const tomShimmer = tomConstants.SelectionBlock;
pub const tomWipeDown = tomConstants.SelectionInlineShape;
pub const tomWipeRight = tomConstants.DisableSmartFont;
pub const tomAnimationMax = tomConstants.DisableSmartFont;
pub const tomLowerCase = tomConstants.False;
pub const tomUpperCase = tomConstants.ApplyLater;
pub const tomTitleCase = tomConstants.TrackParms;
pub const tomSentenceCase = tomConstants.ApplyTmp;
pub const tomToggleCase = tomConstants.SelectionRow;
pub const tomReadOnly = tomConstants.ClientCoord;
pub const tomShareDenyRead = tomConstants.AllowOffClient;
pub const tomShareDenyWrite = tomConstants.Transform;
pub const tomPasteFile = tomConstants.AtEnd;
pub const tomCreateNew = tomConstants.SelReplace;
pub const tomCreateAlways = tomConstants.Start;
pub const tomOpenExisting = tomConstants.OpenExisting;
pub const tomOpenAlways = tomConstants.OpenAlways;
pub const tomTruncateExisting = tomConstants.TruncateExisting;
pub const tomRTF = tomConstants.ApplyLater;
pub const tomText = tomConstants.TrackParms;
pub const tomHTML = tomConstants.CacheParms;
pub const tomWordDocument = tomConstants.ApplyTmp;
pub const tomBold = tomConstants.Bold;
pub const tomItalic = tomConstants.Italic;
pub const tomUnderline = tomConstants.Underline;
pub const tomStrikeout = tomConstants.Strikeout;
pub const tomProtected = tomConstants.Protected;
pub const tomLink = tomConstants.Link;
pub const tomSmallCaps = tomConstants.SmallCaps;
pub const tomAllCaps = tomConstants.AllCaps;
pub const tomHidden = tomConstants.Hidden;
pub const tomOutline = tomConstants.Outline;
pub const tomShadow = tomConstants.Shadow;
pub const tomEmboss = tomConstants.Emboss;
pub const tomImprint = tomConstants.Imprint;
pub const tomDisabled = tomConstants.Disabled;
pub const tomRevised = tomConstants.Revised;
pub const tomSubscriptCF = tomConstants.SubscriptCF;
pub const tomSuperscriptCF = tomConstants.SuperscriptCF;
pub const tomFontBound = tomConstants.FontBound;
pub const tomLinkProtected = tomConstants.LinkProtected;
pub const tomInlineObjectStart = tomConstants.InlineObjectStart;
pub const tomExtendedChar = tomConstants.ExtendedChar;
pub const tomAutoBackColor = tomConstants.AutoBackColor;
pub const tomMathZoneNoBuildUp = tomConstants.MathZoneNoBuildUp;
pub const tomMathZone = tomConstants.MathZone;
pub const tomMathZoneOrdinary = tomConstants.MathZoneOrdinary;
pub const tomAutoTextColor = tomConstants.AutoTextColor;
pub const tomMathZoneDisplay = tomConstants.ListNoNumber;
pub const tomParaEffectRTL = tomConstants.ApplyLater;
pub const tomParaEffectKeep = tomConstants.TrackParms;
pub const tomParaEffectKeepNext = tomConstants.ApplyTmp;
pub const tomParaEffectPageBreakBefore = tomConstants.DisableSmartFont;
pub const tomParaEffectNoLineNumber = tomConstants.SelReplace;
pub const tomParaEffectNoWidowControl = tomConstants.Start;
pub const tomParaEffectDoNotHyphen = tomConstants.OpenAlways;
pub const tomParaEffectSideBySide = tomConstants.FindStory;
pub const tomParaEffectCollapsed = tomConstants.ClientCoord;
pub const tomParaEffectOutlineLevel = tomConstants.AllowOffClient;
pub const tomParaEffectBox = tomConstants.Transform;
pub const tomParaEffectTableRowDelimiter = tomConstants.AtEnd;
pub const tomParaEffectTable = tomConstants.ParaEffectTable;
pub const tomModWidthPairs = tomConstants.ApplyLater;
pub const tomModWidthSpace = tomConstants.TrackParms;
pub const tomAutoSpaceAlpha = tomConstants.ApplyTmp;
pub const tomAutoSpaceNumeric = tomConstants.DisableSmartFont;
pub const tomAutoSpaceParens = tomConstants.SelReplace;
pub const tomEmbeddedFont = tomConstants.Start;
pub const tomDoublestrike = tomConstants.OpenAlways;
pub const tomOverlapping = tomConstants.FindStory;
pub const tomNormalCaret = tomConstants.False;
pub const tomKoreanBlockCaret = tomConstants.ApplyLater;
pub const tomNullCaret = tomConstants.TrackParms;
pub const tomIncludeInset = tomConstants.ApplyLater;
pub const tomUnicodeBiDi = tomConstants.ApplyLater;
pub const tomMathCFCheck = tomConstants.ApplyTmp;
pub const tomUnlink = tomConstants.DisableSmartFont;
pub const tomUnhide = tomConstants.SelReplace;
pub const tomCheckTextLimit = tomConstants.Start;
pub const tomIgnoreCurrentFont = tomConstants.False;
pub const tomMatchCharRep = tomConstants.ApplyLater;
pub const tomMatchFontSignature = tomConstants.TrackParms;
pub const tomMatchAscii = tomConstants.ApplyTmp;
pub const tomGetHeightOnly = tomConstants.DisableSmartFont;
pub const tomMatchMathFont = tomConstants.SelReplace;
pub const tomCharset = tomConstants.Charset;
pub const tomCharRepFromLcid = tomConstants.CharRepFromLcid;
pub const tomAnsi = tomConstants.False;
pub const tomEastEurope = tomConstants.ApplyLater;
pub const tomCyrillic = tomConstants.TrackParms;
pub const tomGreek = tomConstants.CacheParms;
pub const tomTurkish = tomConstants.ApplyTmp;
pub const tomHebrew = tomConstants.SelectionRow;
pub const tomArabic = tomConstants.SelectionBlock;
pub const tomBaltic = tomConstants.SelectionInlineShape;
pub const tomVietnamese = tomConstants.DisableSmartFont;
pub const tomDefaultCharRep = tomConstants.EnableSmartFont;
pub const tomSymbol = tomConstants.UsePoints;
pub const tomThai = tomConstants.UseTwips;
pub const tomShiftJIS = tomConstants.HeavyWave;
pub const tomGB2312 = tomConstants.LongDash;
pub const tomHangul = tomConstants.ThickDash;
pub const tomBIG5 = tomConstants.ThickDashDot;
pub const tomPC437 = tomConstants.SelReplace;
pub const tomOEM = tomConstants.ThickDotted;
pub const tomMac = tomConstants.ThickLongDash;
pub const tomArmenian = tomConstants.ListNumberedThaiAlpha;
pub const tomSyriac = tomConstants.ListNumberedThaiNum;
pub const tomThaana = tomConstants.ListNumberedHindiAlpha;
pub const tomDevanagari = tomConstants.ListNumberedHindiAlpha1;
pub const tomBengali = tomConstants.ListNumberedHindiNum;
pub const tomGurmukhi = tomConstants.Gurmukhi;
pub const tomGujarati = tomConstants.Gujarati;
pub const tomOriya = tomConstants.Oriya;
pub const tomTamil = tomConstants.Tamil;
pub const tomTelugu = tomConstants.Telugu;
pub const tomKannada = tomConstants.Kannada;
pub const tomMalayalam = tomConstants.Malayalam;
pub const tomSinhala = tomConstants.Sinhala;
pub const tomLao = tomConstants.Start;
pub const tomTibetan = tomConstants.Tibetan;
pub const tomMyanmar = tomConstants.Myanmar;
pub const tomGeorgian = tomConstants.Georgian;
pub const tomJamo = tomConstants.Jamo;
pub const tomEthiopic = tomConstants.Ethiopic;
pub const tomCherokee = tomConstants.Cherokee;
pub const tomAboriginal = tomConstants.Aboriginal;
pub const tomOgham = tomConstants.Ogham;
pub const tomRunic = tomConstants.Runic;
pub const tomKhmer = tomConstants.Khmer;
pub const tomMongolian = tomConstants.Mongolian;
pub const tomBraille = tomConstants.Braille;
pub const tomYi = tomConstants.Yi;
pub const tomLimbu = tomConstants.Limbu;
pub const tomTaiLe = tomConstants.TaiLe;
pub const tomNewTaiLue = tomConstants.OpenExisting;
pub const tomSylotiNagri = tomConstants.SylotiNagri;
pub const tomKharoshthi = tomConstants.Kharoshthi;
pub const tomKayahli = tomConstants.Kayahli;
pub const tomUsymbol = tomConstants.Usymbol;
pub const tomEmoji = tomConstants.Emoji;
pub const tomGlagolitic = tomConstants.Glagolitic;
pub const tomLisu = tomConstants.Lisu;
pub const tomVai = tomConstants.Vai;
pub const tomNKo = tomConstants.NKo;
pub const tomOsmanya = tomConstants.Osmanya;
pub const tomPhagsPa = tomConstants.PhagsPa;
pub const tomGothic = tomConstants.Gothic;
pub const tomDeseret = tomConstants.Deseret;
pub const tomTifinagh = tomConstants.Tifinagh;
pub const tomCharRepMax = tomConstants.CharRepMax;
pub const tomRE10Mode = tomConstants.ApplyLater;
pub const tomUseAtFont = tomConstants.TrackParms;
pub const tomTextFlowMask = tomConstants.HeavyWave;
pub const tomTextFlowES = tomConstants.False;
pub const tomTextFlowSW = tomConstants.ApplyTmp;
pub const tomTextFlowWN = tomConstants.DisableSmartFont;
pub const tomTextFlowNE = tomConstants.HeavyWave;
pub const tomNoIME = tomConstants.ListMinus;
pub const tomSelfIME = tomConstants.ListNoNumber;
pub const tomNoUpScroll = tomConstants.ListParentheses;
pub const tomNoVpScroll = tomConstants.ListNoNumber;
pub const tomNoLink = tomConstants.False;
pub const tomClientLink = tomConstants.ApplyLater;
pub const tomFriendlyLinkName = tomConstants.TrackParms;
pub const tomFriendlyLinkAddress = tomConstants.CacheParms;
pub const tomAutoLinkURL = tomConstants.ApplyTmp;
pub const tomAutoLinkEmail = tomConstants.SelectionRow;
pub const tomAutoLinkPhone = tomConstants.SelectionBlock;
pub const tomAutoLinkPath = tomConstants.SelectionInlineShape;
pub const tomCompressNone = tomConstants.False;
pub const tomCompressPunctuation = tomConstants.ApplyLater;
pub const tomCompressPunctuationAndKana = tomConstants.TrackParms;
pub const tomCompressMax = tomConstants.TrackParms;
pub const tomUnderlinePositionAuto = tomConstants.False;
pub const tomUnderlinePositionBelow = tomConstants.ApplyLater;
pub const tomUnderlinePositionAbove = tomConstants.TrackParms;
pub const tomUnderlinePositionMax = tomConstants.TrackParms;
pub const tomFontAlignmentAuto = tomConstants.False;
pub const tomFontAlignmentTop = tomConstants.ApplyLater;
pub const tomFontAlignmentBaseline = tomConstants.TrackParms;
pub const tomFontAlignmentBottom = tomConstants.CacheParms;
pub const tomFontAlignmentCenter = tomConstants.ApplyTmp;
pub const tomFontAlignmentMax = tomConstants.ApplyTmp;
pub const tomRubyBelow = tomConstants.FindStory;
pub const tomRubyAlignCenter = tomConstants.False;
pub const tomRubyAlign010 = tomConstants.ApplyLater;
pub const tomRubyAlign121 = tomConstants.TrackParms;
pub const tomRubyAlignLeft = tomConstants.CacheParms;
pub const tomRubyAlignRight = tomConstants.ApplyTmp;
pub const tomLimitsDefault = tomConstants.False;
pub const tomLimitsUnderOver = tomConstants.ApplyLater;
pub const tomLimitsSubSup = tomConstants.TrackParms;
pub const tomUpperLimitAsSuperScript = tomConstants.CacheParms;
pub const tomLimitsOpposite = tomConstants.ApplyTmp;
pub const tomShowLLimPlaceHldr = tomConstants.DisableSmartFont;
pub const tomShowULimPlaceHldr = tomConstants.SelReplace;
pub const tomDontGrowWithContent = tomConstants.OpenAlways;
pub const tomGrowWithContent = tomConstants.FindStory;
pub const tomSubSupAlign = tomConstants.ApplyLater;
pub const tomLimitAlignMask = tomConstants.CacheParms;
pub const tomLimitAlignCenter = tomConstants.False;
pub const tomLimitAlignLeft = tomConstants.ApplyLater;
pub const tomLimitAlignRight = tomConstants.TrackParms;
pub const tomShowDegPlaceHldr = tomConstants.DisableSmartFont;
pub const tomAlignDefault = tomConstants.False;
pub const tomAlignMatchAscentDescent = tomConstants.TrackParms;
pub const tomMathVariant = tomConstants.Start;
pub const tomStyleDefault = tomConstants.False;
pub const tomStyleScriptScriptCramped = tomConstants.ApplyLater;
pub const tomStyleScriptScript = tomConstants.TrackParms;
pub const tomStyleScriptCramped = tomConstants.CacheParms;
pub const tomStyleScript = tomConstants.ApplyTmp;
pub const tomStyleTextCramped = tomConstants.SelectionRow;
pub const tomStyleText = tomConstants.SelectionBlock;
pub const tomStyleDisplayCramped = tomConstants.SelectionInlineShape;
pub const tomStyleDisplay = tomConstants.DisableSmartFont;
pub const tomMathRelSize = tomConstants.OpenAlways;
pub const tomDecDecSize = tomConstants.DecDecSize;
pub const tomDecSize = tomConstants.DecSize;
pub const tomIncSize = tomConstants.IncSize;
pub const tomIncIncSize = tomConstants.IncIncSize;
pub const tomGravityUI = tomConstants.False;
pub const tomGravityBack = tomConstants.ApplyLater;
pub const tomGravityFore = tomConstants.TrackParms;
pub const tomGravityIn = tomConstants.CacheParms;
pub const tomGravityOut = tomConstants.ApplyTmp;
pub const tomGravityBackward = tomConstants.GravityBackward;
pub const tomGravityForward = tomConstants.CharRepFromLcid;
pub const tomAdjustCRLF = tomConstants.ApplyLater;
pub const tomUseCRLF = tomConstants.TrackParms;
pub const tomTextize = tomConstants.ApplyTmp;
pub const tomAllowFinalEOP = tomConstants.DisableSmartFont;
pub const tomFoldMathAlpha = tomConstants.SelReplace;
pub const tomNoHidden = tomConstants.Start;
pub const tomIncludeNumbering = tomConstants.OpenAlways;
pub const tomTranslateTableCell = tomConstants.FindStory;
pub const tomNoMathZoneBrackets = tomConstants.ClientCoord;
pub const tomConvertMathChar = tomConstants.AllowOffClient;
pub const tomNoUCGreekItalic = tomConstants.Transform;
pub const tomAllowMathBold = tomConstants.ObjectArg;
pub const tomLanguageTag = tomConstants.AtEnd;
pub const tomConvertRTF = tomConstants.ConvertRTF;
pub const tomApplyRtfDocProps = tomConstants.ParaEffectTable;
pub const tomPhantomShow = tomConstants.ApplyLater;
pub const tomPhantomZeroWidth = tomConstants.TrackParms;
pub const tomPhantomZeroAscent = tomConstants.ApplyTmp;
pub const tomPhantomZeroDescent = tomConstants.DisableSmartFont;
pub const tomPhantomTransparent = tomConstants.SelReplace;
pub const tomPhantomASmash = tomConstants.SelectionRow;
pub const tomPhantomDSmash = tomConstants.EnableSmartFont;
pub const tomPhantomHSmash = tomConstants.CacheParms;
pub const tomPhantomSmash = tomConstants.LongDash;
pub const tomPhantomHorz = tomConstants.HeavyWave;
pub const tomPhantomVert = tomConstants.TrackParms;
pub const tomBoxHideTop = tomConstants.ApplyLater;
pub const tomBoxHideBottom = tomConstants.TrackParms;
pub const tomBoxHideLeft = tomConstants.ApplyTmp;
pub const tomBoxHideRight = tomConstants.DisableSmartFont;
pub const tomBoxStrikeH = tomConstants.SelReplace;
pub const tomBoxStrikeV = tomConstants.Start;
pub const tomBoxStrikeTLBR = tomConstants.OpenAlways;
pub const tomBoxStrikeBLTR = tomConstants.FindStory;
pub const tomBoxAlignCenter = tomConstants.ApplyLater;
pub const tomSpaceMask = tomConstants.Telugu;
pub const tomSpaceDefault = tomConstants.False;
pub const tomSpaceUnary = tomConstants.ApplyTmp;
pub const tomSpaceBinary = tomConstants.DisableSmartFont;
pub const tomSpaceRelational = tomConstants.HeavyWave;
pub const tomSpaceSkip = tomConstants.SelReplace;
pub const tomSpaceOrd = tomConstants.ListNumberedThaiNum;
pub const tomSpaceDifferential = tomConstants.Gurmukhi;
pub const tomSizeText = tomConstants.Start;
pub const tomSizeScript = tomConstants.OpenAlways;
pub const tomSizeScriptScript = tomConstants.SizeScriptScript;
pub const tomNoBreak = tomConstants.FindStory;
pub const tomTransparentForPositioning = tomConstants.ClientCoord;
pub const tomTransparentForSpacing = tomConstants.AllowOffClient;
pub const tomStretchCharBelow = tomConstants.False;
pub const tomStretchCharAbove = tomConstants.ApplyLater;
pub const tomStretchBaseBelow = tomConstants.TrackParms;
pub const tomStretchBaseAbove = tomConstants.CacheParms;
pub const tomMatrixAlignMask = tomConstants.CacheParms;
pub const tomMatrixAlignCenter = tomConstants.False;
pub const tomMatrixAlignTopRow = tomConstants.ApplyLater;
pub const tomMatrixAlignBottomRow = tomConstants.CacheParms;
pub const tomShowMatPlaceHldr = tomConstants.DisableSmartFont;
pub const tomEqArrayLayoutWidth = tomConstants.ApplyLater;
pub const tomEqArrayAlignMask = tomConstants.HeavyWave;
pub const tomEqArrayAlignCenter = tomConstants.False;
pub const tomEqArrayAlignTopRow = tomConstants.ApplyTmp;
pub const tomEqArrayAlignBottomRow = tomConstants.HeavyWave;
pub const tomMathManualBreakMask = tomConstants.ScratchStory;
pub const tomMathBreakLeft = tomConstants.MathBreakLeft;
pub const tomMathBreakCenter = tomConstants.MathBreakCenter;
pub const tomMathBreakRight = tomConstants.ScratchStory;
pub const tomMathEqAlign = tomConstants.FindStory;
pub const tomMathArgShadingStart = tomConstants.MathArgShadingStart;
pub const tomMathArgShadingEnd = tomConstants.MathArgShadingEnd;
pub const tomMathObjShadingStart = tomConstants.MathObjShadingStart;
pub const tomMathObjShadingEnd = tomConstants.MathObjShadingEnd;
pub const tomFunctionTypeNone = tomConstants.False;
pub const tomFunctionTypeTakesArg = tomConstants.ApplyLater;
pub const tomFunctionTypeTakesLim = tomConstants.TrackParms;
pub const tomFunctionTypeTakesLim2 = tomConstants.CacheParms;
pub const tomFunctionTypeIsLim = tomConstants.ApplyTmp;
pub const tomMathParaAlignDefault = tomConstants.False;
pub const tomMathParaAlignCenterGroup = tomConstants.ApplyLater;
pub const tomMathParaAlignCenter = tomConstants.TrackParms;
pub const tomMathParaAlignLeft = tomConstants.CacheParms;
pub const tomMathParaAlignRight = tomConstants.ApplyTmp;
pub const tomMathDispAlignMask = tomConstants.CacheParms;
pub const tomMathDispAlignCenterGroup = tomConstants.False;
pub const tomMathDispAlignCenter = tomConstants.ApplyLater;
pub const tomMathDispAlignLeft = tomConstants.TrackParms;
pub const tomMathDispAlignRight = tomConstants.CacheParms;
pub const tomMathDispIntUnderOver = tomConstants.ApplyTmp;
pub const tomMathDispFracTeX = tomConstants.DisableSmartFont;
pub const tomMathDispNaryGrow = tomConstants.SelReplace;
pub const tomMathDocEmptyArgMask = tomConstants.SizeScriptScript;
pub const tomMathDocEmptyArgAuto = tomConstants.False;
pub const tomMathDocEmptyArgAlways = tomConstants.Start;
pub const tomMathDocEmptyArgNever = tomConstants.OpenAlways;
pub const tomMathDocSbSpOpUnchanged = tomConstants.FindStory;
pub const tomMathDocDiffMask = tomConstants.MathDocDiffMask;
pub const tomMathDocDiffDefault = tomConstants.False;
pub const tomMathDocDiffUpright = tomConstants.ClientCoord;
pub const tomMathDocDiffItalic = tomConstants.AllowOffClient;
pub const tomMathDocDiffOpenItalic = tomConstants.MathDocDiffMask;
pub const tomMathDispNarySubSup = tomConstants.Transform;
pub const tomMathDispDef = tomConstants.ObjectArg;
pub const tomMathEnableRtl = tomConstants.AtEnd;
pub const tomMathBrkBinMask = tomConstants.ListPlain;
pub const tomMathBrkBinBefore = tomConstants.False;
pub const tomMathBrkBinAfter = tomConstants.ListParentheses;
pub const tomMathBrkBinDup = tomConstants.ListPeriod;
pub const tomMathBrkBinSubMask = tomConstants.MathBrkBinSubMask;
pub const tomMathBrkBinSubMM = tomConstants.False;
pub const tomMathBrkBinSubPM = tomConstants.ListNoNumber;
pub const tomMathBrkBinSubMP = tomConstants.ListMinus;
pub const tomSelRange = tomConstants.SelRange;
pub const tomHstring = tomConstants.MathObjShadingEnd;
pub const tomFontPropTeXStyle = tomConstants.FontPropTeXStyle;
pub const tomFontPropAlign = tomConstants.FontPropAlign;
pub const tomFontStretch = tomConstants.FontStretch;
pub const tomFontStyle = tomConstants.FontStyle;
pub const tomFontStyleUpright = tomConstants.False;
pub const tomFontStyleOblique = tomConstants.ApplyLater;
pub const tomFontStyleItalic = tomConstants.TrackParms;
pub const tomFontStretchDefault = tomConstants.False;
pub const tomFontStretchUltraCondensed = tomConstants.ApplyLater;
pub const tomFontStretchExtraCondensed = tomConstants.TrackParms;
pub const tomFontStretchCondensed = tomConstants.CacheParms;
pub const tomFontStretchSemiCondensed = tomConstants.ApplyTmp;
pub const tomFontStretchNormal = tomConstants.SelectionRow;
pub const tomFontStretchSemiExpanded = tomConstants.SelectionBlock;
pub const tomFontStretchExpanded = tomConstants.SelectionInlineShape;
pub const tomFontStretchExtraExpanded = tomConstants.DisableSmartFont;
pub const tomFontStretchUltraExpanded = tomConstants.EnableSmartFont;
pub const tomFontWeightDefault = tomConstants.False;
pub const tomFontWeightThin = tomConstants.FontWeightThin;
pub const tomFontWeightExtraLight = tomConstants.FontWeightExtraLight;
pub const tomFontWeightLight = tomConstants.FontWeightLight;
pub const tomFontWeightNormal = tomConstants.FontWeightNormal;
pub const tomFontWeightRegular = tomConstants.FontWeightNormal;
pub const tomFontWeightMedium = tomConstants.FontWeightMedium;
pub const tomFontWeightSemiBold = tomConstants.FontWeightSemiBold;
pub const tomFontWeightBold = tomConstants.FontWeightBold;
pub const tomFontWeightExtraBold = tomConstants.FontWeightExtraBold;
pub const tomFontWeightBlack = tomConstants.FontWeightBlack;
pub const tomFontWeightHeavy = tomConstants.FontWeightBlack;
pub const tomFontWeightExtraBlack = tomConstants.FontWeightExtraBlack;
pub const tomParaPropMathAlign = tomConstants.ParaPropMathAlign;
pub const tomDocMathBuild = tomConstants.FindStory;
pub const tomMathLMargin = tomConstants.ReplaceStory;
pub const tomMathRMargin = tomConstants.MathRMargin;
pub const tomMathWrapIndent = tomConstants.MathWrapIndent;
pub const tomMathWrapRight = tomConstants.MathWrapRight;
pub const tomMathPostSpace = tomConstants.MathPostSpace;
pub const tomMathPreSpace = tomConstants.MathPreSpace;
pub const tomMathInterSpace = tomConstants.MathInterSpace;
pub const tomMathIntraSpace = tomConstants.MathIntraSpace;
pub const tomCanCopy = tomConstants.CanCopy;
pub const tomCanRedo = tomConstants.CanRedo;
pub const tomCanUndo = tomConstants.CanUndo;
pub const tomUndoLimit = tomConstants.UndoLimit;
pub const tomDocAutoLink = tomConstants.DocAutoLink;
pub const tomEllipsisMode = tomConstants.EllipsisMode;
pub const tomEllipsisState = tomConstants.EllipsisState;
pub const tomEllipsisNone = tomConstants.False;
pub const tomEllipsisEnd = tomConstants.ApplyLater;
pub const tomEllipsisWord = tomConstants.CacheParms;
pub const tomEllipsisPresent = tomConstants.ApplyLater;
pub const tomVTopCell = tomConstants.ApplyLater;
pub const tomVLowCell = tomConstants.TrackParms;
pub const tomHStartCell = tomConstants.ApplyTmp;
pub const tomHContCell = tomConstants.DisableSmartFont;
pub const tomRowUpdate = tomConstants.ApplyLater;
pub const tomRowApplyDefault = tomConstants.False;
pub const tomCellStructureChangeOnly = tomConstants.ApplyLater;
pub const tomRowHeightActual = tomConstants.RowHeightActual;
pub const OBJECTTYPE = enum(i32) {
SimpleText = 0,
Ruby = 1,
HorzVert = 2,
Warichu = 3,
Eq = 9,
Math = 10,
// Accent = 10, this enum value conflicts with Math
Box = 11,
BoxedFormula = 12,
Brackets = 13,
BracketsWithSeps = 14,
EquationArray = 15,
Fraction = 16,
FunctionApply = 17,
LeftSubSup = 18,
LowerLimit = 19,
Matrix = 20,
Nary = 21,
OpChar = 22,
Overbar = 23,
Phantom = 24,
Radical = 25,
SlashedFraction = 26,
Stack = 27,
StretchStack = 28,
Subscript = 29,
SubSup = 30,
Superscript = 31,
Underbar = 32,
UpperLimit = 33,
// ObjectMax = 33, this enum value conflicts with UpperLimit
};
pub const tomSimpleText = OBJECTTYPE.SimpleText;
pub const tomRuby = OBJECTTYPE.Ruby;
pub const tomHorzVert = OBJECTTYPE.HorzVert;
pub const tomWarichu = OBJECTTYPE.Warichu;
pub const tomEq = OBJECTTYPE.Eq;
pub const tomMath = OBJECTTYPE.Math;
pub const tomAccent = OBJECTTYPE.Math;
pub const tomBox = OBJECTTYPE.Box;
pub const tomBoxedFormula = OBJECTTYPE.BoxedFormula;
pub const tomBrackets = OBJECTTYPE.Brackets;
pub const tomBracketsWithSeps = OBJECTTYPE.BracketsWithSeps;
pub const tomEquationArray = OBJECTTYPE.EquationArray;
pub const tomFraction = OBJECTTYPE.Fraction;
pub const tomFunctionApply = OBJECTTYPE.FunctionApply;
pub const tomLeftSubSup = OBJECTTYPE.LeftSubSup;
pub const tomLowerLimit = OBJECTTYPE.LowerLimit;
pub const tomMatrix = OBJECTTYPE.Matrix;
pub const tomNary = OBJECTTYPE.Nary;
pub const tomOpChar = OBJECTTYPE.OpChar;
pub const tomOverbar = OBJECTTYPE.Overbar;
pub const tomPhantom = OBJECTTYPE.Phantom;
pub const tomRadical = OBJECTTYPE.Radical;
pub const tomSlashedFraction = OBJECTTYPE.SlashedFraction;
pub const tomStack = OBJECTTYPE.Stack;
pub const tomStretchStack = OBJECTTYPE.StretchStack;
pub const tomSubscript = OBJECTTYPE.Subscript;
pub const tomSubSup = OBJECTTYPE.SubSup;
pub const tomSuperscript = OBJECTTYPE.Superscript;
pub const tomUnderbar = OBJECTTYPE.Underbar;
pub const tomUpperLimit = OBJECTTYPE.UpperLimit;
pub const tomObjectMax = OBJECTTYPE.UpperLimit;
pub const MANCODE = enum(i32) {
BOLD = 16,
ITAL = 32,
GREEK = 64,
ROMN = 0,
SCRP = 1,
FRAK = 2,
OPEN = 3,
SANS = 4,
MONO = 5,
MATH = 6,
ISOL = 7,
INIT = 8,
TAIL = 9,
STRCH = 10,
LOOP = 11,
OPENA = 12,
};
pub const MBOLD = MANCODE.BOLD;
pub const MITAL = MANCODE.ITAL;
pub const MGREEK = MANCODE.GREEK;
pub const MROMN = MANCODE.ROMN;
pub const MSCRP = MANCODE.SCRP;
pub const MFRAK = MANCODE.FRAK;
pub const MOPEN = MANCODE.OPEN;
pub const MSANS = MANCODE.SANS;
pub const MMONO = MANCODE.MONO;
pub const MMATH = MANCODE.MATH;
pub const MISOL = MANCODE.ISOL;
pub const MINIT = MANCODE.INIT;
pub const MTAIL = MANCODE.TAIL;
pub const MSTRCH = MANCODE.STRCH;
pub const MLOOP = MANCODE.LOOP;
pub const MOPENA = MANCODE.OPENA;
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITextDocument_Value = @import("../zig.zig").Guid.initString("8cc497c0-a1df-11ce-8098-00aa0047be5d");
pub const IID_ITextDocument = &IID_ITextDocument_Value;
pub const ITextDocument = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
GetName: fn(
self: *const ITextDocument,
pName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSelection: fn(
self: *const ITextDocument,
ppSel: ?*?*ITextSelection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoryCount: fn(
self: *const ITextDocument,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoryRanges: fn(
self: *const ITextDocument,
ppStories: ?*?*ITextStoryRanges,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSaved: fn(
self: *const ITextDocument,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSaved: fn(
self: *const ITextDocument,
Value: tomConstants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDefaultTabStop: fn(
self: *const ITextDocument,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDefaultTabStop: fn(
self: *const ITextDocument,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
New: fn(
self: *const ITextDocument,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Open: fn(
self: *const ITextDocument,
pVar: ?*VARIANT,
Flags: i32,
CodePage: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Save: fn(
self: *const ITextDocument,
pVar: ?*VARIANT,
Flags: i32,
CodePage: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Freeze: fn(
self: *const ITextDocument,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Unfreeze: fn(
self: *const ITextDocument,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BeginEditCollection: fn(
self: *const ITextDocument,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EndEditCollection: fn(
self: *const ITextDocument,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Undo: fn(
self: *const ITextDocument,
Count: i32,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Redo: fn(
self: *const ITextDocument,
Count: i32,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Range: fn(
self: *const ITextDocument,
cpActive: i32,
cpAnchor: i32,
ppRange: ?*?*ITextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RangeFromPoint: fn(
self: *const ITextDocument,
x: i32,
y: i32,
ppRange: ?*?*ITextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_GetName(self: *const T, pName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).GetName(@ptrCast(*const ITextDocument, self), pName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_GetSelection(self: *const T, ppSel: ?*?*ITextSelection) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).GetSelection(@ptrCast(*const ITextDocument, self), ppSel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_GetStoryCount(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).GetStoryCount(@ptrCast(*const ITextDocument, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_GetStoryRanges(self: *const T, ppStories: ?*?*ITextStoryRanges) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).GetStoryRanges(@ptrCast(*const ITextDocument, self), ppStories);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_GetSaved(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).GetSaved(@ptrCast(*const ITextDocument, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_SetSaved(self: *const T, Value: tomConstants) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).SetSaved(@ptrCast(*const ITextDocument, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_GetDefaultTabStop(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).GetDefaultTabStop(@ptrCast(*const ITextDocument, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_SetDefaultTabStop(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).SetDefaultTabStop(@ptrCast(*const ITextDocument, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_New(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).New(@ptrCast(*const ITextDocument, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_Open(self: *const T, pVar: ?*VARIANT, Flags: i32, CodePage: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).Open(@ptrCast(*const ITextDocument, self), pVar, Flags, CodePage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_Save(self: *const T, pVar: ?*VARIANT, Flags: i32, CodePage: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).Save(@ptrCast(*const ITextDocument, self), pVar, Flags, CodePage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_Freeze(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).Freeze(@ptrCast(*const ITextDocument, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_Unfreeze(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).Unfreeze(@ptrCast(*const ITextDocument, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_BeginEditCollection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).BeginEditCollection(@ptrCast(*const ITextDocument, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_EndEditCollection(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).EndEditCollection(@ptrCast(*const ITextDocument, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_Undo(self: *const T, Count: i32, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).Undo(@ptrCast(*const ITextDocument, self), Count, pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_Redo(self: *const T, Count: i32, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).Redo(@ptrCast(*const ITextDocument, self), Count, pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_Range(self: *const T, cpActive: i32, cpAnchor: i32, ppRange: ?*?*ITextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).Range(@ptrCast(*const ITextDocument, self), cpActive, cpAnchor, ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument_RangeFromPoint(self: *const T, x: i32, y: i32, ppRange: ?*?*ITextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument.VTable, self.vtable).RangeFromPoint(@ptrCast(*const ITextDocument, self), x, y, ppRange);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITextRange_Value = @import("../zig.zig").Guid.initString("8cc497c2-a1df-11ce-8098-00aa0047be5d");
pub const IID_ITextRange = &IID_ITextRange_Value;
pub const ITextRange = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
GetText: fn(
self: *const ITextRange,
pbstr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetText: fn(
self: *const ITextRange,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChar: fn(
self: *const ITextRange,
pChar: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetChar: fn(
self: *const ITextRange,
Char: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDuplicate: fn(
self: *const ITextRange,
ppRange: ?*?*ITextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFormattedText: fn(
self: *const ITextRange,
ppRange: ?*?*ITextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFormattedText: fn(
self: *const ITextRange,
pRange: ?*ITextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStart: fn(
self: *const ITextRange,
pcpFirst: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStart: fn(
self: *const ITextRange,
cpFirst: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEnd: fn(
self: *const ITextRange,
pcpLim: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEnd: fn(
self: *const ITextRange,
cpLim: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFont: fn(
self: *const ITextRange,
ppFont: ?*?*ITextFont,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFont: fn(
self: *const ITextRange,
pFont: ?*ITextFont,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPara: fn(
self: *const ITextRange,
ppPara: ?*?*ITextPara,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPara: fn(
self: *const ITextRange,
pPara: ?*ITextPara,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoryLength: fn(
self: *const ITextRange,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoryType: fn(
self: *const ITextRange,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Collapse: fn(
self: *const ITextRange,
bStart: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Expand: fn(
self: *const ITextRange,
Unit: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIndex: fn(
self: *const ITextRange,
Unit: i32,
pIndex: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIndex: fn(
self: *const ITextRange,
Unit: i32,
Index: i32,
Extend: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetRange: fn(
self: *const ITextRange,
cpAnchor: i32,
cpActive: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InRange: fn(
self: *const ITextRange,
pRange: ?*ITextRange,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InStory: fn(
self: *const ITextRange,
pRange: ?*ITextRange,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEqual: fn(
self: *const ITextRange,
pRange: ?*ITextRange,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Select: fn(
self: *const ITextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
StartOf: fn(
self: *const ITextRange,
Unit: i32,
Extend: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EndOf: fn(
self: *const ITextRange,
Unit: i32,
Extend: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Move: fn(
self: *const ITextRange,
Unit: i32,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveStart: fn(
self: *const ITextRange,
Unit: i32,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveEnd: fn(
self: *const ITextRange,
Unit: i32,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveWhile: fn(
self: *const ITextRange,
Cset: ?*VARIANT,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveStartWhile: fn(
self: *const ITextRange,
Cset: ?*VARIANT,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveEndWhile: fn(
self: *const ITextRange,
Cset: ?*VARIANT,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveUntil: fn(
self: *const ITextRange,
Cset: ?*VARIANT,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveStartUntil: fn(
self: *const ITextRange,
Cset: ?*VARIANT,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveEndUntil: fn(
self: *const ITextRange,
Cset: ?*VARIANT,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindText: fn(
self: *const ITextRange,
bstr: ?BSTR,
Count: i32,
Flags: i32,
pLength: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindTextStart: fn(
self: *const ITextRange,
bstr: ?BSTR,
Count: i32,
Flags: i32,
pLength: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FindTextEnd: fn(
self: *const ITextRange,
bstr: ?BSTR,
Count: i32,
Flags: i32,
pLength: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const ITextRange,
Unit: i32,
Count: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Cut: fn(
self: *const ITextRange,
pVar: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Copy: fn(
self: *const ITextRange,
pVar: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Paste: fn(
self: *const ITextRange,
pVar: ?*VARIANT,
Format: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CanPaste: fn(
self: *const ITextRange,
pVar: ?*VARIANT,
Format: i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CanEdit: fn(
self: *const ITextRange,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ChangeCase: fn(
self: *const ITextRange,
Type: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPoint: fn(
self: *const ITextRange,
Type: i32,
px: ?*i32,
py: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPoint: fn(
self: *const ITextRange,
x: i32,
y: i32,
Type: i32,
Extend: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ScrollIntoView: fn(
self: *const ITextRange,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEmbeddedObject: fn(
self: *const ITextRange,
ppObject: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetText(self: *const T, pbstr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetText(@ptrCast(*const ITextRange, self), pbstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetText(self: *const T, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetText(@ptrCast(*const ITextRange, self), bstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetChar(self: *const T, pChar: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetChar(@ptrCast(*const ITextRange, self), pChar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetChar(self: *const T, Char: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetChar(@ptrCast(*const ITextRange, self), Char);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetDuplicate(self: *const T, ppRange: ?*?*ITextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetDuplicate(@ptrCast(*const ITextRange, self), ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetFormattedText(self: *const T, ppRange: ?*?*ITextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetFormattedText(@ptrCast(*const ITextRange, self), ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetFormattedText(self: *const T, pRange: ?*ITextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetFormattedText(@ptrCast(*const ITextRange, self), pRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetStart(self: *const T, pcpFirst: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetStart(@ptrCast(*const ITextRange, self), pcpFirst);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetStart(self: *const T, cpFirst: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetStart(@ptrCast(*const ITextRange, self), cpFirst);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetEnd(self: *const T, pcpLim: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetEnd(@ptrCast(*const ITextRange, self), pcpLim);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetEnd(self: *const T, cpLim: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetEnd(@ptrCast(*const ITextRange, self), cpLim);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetFont(self: *const T, ppFont: ?*?*ITextFont) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetFont(@ptrCast(*const ITextRange, self), ppFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetFont(self: *const T, pFont: ?*ITextFont) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetFont(@ptrCast(*const ITextRange, self), pFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetPara(self: *const T, ppPara: ?*?*ITextPara) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetPara(@ptrCast(*const ITextRange, self), ppPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetPara(self: *const T, pPara: ?*ITextPara) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetPara(@ptrCast(*const ITextRange, self), pPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetStoryLength(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetStoryLength(@ptrCast(*const ITextRange, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetStoryType(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetStoryType(@ptrCast(*const ITextRange, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_Collapse(self: *const T, bStart: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).Collapse(@ptrCast(*const ITextRange, self), bStart);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_Expand(self: *const T, Unit: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).Expand(@ptrCast(*const ITextRange, self), Unit, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetIndex(self: *const T, Unit: i32, pIndex: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetIndex(@ptrCast(*const ITextRange, self), Unit, pIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetIndex(self: *const T, Unit: i32, Index: i32, Extend: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetIndex(@ptrCast(*const ITextRange, self), Unit, Index, Extend);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetRange(self: *const T, cpAnchor: i32, cpActive: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetRange(@ptrCast(*const ITextRange, self), cpAnchor, cpActive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_InRange(self: *const T, pRange: ?*ITextRange, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).InRange(@ptrCast(*const ITextRange, self), pRange, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_InStory(self: *const T, pRange: ?*ITextRange, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).InStory(@ptrCast(*const ITextRange, self), pRange, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_IsEqual(self: *const T, pRange: ?*ITextRange, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).IsEqual(@ptrCast(*const ITextRange, self), pRange, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_Select(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).Select(@ptrCast(*const ITextRange, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_StartOf(self: *const T, Unit: i32, Extend: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).StartOf(@ptrCast(*const ITextRange, self), Unit, Extend, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_EndOf(self: *const T, Unit: i32, Extend: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).EndOf(@ptrCast(*const ITextRange, self), Unit, Extend, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_Move(self: *const T, Unit: i32, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).Move(@ptrCast(*const ITextRange, self), Unit, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_MoveStart(self: *const T, Unit: i32, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).MoveStart(@ptrCast(*const ITextRange, self), Unit, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_MoveEnd(self: *const T, Unit: i32, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).MoveEnd(@ptrCast(*const ITextRange, self), Unit, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_MoveWhile(self: *const T, Cset: ?*VARIANT, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).MoveWhile(@ptrCast(*const ITextRange, self), Cset, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_MoveStartWhile(self: *const T, Cset: ?*VARIANT, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).MoveStartWhile(@ptrCast(*const ITextRange, self), Cset, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_MoveEndWhile(self: *const T, Cset: ?*VARIANT, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).MoveEndWhile(@ptrCast(*const ITextRange, self), Cset, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_MoveUntil(self: *const T, Cset: ?*VARIANT, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).MoveUntil(@ptrCast(*const ITextRange, self), Cset, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_MoveStartUntil(self: *const T, Cset: ?*VARIANT, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).MoveStartUntil(@ptrCast(*const ITextRange, self), Cset, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_MoveEndUntil(self: *const T, Cset: ?*VARIANT, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).MoveEndUntil(@ptrCast(*const ITextRange, self), Cset, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_FindText(self: *const T, bstr: ?BSTR, Count: i32, Flags: i32, pLength: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).FindText(@ptrCast(*const ITextRange, self), bstr, Count, Flags, pLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_FindTextStart(self: *const T, bstr: ?BSTR, Count: i32, Flags: i32, pLength: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).FindTextStart(@ptrCast(*const ITextRange, self), bstr, Count, Flags, pLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_FindTextEnd(self: *const T, bstr: ?BSTR, Count: i32, Flags: i32, pLength: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).FindTextEnd(@ptrCast(*const ITextRange, self), bstr, Count, Flags, pLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_Delete(self: *const T, Unit: i32, Count: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).Delete(@ptrCast(*const ITextRange, self), Unit, Count, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_Cut(self: *const T, pVar: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).Cut(@ptrCast(*const ITextRange, self), pVar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_Copy(self: *const T, pVar: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).Copy(@ptrCast(*const ITextRange, self), pVar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_Paste(self: *const T, pVar: ?*VARIANT, Format: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).Paste(@ptrCast(*const ITextRange, self), pVar, Format);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_CanPaste(self: *const T, pVar: ?*VARIANT, Format: i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).CanPaste(@ptrCast(*const ITextRange, self), pVar, Format, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_CanEdit(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).CanEdit(@ptrCast(*const ITextRange, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_ChangeCase(self: *const T, Type: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).ChangeCase(@ptrCast(*const ITextRange, self), Type);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetPoint(self: *const T, Type: i32, px: ?*i32, py: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetPoint(@ptrCast(*const ITextRange, self), Type, px, py);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_SetPoint(self: *const T, x: i32, y: i32, Type: i32, Extend: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).SetPoint(@ptrCast(*const ITextRange, self), x, y, Type, Extend);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_ScrollIntoView(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).ScrollIntoView(@ptrCast(*const ITextRange, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange_GetEmbeddedObject(self: *const T, ppObject: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange.VTable, self.vtable).GetEmbeddedObject(@ptrCast(*const ITextRange, self), ppObject);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITextSelection_Value = @import("../zig.zig").Guid.initString("8cc497c1-a1df-11ce-8098-00aa0047be5d");
pub const IID_ITextSelection = &IID_ITextSelection_Value;
pub const ITextSelection = extern struct {
pub const VTable = extern struct {
base: ITextRange.VTable,
GetFlags: fn(
self: *const ITextSelection,
pFlags: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFlags: fn(
self: *const ITextSelection,
Flags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetType: fn(
self: *const ITextSelection,
pType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveLeft: fn(
self: *const ITextSelection,
Unit: i32,
Count: i32,
Extend: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveRight: fn(
self: *const ITextSelection,
Unit: i32,
Count: i32,
Extend: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveUp: fn(
self: *const ITextSelection,
Unit: i32,
Count: i32,
Extend: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveDown: fn(
self: *const ITextSelection,
Unit: i32,
Count: i32,
Extend: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HomeKey: fn(
self: *const ITextSelection,
Unit: tomConstants,
Extend: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EndKey: fn(
self: *const ITextSelection,
Unit: i32,
Extend: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TypeText: fn(
self: *const ITextSelection,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextRange.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_GetFlags(self: *const T, pFlags: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).GetFlags(@ptrCast(*const ITextSelection, self), pFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_SetFlags(self: *const T, Flags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).SetFlags(@ptrCast(*const ITextSelection, self), Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_GetType(self: *const T, pType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).GetType(@ptrCast(*const ITextSelection, self), pType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_MoveLeft(self: *const T, Unit: i32, Count: i32, Extend: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).MoveLeft(@ptrCast(*const ITextSelection, self), Unit, Count, Extend, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_MoveRight(self: *const T, Unit: i32, Count: i32, Extend: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).MoveRight(@ptrCast(*const ITextSelection, self), Unit, Count, Extend, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_MoveUp(self: *const T, Unit: i32, Count: i32, Extend: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).MoveUp(@ptrCast(*const ITextSelection, self), Unit, Count, Extend, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_MoveDown(self: *const T, Unit: i32, Count: i32, Extend: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).MoveDown(@ptrCast(*const ITextSelection, self), Unit, Count, Extend, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_HomeKey(self: *const T, Unit: tomConstants, Extend: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).HomeKey(@ptrCast(*const ITextSelection, self), Unit, Extend, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_EndKey(self: *const T, Unit: i32, Extend: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).EndKey(@ptrCast(*const ITextSelection, self), Unit, Extend, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextSelection_TypeText(self: *const T, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextSelection.VTable, self.vtable).TypeText(@ptrCast(*const ITextSelection, self), bstr);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITextFont_Value = @import("../zig.zig").Guid.initString("8cc497c3-a1df-11ce-8098-00aa0047be5d");
pub const IID_ITextFont = &IID_ITextFont_Value;
pub const ITextFont = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
GetDuplicate: fn(
self: *const ITextFont,
ppFont: ?*?*ITextFont,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDuplicate: fn(
self: *const ITextFont,
pFont: ?*ITextFont,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CanChange: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEqual: fn(
self: *const ITextFont,
pFont: ?*ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const ITextFont,
Value: tomConstants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStyle: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStyle: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAllCaps: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAllCaps: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAnimation: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAnimation: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBackColor: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetBackColor: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetBold: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetBold: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEmboss: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEmboss: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetForeColor: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetForeColor: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetHidden: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHidden: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEngrave: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEngrave: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetItalic: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetItalic: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetKerning: fn(
self: *const ITextFont,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetKerning: fn(
self: *const ITextFont,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLanguageID: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLanguageID: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetName: fn(
self: *const ITextFont,
pbstr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetName: fn(
self: *const ITextFont,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOutline: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetOutline: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPosition: fn(
self: *const ITextFont,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPosition: fn(
self: *const ITextFont,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProtected: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProtected: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetShadow: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetShadow: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSize: fn(
self: *const ITextFont,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSize: fn(
self: *const ITextFont,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSmallCaps: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSmallCaps: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSpacing: fn(
self: *const ITextFont,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSpacing: fn(
self: *const ITextFont,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStrikeThrough: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStrikeThrough: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubscript: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSubscript: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSuperscript: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSuperscript: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetUnderline: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUnderline: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWeight: fn(
self: *const ITextFont,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetWeight: fn(
self: *const ITextFont,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetDuplicate(self: *const T, ppFont: ?*?*ITextFont) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetDuplicate(@ptrCast(*const ITextFont, self), ppFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetDuplicate(self: *const T, pFont: ?*ITextFont) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetDuplicate(@ptrCast(*const ITextFont, self), pFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_CanChange(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).CanChange(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_IsEqual(self: *const T, pFont: ?*ITextFont, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).IsEqual(@ptrCast(*const ITextFont, self), pFont, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_Reset(self: *const T, Value: tomConstants) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).Reset(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetStyle(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetStyle(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetStyle(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetStyle(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetAllCaps(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetAllCaps(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetAllCaps(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetAllCaps(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetAnimation(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetAnimation(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetAnimation(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetAnimation(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetBackColor(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetBackColor(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetBackColor(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetBackColor(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetBold(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetBold(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetBold(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetBold(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetEmboss(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetEmboss(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetEmboss(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetEmboss(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetForeColor(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetForeColor(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetForeColor(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetForeColor(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetHidden(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetHidden(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetHidden(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetHidden(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetEngrave(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetEngrave(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetEngrave(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetEngrave(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetItalic(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetItalic(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetItalic(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetItalic(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetKerning(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetKerning(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetKerning(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetKerning(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetLanguageID(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetLanguageID(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetLanguageID(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetLanguageID(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetName(self: *const T, pbstr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetName(@ptrCast(*const ITextFont, self), pbstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetName(self: *const T, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetName(@ptrCast(*const ITextFont, self), bstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetOutline(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetOutline(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetOutline(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetOutline(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetPosition(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetPosition(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetPosition(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetPosition(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetProtected(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetProtected(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetProtected(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetProtected(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetShadow(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetShadow(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetShadow(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetShadow(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetSize(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetSize(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetSize(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetSize(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetSmallCaps(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetSmallCaps(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetSmallCaps(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetSmallCaps(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetSpacing(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetSpacing(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetSpacing(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetSpacing(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetStrikeThrough(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetStrikeThrough(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetStrikeThrough(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetStrikeThrough(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetSubscript(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetSubscript(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetSubscript(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetSubscript(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetSuperscript(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetSuperscript(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetSuperscript(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetSuperscript(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetUnderline(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetUnderline(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetUnderline(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetUnderline(@ptrCast(*const ITextFont, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_GetWeight(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).GetWeight(@ptrCast(*const ITextFont, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont_SetWeight(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont.VTable, self.vtable).SetWeight(@ptrCast(*const ITextFont, self), Value);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITextPara_Value = @import("../zig.zig").Guid.initString("8cc497c4-a1df-11ce-8098-00aa0047be5d");
pub const IID_ITextPara = &IID_ITextPara_Value;
pub const ITextPara = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
GetDuplicate: fn(
self: *const ITextPara,
ppPara: ?*?*ITextPara,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDuplicate: fn(
self: *const ITextPara,
pPara: ?*ITextPara,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CanChange: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEqual: fn(
self: *const ITextPara,
pPara: ?*ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStyle: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetStyle: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAlignment: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAlignment: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetHyphenation: fn(
self: *const ITextPara,
pValue: ?*tomConstants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHyphenation: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFirstLineIndent: fn(
self: *const ITextPara,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetKeepTogether: fn(
self: *const ITextPara,
pValue: ?*tomConstants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetKeepTogether: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetKeepWithNext: fn(
self: *const ITextPara,
pValue: ?*tomConstants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetKeepWithNext: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLeftIndent: fn(
self: *const ITextPara,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLineSpacing: fn(
self: *const ITextPara,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLineSpacingRule: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetListAlignment: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetListAlignment: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetListLevelIndex: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetListLevelIndex: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetListStart: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetListStart: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetListTab: fn(
self: *const ITextPara,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetListTab: fn(
self: *const ITextPara,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetListType: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetListType: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNoLineNumber: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNoLineNumber: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPageBreakBefore: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPageBreakBefore: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRightIndent: fn(
self: *const ITextPara,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetRightIndent: fn(
self: *const ITextPara,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIndents: fn(
self: *const ITextPara,
First: f32,
Left: f32,
Right: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLineSpacing: fn(
self: *const ITextPara,
Rule: i32,
Spacing: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSpaceAfter: fn(
self: *const ITextPara,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSpaceAfter: fn(
self: *const ITextPara,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSpaceBefore: fn(
self: *const ITextPara,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSpaceBefore: fn(
self: *const ITextPara,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWidowControl: fn(
self: *const ITextPara,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetWidowControl: fn(
self: *const ITextPara,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTabCount: fn(
self: *const ITextPara,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddTab: fn(
self: *const ITextPara,
tbPos: f32,
tbAlign: i32,
tbLeader: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearAllTabs: fn(
self: *const ITextPara,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteTab: fn(
self: *const ITextPara,
tbPos: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTab: fn(
self: *const ITextPara,
iTab: i32,
ptbPos: ?*f32,
ptbAlign: ?*i32,
ptbLeader: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetDuplicate(self: *const T, ppPara: ?*?*ITextPara) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetDuplicate(@ptrCast(*const ITextPara, self), ppPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetDuplicate(self: *const T, pPara: ?*ITextPara) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetDuplicate(@ptrCast(*const ITextPara, self), pPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_CanChange(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).CanChange(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_IsEqual(self: *const T, pPara: ?*ITextPara, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).IsEqual(@ptrCast(*const ITextPara, self), pPara, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_Reset(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).Reset(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetStyle(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetStyle(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetStyle(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetStyle(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetAlignment(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetAlignment(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetAlignment(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetAlignment(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetHyphenation(self: *const T, pValue: ?*tomConstants) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetHyphenation(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetHyphenation(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetHyphenation(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetFirstLineIndent(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetFirstLineIndent(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetKeepTogether(self: *const T, pValue: ?*tomConstants) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetKeepTogether(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetKeepTogether(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetKeepTogether(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetKeepWithNext(self: *const T, pValue: ?*tomConstants) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetKeepWithNext(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetKeepWithNext(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetKeepWithNext(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetLeftIndent(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetLeftIndent(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetLineSpacing(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetLineSpacing(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetLineSpacingRule(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetLineSpacingRule(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetListAlignment(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetListAlignment(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetListAlignment(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetListAlignment(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetListLevelIndex(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetListLevelIndex(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetListLevelIndex(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetListLevelIndex(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetListStart(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetListStart(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetListStart(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetListStart(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetListTab(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetListTab(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetListTab(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetListTab(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetListType(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetListType(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetListType(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetListType(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetNoLineNumber(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetNoLineNumber(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetNoLineNumber(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetNoLineNumber(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetPageBreakBefore(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetPageBreakBefore(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetPageBreakBefore(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetPageBreakBefore(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetRightIndent(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetRightIndent(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetRightIndent(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetRightIndent(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetIndents(self: *const T, First: f32, Left: f32, Right: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetIndents(@ptrCast(*const ITextPara, self), First, Left, Right);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetLineSpacing(self: *const T, Rule: i32, Spacing: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetLineSpacing(@ptrCast(*const ITextPara, self), Rule, Spacing);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetSpaceAfter(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetSpaceAfter(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetSpaceAfter(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetSpaceAfter(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetSpaceBefore(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetSpaceBefore(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetSpaceBefore(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetSpaceBefore(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetWidowControl(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetWidowControl(@ptrCast(*const ITextPara, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_SetWidowControl(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).SetWidowControl(@ptrCast(*const ITextPara, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetTabCount(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetTabCount(@ptrCast(*const ITextPara, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_AddTab(self: *const T, tbPos: f32, tbAlign: i32, tbLeader: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).AddTab(@ptrCast(*const ITextPara, self), tbPos, tbAlign, tbLeader);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_ClearAllTabs(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).ClearAllTabs(@ptrCast(*const ITextPara, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_DeleteTab(self: *const T, tbPos: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).DeleteTab(@ptrCast(*const ITextPara, self), tbPos);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara_GetTab(self: *const T, iTab: i32, ptbPos: ?*f32, ptbAlign: ?*i32, ptbLeader: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara.VTable, self.vtable).GetTab(@ptrCast(*const ITextPara, self), iTab, ptbPos, ptbAlign, ptbLeader);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ITextStoryRanges_Value = @import("../zig.zig").Guid.initString("8cc497c5-a1df-11ce-8098-00aa0047be5d");
pub const IID_ITextStoryRanges = &IID_ITextStoryRanges_Value;
pub const ITextStoryRanges = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
_NewEnum: fn(
self: *const ITextStoryRanges,
ppunkEnum: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Item: fn(
self: *const ITextStoryRanges,
Index: i32,
ppRange: ?*?*ITextRange,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const ITextStoryRanges,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStoryRanges__NewEnum(self: *const T, ppunkEnum: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStoryRanges.VTable, self.vtable)._NewEnum(@ptrCast(*const ITextStoryRanges, self), ppunkEnum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStoryRanges_Item(self: *const T, Index: i32, ppRange: ?*?*ITextRange) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStoryRanges.VTable, self.vtable).Item(@ptrCast(*const ITextStoryRanges, self), Index, ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStoryRanges_GetCount(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStoryRanges.VTable, self.vtable).GetCount(@ptrCast(*const ITextStoryRanges, self), pCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextDocument2_Value = @import("../zig.zig").Guid.initString("c241f5e0-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextDocument2 = &IID_ITextDocument2_Value;
pub const ITextDocument2 = extern struct {
pub const VTable = extern struct {
base: ITextDocument.VTable,
GetCaretType: fn(
self: *const ITextDocument2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCaretType: fn(
self: *const ITextDocument2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDisplays: fn(
self: *const ITextDocument2,
ppDisplays: ?*?*ITextDisplays,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDocumentFont: fn(
self: *const ITextDocument2,
ppFont: ?*?*ITextFont2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDocumentFont: fn(
self: *const ITextDocument2,
pFont: ?*ITextFont2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDocumentPara: fn(
self: *const ITextDocument2,
ppPara: ?*?*ITextPara2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDocumentPara: fn(
self: *const ITextDocument2,
pPara: ?*ITextPara2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEastAsianFlags: fn(
self: *const ITextDocument2,
pFlags: ?*tomConstants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGenerator: fn(
self: *const ITextDocument2,
pbstr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIMEInProgress: fn(
self: *const ITextDocument2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNotificationMode: fn(
self: *const ITextDocument2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNotificationMode: fn(
self: *const ITextDocument2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSelection2: fn(
self: *const ITextDocument2,
ppSel: ?*?*ITextSelection2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStoryRanges2: fn(
self: *const ITextDocument2,
ppStories: ?*?*ITextStoryRanges2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTypographyOptions: fn(
self: *const ITextDocument2,
pOptions: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetVersion: fn(
self: *const ITextDocument2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWindow: fn(
self: *const ITextDocument2,
pHwnd: ?*i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AttachMsgFilter: fn(
self: *const ITextDocument2,
pFilter: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckTextLimit: fn(
self: *const ITextDocument2,
cch: i32,
pcch: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCallManager: fn(
self: *const ITextDocument2,
ppVoid: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetClientRect: fn(
self: *const ITextDocument2,
Type: tomConstants,
pLeft: ?*i32,
pTop: ?*i32,
pRight: ?*i32,
pBottom: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEffectColor: fn(
self: *const ITextDocument2,
Index: i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetImmContext: fn(
self: *const ITextDocument2,
pContext: ?*i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreferredFont: fn(
self: *const ITextDocument2,
cp: i32,
CharRep: i32,
Options: i32,
curCharRep: i32,
curFontSize: i32,
pbstr: ?*?BSTR,
pPitchAndFamily: ?*i32,
pNewFontSize: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const ITextDocument2,
Type: i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStrings: fn(
self: *const ITextDocument2,
ppStrs: ?*?*ITextStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Notify: fn(
self: *const ITextDocument2,
Notify: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Range2: fn(
self: *const ITextDocument2,
cpActive: i32,
cpAnchor: i32,
ppRange: ?*?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RangeFromPoint2: fn(
self: *const ITextDocument2,
x: i32,
y: i32,
Type: i32,
ppRange: ?*?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseCallManager: fn(
self: *const ITextDocument2,
pVoid: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseImmContext: fn(
self: *const ITextDocument2,
Context: i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEffectColor: fn(
self: *const ITextDocument2,
Index: i32,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const ITextDocument2,
Type: i32,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTypographyOptions: fn(
self: *const ITextDocument2,
Options: i32,
Mask: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SysBeep: fn(
self: *const ITextDocument2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Update: fn(
self: *const ITextDocument2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UpdateWindow: fn(
self: *const ITextDocument2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMathProperties: fn(
self: *const ITextDocument2,
pOptions: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMathProperties: fn(
self: *const ITextDocument2,
Options: i32,
Mask: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetActiveStory: fn(
self: *const ITextDocument2,
ppStory: ?*?*ITextStory,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetActiveStory: fn(
self: *const ITextDocument2,
pStory: ?*ITextStory,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMainStory: fn(
self: *const ITextDocument2,
ppStory: ?*?*ITextStory,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNewStory: fn(
self: *const ITextDocument2,
ppStory: ?*?*ITextStory,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStory: fn(
self: *const ITextDocument2,
Index: i32,
ppStory: ?*?*ITextStory,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextDocument.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetCaretType(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetCaretType(@ptrCast(*const ITextDocument2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetCaretType(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetCaretType(@ptrCast(*const ITextDocument2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetDisplays(self: *const T, ppDisplays: ?*?*ITextDisplays) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetDisplays(@ptrCast(*const ITextDocument2, self), ppDisplays);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetDocumentFont(self: *const T, ppFont: ?*?*ITextFont2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetDocumentFont(@ptrCast(*const ITextDocument2, self), ppFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetDocumentFont(self: *const T, pFont: ?*ITextFont2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetDocumentFont(@ptrCast(*const ITextDocument2, self), pFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetDocumentPara(self: *const T, ppPara: ?*?*ITextPara2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetDocumentPara(@ptrCast(*const ITextDocument2, self), ppPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetDocumentPara(self: *const T, pPara: ?*ITextPara2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetDocumentPara(@ptrCast(*const ITextDocument2, self), pPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetEastAsianFlags(self: *const T, pFlags: ?*tomConstants) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetEastAsianFlags(@ptrCast(*const ITextDocument2, self), pFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetGenerator(self: *const T, pbstr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetGenerator(@ptrCast(*const ITextDocument2, self), pbstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetIMEInProgress(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetIMEInProgress(@ptrCast(*const ITextDocument2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetNotificationMode(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetNotificationMode(@ptrCast(*const ITextDocument2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetNotificationMode(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetNotificationMode(@ptrCast(*const ITextDocument2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetSelection2(self: *const T, ppSel: ?*?*ITextSelection2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetSelection2(@ptrCast(*const ITextDocument2, self), ppSel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetStoryRanges2(self: *const T, ppStories: ?*?*ITextStoryRanges2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetStoryRanges2(@ptrCast(*const ITextDocument2, self), ppStories);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetTypographyOptions(self: *const T, pOptions: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetTypographyOptions(@ptrCast(*const ITextDocument2, self), pOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetVersion(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetVersion(@ptrCast(*const ITextDocument2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetWindow(self: *const T, pHwnd: ?*i64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetWindow(@ptrCast(*const ITextDocument2, self), pHwnd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_AttachMsgFilter(self: *const T, pFilter: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).AttachMsgFilter(@ptrCast(*const ITextDocument2, self), pFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_CheckTextLimit(self: *const T, cch: i32, pcch: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).CheckTextLimit(@ptrCast(*const ITextDocument2, self), cch, pcch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetCallManager(self: *const T, ppVoid: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetCallManager(@ptrCast(*const ITextDocument2, self), ppVoid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetClientRect(self: *const T, Type: tomConstants, pLeft: ?*i32, pTop: ?*i32, pRight: ?*i32, pBottom: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetClientRect(@ptrCast(*const ITextDocument2, self), Type, pLeft, pTop, pRight, pBottom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetEffectColor(self: *const T, Index: i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetEffectColor(@ptrCast(*const ITextDocument2, self), Index, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetImmContext(self: *const T, pContext: ?*i64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetImmContext(@ptrCast(*const ITextDocument2, self), pContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetPreferredFont(self: *const T, cp: i32, CharRep: i32, Options: i32, curCharRep: i32, curFontSize: i32, pbstr: ?*?BSTR, pPitchAndFamily: ?*i32, pNewFontSize: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetPreferredFont(@ptrCast(*const ITextDocument2, self), cp, CharRep, Options, curCharRep, curFontSize, pbstr, pPitchAndFamily, pNewFontSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetProperty(self: *const T, Type: i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetProperty(@ptrCast(*const ITextDocument2, self), Type, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetStrings(self: *const T, ppStrs: ?*?*ITextStrings) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetStrings(@ptrCast(*const ITextDocument2, self), ppStrs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_Notify(self: *const T, Notify: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).Notify(@ptrCast(*const ITextDocument2, self), Notify);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_Range2(self: *const T, cpActive: i32, cpAnchor: i32, ppRange: ?*?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).Range2(@ptrCast(*const ITextDocument2, self), cpActive, cpAnchor, ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_RangeFromPoint2(self: *const T, x: i32, y: i32, Type: i32, ppRange: ?*?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).RangeFromPoint2(@ptrCast(*const ITextDocument2, self), x, y, Type, ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_ReleaseCallManager(self: *const T, pVoid: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).ReleaseCallManager(@ptrCast(*const ITextDocument2, self), pVoid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_ReleaseImmContext(self: *const T, Context: i64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).ReleaseImmContext(@ptrCast(*const ITextDocument2, self), Context);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetEffectColor(self: *const T, Index: i32, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetEffectColor(@ptrCast(*const ITextDocument2, self), Index, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetProperty(self: *const T, Type: i32, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetProperty(@ptrCast(*const ITextDocument2, self), Type, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetTypographyOptions(self: *const T, Options: i32, Mask: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetTypographyOptions(@ptrCast(*const ITextDocument2, self), Options, Mask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SysBeep(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SysBeep(@ptrCast(*const ITextDocument2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_Update(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).Update(@ptrCast(*const ITextDocument2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_UpdateWindow(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).UpdateWindow(@ptrCast(*const ITextDocument2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetMathProperties(self: *const T, pOptions: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetMathProperties(@ptrCast(*const ITextDocument2, self), pOptions);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetMathProperties(self: *const T, Options: i32, Mask: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetMathProperties(@ptrCast(*const ITextDocument2, self), Options, Mask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetActiveStory(self: *const T, ppStory: ?*?*ITextStory) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetActiveStory(@ptrCast(*const ITextDocument2, self), ppStory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_SetActiveStory(self: *const T, pStory: ?*ITextStory) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).SetActiveStory(@ptrCast(*const ITextDocument2, self), pStory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetMainStory(self: *const T, ppStory: ?*?*ITextStory) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetMainStory(@ptrCast(*const ITextDocument2, self), ppStory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetNewStory(self: *const T, ppStory: ?*?*ITextStory) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetNewStory(@ptrCast(*const ITextDocument2, self), ppStory);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2_GetStory(self: *const T, Index: i32, ppStory: ?*?*ITextStory) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2.VTable, self.vtable).GetStory(@ptrCast(*const ITextDocument2, self), Index, ppStory);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextRange2_Value = @import("../zig.zig").Guid.initString("c241f5e2-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextRange2 = &IID_ITextRange2_Value;
pub const ITextRange2 = extern struct {
pub const VTable = extern struct {
base: ITextSelection.VTable,
GetCch: fn(
self: *const ITextRange2,
pcch: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCells: fn(
self: *const ITextRange2,
ppCells: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetColumn: fn(
self: *const ITextRange2,
ppColumn: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const ITextRange2,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDuplicate2: fn(
self: *const ITextRange2,
ppRange: ?*?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFont2: fn(
self: *const ITextRange2,
ppFont: ?*?*ITextFont2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFont2: fn(
self: *const ITextRange2,
pFont: ?*ITextFont2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFormattedText2: fn(
self: *const ITextRange2,
ppRange: ?*?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFormattedText2: fn(
self: *const ITextRange2,
pRange: ?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGravity: fn(
self: *const ITextRange2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetGravity: fn(
self: *const ITextRange2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPara2: fn(
self: *const ITextRange2,
ppPara: ?*?*ITextPara2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPara2: fn(
self: *const ITextRange2,
pPara: ?*ITextPara2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRow: fn(
self: *const ITextRange2,
ppRow: ?*?*ITextRow,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStartPara: fn(
self: *const ITextRange2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTable: fn(
self: *const ITextRange2,
ppTable: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetURL: fn(
self: *const ITextRange2,
pbstr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetURL: fn(
self: *const ITextRange2,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddSubrange: fn(
self: *const ITextRange2,
cp1: i32,
cp2: i32,
Activate: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BuildUpMath: fn(
self: *const ITextRange2,
Flags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteSubrange: fn(
self: *const ITextRange2,
cpFirst: i32,
cpLim: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Find: fn(
self: *const ITextRange2,
pRange: ?*ITextRange2,
Count: i32,
Flags: i32,
pDelta: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetChar2: fn(
self: *const ITextRange2,
pChar: ?*i32,
Offset: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDropCap: fn(
self: *const ITextRange2,
pcLine: ?*i32,
pPosition: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInlineObject: fn(
self: *const ITextRange2,
pType: ?*i32,
pAlign: ?*i32,
pChar: ?*i32,
pChar1: ?*i32,
pChar2: ?*i32,
pCount: ?*i32,
pTeXStyle: ?*i32,
pcCol: ?*i32,
pLevel: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const ITextRange2,
Type: i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRect: fn(
self: *const ITextRange2,
Type: i32,
pLeft: ?*i32,
pTop: ?*i32,
pRight: ?*i32,
pBottom: ?*i32,
pHit: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubrange: fn(
self: *const ITextRange2,
iSubrange: i32,
pcpFirst: ?*i32,
pcpLim: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetText2: fn(
self: *const ITextRange2,
Flags: i32,
pbstr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HexToUnicode: fn(
self: *const ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InsertTable: fn(
self: *const ITextRange2,
cCol: i32,
cRow: i32,
AutoFit: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Linearize: fn(
self: *const ITextRange2,
Flags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetActiveSubrange: fn(
self: *const ITextRange2,
cpAnchor: i32,
cpActive: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDropCap: fn(
self: *const ITextRange2,
cLine: i32,
Position: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const ITextRange2,
Type: i32,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetText2: fn(
self: *const ITextRange2,
Flags: i32,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnicodeToHex: fn(
self: *const ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInlineObject: fn(
self: *const ITextRange2,
Type: i32,
Align: i32,
Char: i32,
Char1: i32,
Char2: i32,
Count: i32,
TeXStyle: i32,
cCol: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMathFunctionType: fn(
self: *const ITextRange2,
bstr: ?BSTR,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InsertImage: fn(
self: *const ITextRange2,
width: i32,
height: i32,
ascent: i32,
Type: TEXT_ALIGN_OPTIONS,
bstrAltText: ?BSTR,
pStream: ?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextSelection.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetCch(self: *const T, pcch: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetCch(@ptrCast(*const ITextRange2, self), pcch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetCells(self: *const T, ppCells: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetCells(@ptrCast(*const ITextRange2, self), ppCells);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetColumn(self: *const T, ppColumn: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetColumn(@ptrCast(*const ITextRange2, self), ppColumn);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetCount(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetCount(@ptrCast(*const ITextRange2, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetDuplicate2(self: *const T, ppRange: ?*?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetDuplicate2(@ptrCast(*const ITextRange2, self), ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetFont2(self: *const T, ppFont: ?*?*ITextFont2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetFont2(@ptrCast(*const ITextRange2, self), ppFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetFont2(self: *const T, pFont: ?*ITextFont2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetFont2(@ptrCast(*const ITextRange2, self), pFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetFormattedText2(self: *const T, ppRange: ?*?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetFormattedText2(@ptrCast(*const ITextRange2, self), ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetFormattedText2(self: *const T, pRange: ?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetFormattedText2(@ptrCast(*const ITextRange2, self), pRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetGravity(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetGravity(@ptrCast(*const ITextRange2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetGravity(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetGravity(@ptrCast(*const ITextRange2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetPara2(self: *const T, ppPara: ?*?*ITextPara2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetPara2(@ptrCast(*const ITextRange2, self), ppPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetPara2(self: *const T, pPara: ?*ITextPara2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetPara2(@ptrCast(*const ITextRange2, self), pPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetRow(self: *const T, ppRow: ?*?*ITextRow) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetRow(@ptrCast(*const ITextRange2, self), ppRow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetStartPara(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetStartPara(@ptrCast(*const ITextRange2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetTable(self: *const T, ppTable: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetTable(@ptrCast(*const ITextRange2, self), ppTable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetURL(self: *const T, pbstr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetURL(@ptrCast(*const ITextRange2, self), pbstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetURL(self: *const T, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetURL(@ptrCast(*const ITextRange2, self), bstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_AddSubrange(self: *const T, cp1: i32, cp2: i32, Activate: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).AddSubrange(@ptrCast(*const ITextRange2, self), cp1, cp2, Activate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_BuildUpMath(self: *const T, Flags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).BuildUpMath(@ptrCast(*const ITextRange2, self), Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_DeleteSubrange(self: *const T, cpFirst: i32, cpLim: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).DeleteSubrange(@ptrCast(*const ITextRange2, self), cpFirst, cpLim);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_Find(self: *const T, pRange: ?*ITextRange2, Count: i32, Flags: i32, pDelta: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).Find(@ptrCast(*const ITextRange2, self), pRange, Count, Flags, pDelta);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetChar2(self: *const T, pChar: ?*i32, Offset: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetChar2(@ptrCast(*const ITextRange2, self), pChar, Offset);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetDropCap(self: *const T, pcLine: ?*i32, pPosition: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetDropCap(@ptrCast(*const ITextRange2, self), pcLine, pPosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetInlineObject(self: *const T, pType: ?*i32, pAlign: ?*i32, pChar: ?*i32, pChar1: ?*i32, pChar2: ?*i32, pCount: ?*i32, pTeXStyle: ?*i32, pcCol: ?*i32, pLevel: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetInlineObject(@ptrCast(*const ITextRange2, self), pType, pAlign, pChar, pChar1, pChar2, pCount, pTeXStyle, pcCol, pLevel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetProperty(self: *const T, Type: i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetProperty(@ptrCast(*const ITextRange2, self), Type, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetRect(self: *const T, Type: i32, pLeft: ?*i32, pTop: ?*i32, pRight: ?*i32, pBottom: ?*i32, pHit: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetRect(@ptrCast(*const ITextRange2, self), Type, pLeft, pTop, pRight, pBottom, pHit);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetSubrange(self: *const T, iSubrange: i32, pcpFirst: ?*i32, pcpLim: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetSubrange(@ptrCast(*const ITextRange2, self), iSubrange, pcpFirst, pcpLim);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetText2(self: *const T, Flags: i32, pbstr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetText2(@ptrCast(*const ITextRange2, self), Flags, pbstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_HexToUnicode(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).HexToUnicode(@ptrCast(*const ITextRange2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_InsertTable(self: *const T, cCol: i32, cRow: i32, AutoFit: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).InsertTable(@ptrCast(*const ITextRange2, self), cCol, cRow, AutoFit);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_Linearize(self: *const T, Flags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).Linearize(@ptrCast(*const ITextRange2, self), Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetActiveSubrange(self: *const T, cpAnchor: i32, cpActive: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetActiveSubrange(@ptrCast(*const ITextRange2, self), cpAnchor, cpActive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetDropCap(self: *const T, cLine: i32, Position: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetDropCap(@ptrCast(*const ITextRange2, self), cLine, Position);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetProperty(self: *const T, Type: i32, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetProperty(@ptrCast(*const ITextRange2, self), Type, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetText2(self: *const T, Flags: i32, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetText2(@ptrCast(*const ITextRange2, self), Flags, bstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_UnicodeToHex(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).UnicodeToHex(@ptrCast(*const ITextRange2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_SetInlineObject(self: *const T, Type: i32, Align: i32, Char: i32, Char1: i32, Char2: i32, Count: i32, TeXStyle: i32, cCol: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).SetInlineObject(@ptrCast(*const ITextRange2, self), Type, Align, Char, Char1, Char2, Count, TeXStyle, cCol);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_GetMathFunctionType(self: *const T, bstr: ?BSTR, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).GetMathFunctionType(@ptrCast(*const ITextRange2, self), bstr, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRange2_InsertImage(self: *const T, width: i32, height: i32, ascent: i32, Type: TEXT_ALIGN_OPTIONS, bstrAltText: ?BSTR, pStream: ?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRange2.VTable, self.vtable).InsertImage(@ptrCast(*const ITextRange2, self), width, height, ascent, Type, bstrAltText, pStream);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextSelection2_Value = @import("../zig.zig").Guid.initString("c241f5e1-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextSelection2 = &IID_ITextSelection2_Value;
pub const ITextSelection2 = extern struct {
pub const VTable = extern struct {
base: ITextRange2.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextRange2.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextFont2_Value = @import("../zig.zig").Guid.initString("c241f5e3-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextFont2 = &IID_ITextFont2_Value;
pub const ITextFont2 = extern struct {
pub const VTable = extern struct {
base: ITextFont.VTable,
GetCount: fn(
self: *const ITextFont2,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAutoLigatures: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAutoLigatures: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAutospaceAlpha: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAutospaceAlpha: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAutospaceNumeric: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAutospaceNumeric: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAutospaceParens: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAutospaceParens: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCharRep: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCharRep: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCompressionMode: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCompressionMode: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCookie: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCookie: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDoubleStrike: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDoubleStrike: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDuplicate2: fn(
self: *const ITextFont2,
ppFont: ?*?*ITextFont2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDuplicate2: fn(
self: *const ITextFont2,
pFont: ?*ITextFont2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetLinkType: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetMathZone: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMathZone: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetModWidthPairs: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetModWidthPairs: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetModWidthSpace: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetModWidthSpace: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOldNumbers: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetOldNumbers: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOverlapping: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetOverlapping: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPositionSubSuper: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetPositionSubSuper: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetScaling: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetScaling: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSpaceExtension: fn(
self: *const ITextFont2,
pValue: ?*f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSpaceExtension: fn(
self: *const ITextFont2,
Value: f32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetUnderlinePositionMode: fn(
self: *const ITextFont2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUnderlinePositionMode: fn(
self: *const ITextFont2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEffects: fn(
self: *const ITextFont2,
pValue: ?*i32,
pMask: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEffects2: fn(
self: *const ITextFont2,
pValue: ?*i32,
pMask: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const ITextFont2,
Type: i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPropertyInfo: fn(
self: *const ITextFont2,
Index: i32,
pType: ?*i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEqual2: fn(
self: *const ITextFont2,
pFont: ?*ITextFont2,
pB: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEffects: fn(
self: *const ITextFont2,
Value: i32,
Mask: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEffects2: fn(
self: *const ITextFont2,
Value: i32,
Mask: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const ITextFont2,
Type: i32,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextFont.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetCount(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetCount(@ptrCast(*const ITextFont2, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetAutoLigatures(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetAutoLigatures(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetAutoLigatures(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetAutoLigatures(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetAutospaceAlpha(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetAutospaceAlpha(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetAutospaceAlpha(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetAutospaceAlpha(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetAutospaceNumeric(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetAutospaceNumeric(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetAutospaceNumeric(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetAutospaceNumeric(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetAutospaceParens(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetAutospaceParens(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetAutospaceParens(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetAutospaceParens(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetCharRep(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetCharRep(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetCharRep(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetCharRep(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetCompressionMode(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetCompressionMode(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetCompressionMode(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetCompressionMode(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetCookie(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetCookie(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetCookie(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetCookie(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetDoubleStrike(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetDoubleStrike(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetDoubleStrike(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetDoubleStrike(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetDuplicate2(self: *const T, ppFont: ?*?*ITextFont2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetDuplicate2(@ptrCast(*const ITextFont2, self), ppFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetDuplicate2(self: *const T, pFont: ?*ITextFont2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetDuplicate2(@ptrCast(*const ITextFont2, self), pFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetLinkType(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetLinkType(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetMathZone(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetMathZone(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetMathZone(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetMathZone(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetModWidthPairs(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetModWidthPairs(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetModWidthPairs(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetModWidthPairs(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetModWidthSpace(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetModWidthSpace(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetModWidthSpace(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetModWidthSpace(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetOldNumbers(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetOldNumbers(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetOldNumbers(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetOldNumbers(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetOverlapping(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetOverlapping(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetOverlapping(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetOverlapping(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetPositionSubSuper(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetPositionSubSuper(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetPositionSubSuper(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetPositionSubSuper(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetScaling(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetScaling(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetScaling(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetScaling(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetSpaceExtension(self: *const T, pValue: ?*f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetSpaceExtension(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetSpaceExtension(self: *const T, Value: f32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetSpaceExtension(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetUnderlinePositionMode(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetUnderlinePositionMode(@ptrCast(*const ITextFont2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetUnderlinePositionMode(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetUnderlinePositionMode(@ptrCast(*const ITextFont2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetEffects(self: *const T, pValue: ?*i32, pMask: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetEffects(@ptrCast(*const ITextFont2, self), pValue, pMask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetEffects2(self: *const T, pValue: ?*i32, pMask: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetEffects2(@ptrCast(*const ITextFont2, self), pValue, pMask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetProperty(self: *const T, Type: i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetProperty(@ptrCast(*const ITextFont2, self), Type, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_GetPropertyInfo(self: *const T, Index: i32, pType: ?*i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).GetPropertyInfo(@ptrCast(*const ITextFont2, self), Index, pType, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_IsEqual2(self: *const T, pFont: ?*ITextFont2, pB: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).IsEqual2(@ptrCast(*const ITextFont2, self), pFont, pB);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetEffects(self: *const T, Value: i32, Mask: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetEffects(@ptrCast(*const ITextFont2, self), Value, Mask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetEffects2(self: *const T, Value: i32, Mask: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetEffects2(@ptrCast(*const ITextFont2, self), Value, Mask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextFont2_SetProperty(self: *const T, Type: i32, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextFont2.VTable, self.vtable).SetProperty(@ptrCast(*const ITextFont2, self), Type, Value);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextPara2_Value = @import("../zig.zig").Guid.initString("c241f5e4-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextPara2 = &IID_ITextPara2_Value;
pub const ITextPara2 = extern struct {
pub const VTable = extern struct {
base: ITextPara.VTable,
GetBorders: fn(
self: *const ITextPara2,
ppBorders: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDuplicate2: fn(
self: *const ITextPara2,
ppPara: ?*?*ITextPara2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDuplicate2: fn(
self: *const ITextPara2,
pPara: ?*ITextPara2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFontAlignment: fn(
self: *const ITextPara2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFontAlignment: fn(
self: *const ITextPara2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetHangingPunctuation: fn(
self: *const ITextPara2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHangingPunctuation: fn(
self: *const ITextPara2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSnapToGrid: fn(
self: *const ITextPara2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSnapToGrid: fn(
self: *const ITextPara2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTrimPunctuationAtStart: fn(
self: *const ITextPara2,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetTrimPunctuationAtStart: fn(
self: *const ITextPara2,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEffects: fn(
self: *const ITextPara2,
pValue: ?*i32,
pMask: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const ITextPara2,
Type: i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEqual2: fn(
self: *const ITextPara2,
pPara: ?*ITextPara2,
pB: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEffects: fn(
self: *const ITextPara2,
Value: i32,
Mask: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const ITextPara2,
Type: i32,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextPara.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_GetBorders(self: *const T, ppBorders: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).GetBorders(@ptrCast(*const ITextPara2, self), ppBorders);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_GetDuplicate2(self: *const T, ppPara: ?*?*ITextPara2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).GetDuplicate2(@ptrCast(*const ITextPara2, self), ppPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_SetDuplicate2(self: *const T, pPara: ?*ITextPara2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).SetDuplicate2(@ptrCast(*const ITextPara2, self), pPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_GetFontAlignment(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).GetFontAlignment(@ptrCast(*const ITextPara2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_SetFontAlignment(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).SetFontAlignment(@ptrCast(*const ITextPara2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_GetHangingPunctuation(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).GetHangingPunctuation(@ptrCast(*const ITextPara2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_SetHangingPunctuation(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).SetHangingPunctuation(@ptrCast(*const ITextPara2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_GetSnapToGrid(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).GetSnapToGrid(@ptrCast(*const ITextPara2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_SetSnapToGrid(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).SetSnapToGrid(@ptrCast(*const ITextPara2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_GetTrimPunctuationAtStart(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).GetTrimPunctuationAtStart(@ptrCast(*const ITextPara2, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_SetTrimPunctuationAtStart(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).SetTrimPunctuationAtStart(@ptrCast(*const ITextPara2, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_GetEffects(self: *const T, pValue: ?*i32, pMask: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).GetEffects(@ptrCast(*const ITextPara2, self), pValue, pMask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_GetProperty(self: *const T, Type: i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).GetProperty(@ptrCast(*const ITextPara2, self), Type, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_IsEqual2(self: *const T, pPara: ?*ITextPara2, pB: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).IsEqual2(@ptrCast(*const ITextPara2, self), pPara, pB);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_SetEffects(self: *const T, Value: i32, Mask: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).SetEffects(@ptrCast(*const ITextPara2, self), Value, Mask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextPara2_SetProperty(self: *const T, Type: i32, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextPara2.VTable, self.vtable).SetProperty(@ptrCast(*const ITextPara2, self), Type, Value);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextStoryRanges2_Value = @import("../zig.zig").Guid.initString("c241f5e5-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextStoryRanges2 = &IID_ITextStoryRanges2_Value;
pub const ITextStoryRanges2 = extern struct {
pub const VTable = extern struct {
base: ITextStoryRanges.VTable,
Item2: fn(
self: *const ITextStoryRanges2,
Index: i32,
ppRange: ?*?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextStoryRanges.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStoryRanges2_Item2(self: *const T, Index: i32, ppRange: ?*?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStoryRanges2.VTable, self.vtable).Item2(@ptrCast(*const ITextStoryRanges2, self), Index, ppRange);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextStory_Value = @import("../zig.zig").Guid.initString("c241f5f3-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextStory = &IID_ITextStory_Value;
pub const ITextStory = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetActive: fn(
self: *const ITextStory,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetActive: fn(
self: *const ITextStory,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDisplay: fn(
self: *const ITextStory,
ppDisplay: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIndex: fn(
self: *const ITextStory,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetType: fn(
self: *const ITextStory,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetType: fn(
self: *const ITextStory,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const ITextStory,
Type: i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRange: fn(
self: *const ITextStory,
cpActive: i32,
cpAnchor: i32,
ppRange: ?*?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetText: fn(
self: *const ITextStory,
Flags: i32,
pbstr: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFormattedText: fn(
self: *const ITextStory,
pUnk: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const ITextStory,
Type: i32,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetText: fn(
self: *const ITextStory,
Flags: i32,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_GetActive(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).GetActive(@ptrCast(*const ITextStory, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_SetActive(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).SetActive(@ptrCast(*const ITextStory, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_GetDisplay(self: *const T, ppDisplay: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).GetDisplay(@ptrCast(*const ITextStory, self), ppDisplay);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_GetIndex(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).GetIndex(@ptrCast(*const ITextStory, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_GetType(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).GetType(@ptrCast(*const ITextStory, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_SetType(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).SetType(@ptrCast(*const ITextStory, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_GetProperty(self: *const T, Type: i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).GetProperty(@ptrCast(*const ITextStory, self), Type, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_GetRange(self: *const T, cpActive: i32, cpAnchor: i32, ppRange: ?*?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).GetRange(@ptrCast(*const ITextStory, self), cpActive, cpAnchor, ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_GetText(self: *const T, Flags: i32, pbstr: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).GetText(@ptrCast(*const ITextStory, self), Flags, pbstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_SetFormattedText(self: *const T, pUnk: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).SetFormattedText(@ptrCast(*const ITextStory, self), pUnk);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_SetProperty(self: *const T, Type: i32, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).SetProperty(@ptrCast(*const ITextStory, self), Type, Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStory_SetText(self: *const T, Flags: i32, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStory.VTable, self.vtable).SetText(@ptrCast(*const ITextStory, self), Flags, bstr);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextStrings_Value = @import("../zig.zig").Guid.initString("c241f5e7-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextStrings = &IID_ITextStrings_Value;
pub const ITextStrings = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
Item: fn(
self: *const ITextStrings,
Index: i32,
ppRange: ?*?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCount: fn(
self: *const ITextStrings,
pCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Add: fn(
self: *const ITextStrings,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Append: fn(
self: *const ITextStrings,
pRange: ?*ITextRange2,
iString: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Cat2: fn(
self: *const ITextStrings,
iString: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CatTop2: fn(
self: *const ITextStrings,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteRange: fn(
self: *const ITextStrings,
pRange: ?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
EncodeFunction: fn(
self: *const ITextStrings,
Type: i32,
Align: i32,
Char: i32,
Char1: i32,
Char2: i32,
Count: i32,
TeXStyle: i32,
cCol: i32,
pRange: ?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCch: fn(
self: *const ITextStrings,
iString: i32,
pcch: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InsertNullStr: fn(
self: *const ITextStrings,
iString: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MoveBoundary: fn(
self: *const ITextStrings,
iString: i32,
cch: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PrefixTop: fn(
self: *const ITextStrings,
bstr: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Remove: fn(
self: *const ITextStrings,
iString: i32,
cString: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFormattedText: fn(
self: *const ITextStrings,
pRangeD: ?*ITextRange2,
pRangeS: ?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetOpCp: fn(
self: *const ITextStrings,
iString: i32,
cp: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SuffixTop: fn(
self: *const ITextStrings,
bstr: ?BSTR,
pRange: ?*ITextRange2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Swap: fn(
self: *const ITextStrings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_Item(self: *const T, Index: i32, ppRange: ?*?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).Item(@ptrCast(*const ITextStrings, self), Index, ppRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_GetCount(self: *const T, pCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).GetCount(@ptrCast(*const ITextStrings, self), pCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_Add(self: *const T, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).Add(@ptrCast(*const ITextStrings, self), bstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_Append(self: *const T, pRange: ?*ITextRange2, iString: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).Append(@ptrCast(*const ITextStrings, self), pRange, iString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_Cat2(self: *const T, iString: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).Cat2(@ptrCast(*const ITextStrings, self), iString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_CatTop2(self: *const T, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).CatTop2(@ptrCast(*const ITextStrings, self), bstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_DeleteRange(self: *const T, pRange: ?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).DeleteRange(@ptrCast(*const ITextStrings, self), pRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_EncodeFunction(self: *const T, Type: i32, Align: i32, Char: i32, Char1: i32, Char2: i32, Count: i32, TeXStyle: i32, cCol: i32, pRange: ?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).EncodeFunction(@ptrCast(*const ITextStrings, self), Type, Align, Char, Char1, Char2, Count, TeXStyle, cCol, pRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_GetCch(self: *const T, iString: i32, pcch: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).GetCch(@ptrCast(*const ITextStrings, self), iString, pcch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_InsertNullStr(self: *const T, iString: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).InsertNullStr(@ptrCast(*const ITextStrings, self), iString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_MoveBoundary(self: *const T, iString: i32, cch: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).MoveBoundary(@ptrCast(*const ITextStrings, self), iString, cch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_PrefixTop(self: *const T, bstr: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).PrefixTop(@ptrCast(*const ITextStrings, self), bstr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_Remove(self: *const T, iString: i32, cString: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).Remove(@ptrCast(*const ITextStrings, self), iString, cString);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_SetFormattedText(self: *const T, pRangeD: ?*ITextRange2, pRangeS: ?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).SetFormattedText(@ptrCast(*const ITextStrings, self), pRangeD, pRangeS);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_SetOpCp(self: *const T, iString: i32, cp: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).SetOpCp(@ptrCast(*const ITextStrings, self), iString, cp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_SuffixTop(self: *const T, bstr: ?BSTR, pRange: ?*ITextRange2) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).SuffixTop(@ptrCast(*const ITextStrings, self), bstr, pRange);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextStrings_Swap(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextStrings.VTable, self.vtable).Swap(@ptrCast(*const ITextStrings, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextRow_Value = @import("../zig.zig").Guid.initString("c241f5ef-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextRow = &IID_ITextRow_Value;
pub const ITextRow = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
GetAlignment: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetAlignment: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellCount: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellCount: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellCountCache: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellCountCache: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellIndex: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellIndex: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellMargin: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellMargin: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetHeight: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHeight: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetIndent: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIndent: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetKeepTogether: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetKeepTogether: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetKeepWithNext: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetKeepWithNext: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNestLevel: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRTL: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetRTL: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellAlignment: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellAlignment: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellColorBack: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellColorBack: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellColorFore: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellColorFore: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellMergeFlags: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellMergeFlags: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellShading: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellShading: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellVerticalText: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellVerticalText: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellWidth: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellWidth: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellBorderColors: fn(
self: *const ITextRow,
pcrLeft: ?*i32,
pcrTop: ?*i32,
pcrRight: ?*i32,
pcrBottom: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCellBorderWidths: fn(
self: *const ITextRow,
pduLeft: ?*i32,
pduTop: ?*i32,
pduRight: ?*i32,
pduBottom: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellBorderColors: fn(
self: *const ITextRow,
crLeft: i32,
crTop: i32,
crRight: i32,
crBottom: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCellBorderWidths: fn(
self: *const ITextRow,
duLeft: i32,
duTop: i32,
duRight: i32,
duBottom: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Apply: fn(
self: *const ITextRow,
cRow: i32,
Flags: tomConstants,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CanChange: fn(
self: *const ITextRow,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const ITextRow,
Type: i32,
pValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Insert: fn(
self: *const ITextRow,
cRow: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsEqual: fn(
self: *const ITextRow,
pRow: ?*ITextRow,
pB: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Reset: fn(
self: *const ITextRow,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const ITextRow,
Type: i32,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetAlignment(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetAlignment(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetAlignment(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetAlignment(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellCount(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellCount(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellCount(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellCount(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellCountCache(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellCountCache(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellCountCache(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellCountCache(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellIndex(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellIndex(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellIndex(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellIndex(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellMargin(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellMargin(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellMargin(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellMargin(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetHeight(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetHeight(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetHeight(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetHeight(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetIndent(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetIndent(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetIndent(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetIndent(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetKeepTogether(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetKeepTogether(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetKeepTogether(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetKeepTogether(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetKeepWithNext(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetKeepWithNext(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetKeepWithNext(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetKeepWithNext(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetNestLevel(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetNestLevel(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetRTL(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetRTL(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetRTL(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetRTL(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellAlignment(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellAlignment(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellAlignment(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellAlignment(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellColorBack(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellColorBack(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellColorBack(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellColorBack(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellColorFore(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellColorFore(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellColorFore(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellColorFore(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellMergeFlags(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellMergeFlags(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellMergeFlags(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellMergeFlags(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellShading(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellShading(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellShading(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellShading(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellVerticalText(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellVerticalText(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellVerticalText(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellVerticalText(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellWidth(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellWidth(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellWidth(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellWidth(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellBorderColors(self: *const T, pcrLeft: ?*i32, pcrTop: ?*i32, pcrRight: ?*i32, pcrBottom: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellBorderColors(@ptrCast(*const ITextRow, self), pcrLeft, pcrTop, pcrRight, pcrBottom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetCellBorderWidths(self: *const T, pduLeft: ?*i32, pduTop: ?*i32, pduRight: ?*i32, pduBottom: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetCellBorderWidths(@ptrCast(*const ITextRow, self), pduLeft, pduTop, pduRight, pduBottom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellBorderColors(self: *const T, crLeft: i32, crTop: i32, crRight: i32, crBottom: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellBorderColors(@ptrCast(*const ITextRow, self), crLeft, crTop, crRight, crBottom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetCellBorderWidths(self: *const T, duLeft: i32, duTop: i32, duRight: i32, duBottom: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetCellBorderWidths(@ptrCast(*const ITextRow, self), duLeft, duTop, duRight, duBottom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_Apply(self: *const T, cRow: i32, Flags: tomConstants) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).Apply(@ptrCast(*const ITextRow, self), cRow, Flags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_CanChange(self: *const T, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).CanChange(@ptrCast(*const ITextRow, self), pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_GetProperty(self: *const T, Type: i32, pValue: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).GetProperty(@ptrCast(*const ITextRow, self), Type, pValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_Insert(self: *const T, cRow: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).Insert(@ptrCast(*const ITextRow, self), cRow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_IsEqual(self: *const T, pRow: ?*ITextRow, pB: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).IsEqual(@ptrCast(*const ITextRow, self), pRow, pB);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_Reset(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).Reset(@ptrCast(*const ITextRow, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextRow_SetProperty(self: *const T, Type: i32, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextRow.VTable, self.vtable).SetProperty(@ptrCast(*const ITextRow, self), Type, Value);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ITextDisplays_Value = @import("../zig.zig").Guid.initString("c241f5f2-7206-11d8-a2c7-00a0d1d6c6b3");
pub const IID_ITextDisplays = &IID_ITextDisplays_Value;
pub const ITextDisplays = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
const IID_ITextDocument2Old_Value = @import("../zig.zig").Guid.initString("01c25500-4268-11d1-883a-3c8b00c10000");
pub const IID_ITextDocument2Old = &IID_ITextDocument2Old_Value;
pub const ITextDocument2Old = extern struct {
pub const VTable = extern struct {
base: ITextDocument.VTable,
AttachMsgFilter: fn(
self: *const ITextDocument2Old,
pFilter: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetEffectColor: fn(
self: *const ITextDocument2Old,
Index: i32,
cr: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEffectColor: fn(
self: *const ITextDocument2Old,
Index: i32,
pcr: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCaretType: fn(
self: *const ITextDocument2Old,
pCaretType: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCaretType: fn(
self: *const ITextDocument2Old,
CaretType: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetImmContext: fn(
self: *const ITextDocument2Old,
pContext: ?*i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseImmContext: fn(
self: *const ITextDocument2Old,
Context: i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPreferredFont: fn(
self: *const ITextDocument2Old,
cp: i32,
CharRep: i32,
Option: i32,
CharRepCur: i32,
curFontSize: i32,
pbstr: ?*?BSTR,
pPitchAndFamily: ?*i32,
pNewFontSize: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetNotificationMode: fn(
self: *const ITextDocument2Old,
pMode: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetNotificationMode: fn(
self: *const ITextDocument2Old,
Mode: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetClientRect: fn(
self: *const ITextDocument2Old,
Type: i32,
pLeft: ?*i32,
pTop: ?*i32,
pRight: ?*i32,
pBottom: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSelection2: fn(
self: *const ITextDocument2Old,
ppSel: ?*?*ITextSelection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWindow: fn(
self: *const ITextDocument2Old,
phWnd: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFEFlags: fn(
self: *const ITextDocument2Old,
pFlags: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UpdateWindow: fn(
self: *const ITextDocument2Old,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CheckTextLimit: fn(
self: *const ITextDocument2Old,
cch: i32,
pcch: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IMEInProgress: fn(
self: *const ITextDocument2Old,
Value: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SysBeep: fn(
self: *const ITextDocument2Old,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Update: fn(
self: *const ITextDocument2Old,
Mode: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Notify: fn(
self: *const ITextDocument2Old,
Notify: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDocumentFont: fn(
self: *const ITextDocument2Old,
ppITextFont: ?*?*ITextFont,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDocumentPara: fn(
self: *const ITextDocument2Old,
ppITextPara: ?*?*ITextPara,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCallManager: fn(
self: *const ITextDocument2Old,
ppVoid: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ReleaseCallManager: fn(
self: *const ITextDocument2Old,
pVoid: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextDocument.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_AttachMsgFilter(self: *const T, pFilter: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).AttachMsgFilter(@ptrCast(*const ITextDocument2Old, self), pFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_SetEffectColor(self: *const T, Index: i32, cr: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).SetEffectColor(@ptrCast(*const ITextDocument2Old, self), Index, cr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetEffectColor(self: *const T, Index: i32, pcr: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetEffectColor(@ptrCast(*const ITextDocument2Old, self), Index, pcr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetCaretType(self: *const T, pCaretType: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetCaretType(@ptrCast(*const ITextDocument2Old, self), pCaretType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_SetCaretType(self: *const T, CaretType: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).SetCaretType(@ptrCast(*const ITextDocument2Old, self), CaretType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetImmContext(self: *const T, pContext: ?*i64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetImmContext(@ptrCast(*const ITextDocument2Old, self), pContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_ReleaseImmContext(self: *const T, Context: i64) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).ReleaseImmContext(@ptrCast(*const ITextDocument2Old, self), Context);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetPreferredFont(self: *const T, cp: i32, CharRep: i32, Option: i32, CharRepCur: i32, curFontSize: i32, pbstr: ?*?BSTR, pPitchAndFamily: ?*i32, pNewFontSize: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetPreferredFont(@ptrCast(*const ITextDocument2Old, self), cp, CharRep, Option, CharRepCur, curFontSize, pbstr, pPitchAndFamily, pNewFontSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetNotificationMode(self: *const T, pMode: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetNotificationMode(@ptrCast(*const ITextDocument2Old, self), pMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_SetNotificationMode(self: *const T, Mode: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).SetNotificationMode(@ptrCast(*const ITextDocument2Old, self), Mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetClientRect(self: *const T, Type: i32, pLeft: ?*i32, pTop: ?*i32, pRight: ?*i32, pBottom: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetClientRect(@ptrCast(*const ITextDocument2Old, self), Type, pLeft, pTop, pRight, pBottom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetSelection2(self: *const T, ppSel: ?*?*ITextSelection) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetSelection2(@ptrCast(*const ITextDocument2Old, self), ppSel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetWindow(self: *const T, phWnd: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetWindow(@ptrCast(*const ITextDocument2Old, self), phWnd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetFEFlags(self: *const T, pFlags: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetFEFlags(@ptrCast(*const ITextDocument2Old, self), pFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_UpdateWindow(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).UpdateWindow(@ptrCast(*const ITextDocument2Old, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_CheckTextLimit(self: *const T, cch: i32, pcch: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).CheckTextLimit(@ptrCast(*const ITextDocument2Old, self), cch, pcch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_IMEInProgress(self: *const T, Value: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).IMEInProgress(@ptrCast(*const ITextDocument2Old, self), Value);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_SysBeep(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).SysBeep(@ptrCast(*const ITextDocument2Old, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_Update(self: *const T, Mode: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).Update(@ptrCast(*const ITextDocument2Old, self), Mode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_Notify(self: *const T, Notify: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).Notify(@ptrCast(*const ITextDocument2Old, self), Notify);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetDocumentFont(self: *const T, ppITextFont: ?*?*ITextFont) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetDocumentFont(@ptrCast(*const ITextDocument2Old, self), ppITextFont);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetDocumentPara(self: *const T, ppITextPara: ?*?*ITextPara) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetDocumentPara(@ptrCast(*const ITextDocument2Old, self), ppITextPara);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_GetCallManager(self: *const T, ppVoid: ?*?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).GetCallManager(@ptrCast(*const ITextDocument2Old, self), ppVoid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextDocument2Old_ReleaseCallManager(self: *const T, pVoid: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextDocument2Old.VTable, self.vtable).ReleaseCallManager(@ptrCast(*const ITextDocument2Old, self), pVoid);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const REOBJECT = extern struct {
cbStruct: u32,
cp: i32,
clsid: Guid,
poleobj: ?*IOleObject,
pstg: ?*IStorage,
polesite: ?*IOleClientSite,
sizel: SIZE,
dvaspect: u32,
dwFlags: REOBJECT_FLAGS,
dwUser: u32,
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IRichEditOle_Value = @import("../zig.zig").Guid.initString("00020d00-0000-0000-c000-000000000046");
pub const IID_IRichEditOle = &IID_IRichEditOle_Value;
pub const IRichEditOle = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetClientSite: fn(
self: *const IRichEditOle,
lplpolesite: ?*?*IOleClientSite,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetObjectCount: fn(
self: *const IRichEditOle,
) callconv(@import("std").os.windows.WINAPI) i32,
GetLinkCount: fn(
self: *const IRichEditOle,
) callconv(@import("std").os.windows.WINAPI) i32,
GetObject: fn(
self: *const IRichEditOle,
iob: i32,
lpreobject: ?*REOBJECT,
dwFlags: RICH_EDIT_GET_OBJECT_FLAGS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InsertObject: fn(
self: *const IRichEditOle,
lpreobject: ?*REOBJECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ConvertObject: fn(
self: *const IRichEditOle,
iob: i32,
rclsidNew: ?*const Guid,
lpstrUserTypeNew: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ActivateAs: fn(
self: *const IRichEditOle,
rclsid: ?*const Guid,
rclsidAs: ?*const Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetHostNames: fn(
self: *const IRichEditOle,
lpstrContainerApp: ?[*:0]const u8,
lpstrContainerObj: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetLinkAvailable: fn(
self: *const IRichEditOle,
iob: i32,
fAvailable: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDvaspect: fn(
self: *const IRichEditOle,
iob: i32,
dvaspect: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
HandsOffStorage: fn(
self: *const IRichEditOle,
iob: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SaveCompleted: fn(
self: *const IRichEditOle,
iob: i32,
lpstg: ?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InPlaceDeactivate: fn(
self: *const IRichEditOle,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ContextSensitiveHelp: fn(
self: *const IRichEditOle,
fEnterMode: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetClipboardData: fn(
self: *const IRichEditOle,
lpchrg: ?*CHARRANGE,
reco: u32,
lplpdataobj: ?*?*IDataObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ImportDataObject: fn(
self: *const IRichEditOle,
lpdataobj: ?*IDataObject,
cf: u16,
hMetaPict: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_GetClientSite(self: *const T, lplpolesite: ?*?*IOleClientSite) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).GetClientSite(@ptrCast(*const IRichEditOle, self), lplpolesite);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_GetObjectCount(self: *const T) callconv(.Inline) i32 {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).GetObjectCount(@ptrCast(*const IRichEditOle, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_GetLinkCount(self: *const T) callconv(.Inline) i32 {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).GetLinkCount(@ptrCast(*const IRichEditOle, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_GetObject(self: *const T, iob: i32, lpreobject: ?*REOBJECT, dwFlags: RICH_EDIT_GET_OBJECT_FLAGS) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).GetObject(@ptrCast(*const IRichEditOle, self), iob, lpreobject, dwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_InsertObject(self: *const T, lpreobject: ?*REOBJECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).InsertObject(@ptrCast(*const IRichEditOle, self), lpreobject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_ConvertObject(self: *const T, iob: i32, rclsidNew: ?*const Guid, lpstrUserTypeNew: ?[*:0]const u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).ConvertObject(@ptrCast(*const IRichEditOle, self), iob, rclsidNew, lpstrUserTypeNew);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_ActivateAs(self: *const T, rclsid: ?*const Guid, rclsidAs: ?*const Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).ActivateAs(@ptrCast(*const IRichEditOle, self), rclsid, rclsidAs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_SetHostNames(self: *const T, lpstrContainerApp: ?[*:0]const u8, lpstrContainerObj: ?[*:0]const u8) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).SetHostNames(@ptrCast(*const IRichEditOle, self), lpstrContainerApp, lpstrContainerObj);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_SetLinkAvailable(self: *const T, iob: i32, fAvailable: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).SetLinkAvailable(@ptrCast(*const IRichEditOle, self), iob, fAvailable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_SetDvaspect(self: *const T, iob: i32, dvaspect: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).SetDvaspect(@ptrCast(*const IRichEditOle, self), iob, dvaspect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_HandsOffStorage(self: *const T, iob: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).HandsOffStorage(@ptrCast(*const IRichEditOle, self), iob);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_SaveCompleted(self: *const T, iob: i32, lpstg: ?*IStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).SaveCompleted(@ptrCast(*const IRichEditOle, self), iob, lpstg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_InPlaceDeactivate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).InPlaceDeactivate(@ptrCast(*const IRichEditOle, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_ContextSensitiveHelp(self: *const T, fEnterMode: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).ContextSensitiveHelp(@ptrCast(*const IRichEditOle, self), fEnterMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_GetClipboardData(self: *const T, lpchrg: ?*CHARRANGE, reco: u32, lplpdataobj: ?*?*IDataObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).GetClipboardData(@ptrCast(*const IRichEditOle, self), lpchrg, reco, lplpdataobj);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOle_ImportDataObject(self: *const T, lpdataobj: ?*IDataObject, cf: u16, hMetaPict: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOle.VTable, self.vtable).ImportDataObject(@ptrCast(*const IRichEditOle, self), lpdataobj, cf, hMetaPict);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_IRichEditOleCallback_Value = @import("../zig.zig").Guid.initString("00020d03-0000-0000-c000-000000000046");
pub const IID_IRichEditOleCallback = &IID_IRichEditOleCallback_Value;
pub const IRichEditOleCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetNewStorage: fn(
self: *const IRichEditOleCallback,
lplpstg: ?*?*IStorage,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInPlaceContext: fn(
self: *const IRichEditOleCallback,
lplpFrame: ?*?*IOleInPlaceFrame,
lplpDoc: ?*?*IOleInPlaceUIWindow,
lpFrameInfo: ?*OIFI,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ShowContainerUI: fn(
self: *const IRichEditOleCallback,
fShow: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryInsertObject: fn(
self: *const IRichEditOleCallback,
lpclsid: ?*Guid,
lpstg: ?*IStorage,
cp: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteObject: fn(
self: *const IRichEditOleCallback,
lpoleobj: ?*IOleObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
QueryAcceptData: fn(
self: *const IRichEditOleCallback,
lpdataobj: ?*IDataObject,
lpcfFormat: ?*u16,
reco: u32,
fReally: BOOL,
hMetaPict: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ContextSensitiveHelp: fn(
self: *const IRichEditOleCallback,
fEnterMode: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetClipboardData: fn(
self: *const IRichEditOleCallback,
lpchrg: ?*CHARRANGE,
reco: u32,
lplpdataobj: ?*?*IDataObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetDragDropEffect: fn(
self: *const IRichEditOleCallback,
fDrag: BOOL,
grfKeyState: u32,
pdwEffect: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContextMenu: fn(
self: *const IRichEditOleCallback,
seltype: RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE,
lpoleobj: ?*IOleObject,
lpchrg: ?*CHARRANGE,
lphmenu: ?*?HMENU,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_GetNewStorage(self: *const T, lplpstg: ?*?*IStorage) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).GetNewStorage(@ptrCast(*const IRichEditOleCallback, self), lplpstg);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_GetInPlaceContext(self: *const T, lplpFrame: ?*?*IOleInPlaceFrame, lplpDoc: ?*?*IOleInPlaceUIWindow, lpFrameInfo: ?*OIFI) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).GetInPlaceContext(@ptrCast(*const IRichEditOleCallback, self), lplpFrame, lplpDoc, lpFrameInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_ShowContainerUI(self: *const T, fShow: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).ShowContainerUI(@ptrCast(*const IRichEditOleCallback, self), fShow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_QueryInsertObject(self: *const T, lpclsid: ?*Guid, lpstg: ?*IStorage, cp: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).QueryInsertObject(@ptrCast(*const IRichEditOleCallback, self), lpclsid, lpstg, cp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_DeleteObject(self: *const T, lpoleobj: ?*IOleObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).DeleteObject(@ptrCast(*const IRichEditOleCallback, self), lpoleobj);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_QueryAcceptData(self: *const T, lpdataobj: ?*IDataObject, lpcfFormat: ?*u16, reco: u32, fReally: BOOL, hMetaPict: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).QueryAcceptData(@ptrCast(*const IRichEditOleCallback, self), lpdataobj, lpcfFormat, reco, fReally, hMetaPict);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_ContextSensitiveHelp(self: *const T, fEnterMode: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).ContextSensitiveHelp(@ptrCast(*const IRichEditOleCallback, self), fEnterMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_GetClipboardData(self: *const T, lpchrg: ?*CHARRANGE, reco: u32, lplpdataobj: ?*?*IDataObject) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).GetClipboardData(@ptrCast(*const IRichEditOleCallback, self), lpchrg, reco, lplpdataobj);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_GetDragDropEffect(self: *const T, fDrag: BOOL, grfKeyState: u32, pdwEffect: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).GetDragDropEffect(@ptrCast(*const IRichEditOleCallback, self), fDrag, grfKeyState, pdwEffect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditOleCallback_GetContextMenu(self: *const T, seltype: RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE, lpoleobj: ?*IOleObject, lpchrg: ?*CHARRANGE, lphmenu: ?*?HMENU) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditOleCallback.VTable, self.vtable).GetContextMenu(@ptrCast(*const IRichEditOleCallback, self), seltype, lpoleobj, lpchrg, lphmenu);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const TXTBACKSTYLE = enum(i32) {
TRANSPARENT = 0,
OPAQUE = 1,
};
pub const TXTBACK_TRANSPARENT = TXTBACKSTYLE.TRANSPARENT;
pub const TXTBACK_OPAQUE = TXTBACKSTYLE.OPAQUE;
pub const TXTHITRESULT = enum(i32) {
NOHIT = 0,
TRANSPARENT = 1,
CLOSE = 2,
HIT = 3,
};
pub const TXTHITRESULT_NOHIT = TXTHITRESULT.NOHIT;
pub const TXTHITRESULT_TRANSPARENT = TXTHITRESULT.TRANSPARENT;
pub const TXTHITRESULT_CLOSE = TXTHITRESULT.CLOSE;
pub const TXTHITRESULT_HIT = TXTHITRESULT.HIT;
pub const TXTNATURALSIZE = enum(i32) {
FITTOCONTENT2 = 0,
FITTOCONTENT = 1,
ROUNDTOLINE = 2,
FITTOCONTENT3 = 3,
FITTOCONTENTWSP = 4,
INCLUDELASTLINE = 1073741824,
EMU = -2147483648,
};
pub const TXTNS_FITTOCONTENT2 = TXTNATURALSIZE.FITTOCONTENT2;
pub const TXTNS_FITTOCONTENT = TXTNATURALSIZE.FITTOCONTENT;
pub const TXTNS_ROUNDTOLINE = TXTNATURALSIZE.ROUNDTOLINE;
pub const TXTNS_FITTOCONTENT3 = TXTNATURALSIZE.FITTOCONTENT3;
pub const TXTNS_FITTOCONTENTWSP = TXTNATURALSIZE.FITTOCONTENTWSP;
pub const TXTNS_INCLUDELASTLINE = TXTNATURALSIZE.INCLUDELASTLINE;
pub const TXTNS_EMU = TXTNATURALSIZE.EMU;
pub const TXTVIEW = enum(i32) {
ACTIVE = 0,
INACTIVE = -1,
};
pub const TXTVIEW_ACTIVE = TXTVIEW.ACTIVE;
pub const TXTVIEW_INACTIVE = TXTVIEW.INACTIVE;
pub const CHANGETYPE = enum(i32) {
GENERIC = 0,
TEXTCHANGED = 1,
NEWUNDO = 2,
NEWREDO = 4,
};
pub const CN_GENERIC = CHANGETYPE.GENERIC;
pub const CN_TEXTCHANGED = CHANGETYPE.TEXTCHANGED;
pub const CN_NEWUNDO = CHANGETYPE.NEWUNDO;
pub const CN_NEWREDO = CHANGETYPE.NEWREDO;
pub const CHANGENOTIFY = extern struct {
dwChangeType: CHANGETYPE,
pvCookieData: ?*c_void,
};
pub const ITextServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
TxSendMessage: fn(
self: *const ITextServices,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
plresult: ?*LRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxDraw: fn(
self: *const ITextServices,
dwDrawAspect: DVASPECT,
lindex: i32,
pvAspect: ?*c_void,
ptd: ?*DVTARGETDEVICE,
hdcDraw: ?HDC,
hicTargetDev: ?HDC,
lprcBounds: ?*RECTL,
lprcWBounds: ?*RECTL,
lprcUpdate: ?*RECT,
pfnContinue: isize,
dwContinue: u32,
lViewId: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetHScroll: fn(
self: *const ITextServices,
plMin: ?*i32,
plMax: ?*i32,
plPos: ?*i32,
plPage: ?*i32,
pfEnabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetVScroll: fn(
self: *const ITextServices,
plMin: ?*i32,
plMax: ?*i32,
plPos: ?*i32,
plPage: ?*i32,
pfEnabled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnTxSetCursor: fn(
self: *const ITextServices,
dwDrawAspect: DVASPECT,
lindex: i32,
pvAspect: ?*c_void,
ptd: ?*DVTARGETDEVICE,
hdcDraw: ?HDC,
hicTargetDev: ?HDC,
lprcClient: ?*RECT,
x: i32,
y: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxQueryHitPoint: fn(
self: *const ITextServices,
dwDrawAspect: DVASPECT,
lindex: i32,
pvAspect: ?*c_void,
ptd: ?*DVTARGETDEVICE,
hdcDraw: ?HDC,
hicTargetDev: ?HDC,
lprcClient: ?*RECT,
x: i32,
y: i32,
pHitResult: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnTxInPlaceActivate: fn(
self: *const ITextServices,
prcClient: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnTxInPlaceDeactivate: fn(
self: *const ITextServices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnTxUIActivate: fn(
self: *const ITextServices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnTxUIDeactivate: fn(
self: *const ITextServices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetText: fn(
self: *const ITextServices,
pbstrText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxSetText: fn(
self: *const ITextServices,
pszText: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetCurTargetX: fn(
self: *const ITextServices,
param0: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetBaseLinePos: fn(
self: *const ITextServices,
param0: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetNaturalSize: fn(
self: *const ITextServices,
dwAspect: u32,
hdcDraw: ?HDC,
hicTargetDev: ?HDC,
ptd: ?*DVTARGETDEVICE,
dwMode: u32,
psizelExtent: ?*const SIZE,
pwidth: ?*i32,
pheight: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetDropTarget: fn(
self: *const ITextServices,
ppDropTarget: ?*?*IDropTarget,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnTxPropertyBitsChange: fn(
self: *const ITextServices,
dwMask: u32,
dwBits: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetCachedSize: fn(
self: *const ITextServices,
pdwWidth: ?*u32,
pdwHeight: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxSendMessage(self: *const T, msg: u32, wparam: WPARAM, lparam: LPARAM, plresult: ?*LRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxSendMessage(@ptrCast(*const ITextServices, self), msg, wparam, lparam, plresult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxDraw(self: *const T, dwDrawAspect: DVASPECT, lindex: i32, pvAspect: ?*c_void, ptd: ?*DVTARGETDEVICE, hdcDraw: ?HDC, hicTargetDev: ?HDC, lprcBounds: ?*RECTL, lprcWBounds: ?*RECTL, lprcUpdate: ?*RECT, pfnContinue: isize, dwContinue: u32, lViewId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxDraw(@ptrCast(*const ITextServices, self), dwDrawAspect, lindex, pvAspect, ptd, hdcDraw, hicTargetDev, lprcBounds, lprcWBounds, lprcUpdate, pfnContinue, dwContinue, lViewId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxGetHScroll(self: *const T, plMin: ?*i32, plMax: ?*i32, plPos: ?*i32, plPage: ?*i32, pfEnabled: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxGetHScroll(@ptrCast(*const ITextServices, self), plMin, plMax, plPos, plPage, pfEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxGetVScroll(self: *const T, plMin: ?*i32, plMax: ?*i32, plPos: ?*i32, plPage: ?*i32, pfEnabled: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxGetVScroll(@ptrCast(*const ITextServices, self), plMin, plMax, plPos, plPage, pfEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_OnTxSetCursor(self: *const T, dwDrawAspect: DVASPECT, lindex: i32, pvAspect: ?*c_void, ptd: ?*DVTARGETDEVICE, hdcDraw: ?HDC, hicTargetDev: ?HDC, lprcClient: ?*RECT, x: i32, y: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).OnTxSetCursor(@ptrCast(*const ITextServices, self), dwDrawAspect, lindex, pvAspect, ptd, hdcDraw, hicTargetDev, lprcClient, x, y);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxQueryHitPoint(self: *const T, dwDrawAspect: DVASPECT, lindex: i32, pvAspect: ?*c_void, ptd: ?*DVTARGETDEVICE, hdcDraw: ?HDC, hicTargetDev: ?HDC, lprcClient: ?*RECT, x: i32, y: i32, pHitResult: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxQueryHitPoint(@ptrCast(*const ITextServices, self), dwDrawAspect, lindex, pvAspect, ptd, hdcDraw, hicTargetDev, lprcClient, x, y, pHitResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_OnTxInPlaceActivate(self: *const T, prcClient: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).OnTxInPlaceActivate(@ptrCast(*const ITextServices, self), prcClient);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_OnTxInPlaceDeactivate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).OnTxInPlaceDeactivate(@ptrCast(*const ITextServices, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_OnTxUIActivate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).OnTxUIActivate(@ptrCast(*const ITextServices, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_OnTxUIDeactivate(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).OnTxUIDeactivate(@ptrCast(*const ITextServices, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxGetText(self: *const T, pbstrText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxGetText(@ptrCast(*const ITextServices, self), pbstrText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxSetText(self: *const T, pszText: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxSetText(@ptrCast(*const ITextServices, self), pszText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxGetCurTargetX(self: *const T, param0: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxGetCurTargetX(@ptrCast(*const ITextServices, self), param0);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxGetBaseLinePos(self: *const T, param0: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxGetBaseLinePos(@ptrCast(*const ITextServices, self), param0);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxGetNaturalSize(self: *const T, dwAspect: u32, hdcDraw: ?HDC, hicTargetDev: ?HDC, ptd: ?*DVTARGETDEVICE, dwMode: u32, psizelExtent: ?*const SIZE, pwidth: ?*i32, pheight: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxGetNaturalSize(@ptrCast(*const ITextServices, self), dwAspect, hdcDraw, hicTargetDev, ptd, dwMode, psizelExtent, pwidth, pheight);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxGetDropTarget(self: *const T, ppDropTarget: ?*?*IDropTarget) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxGetDropTarget(@ptrCast(*const ITextServices, self), ppDropTarget);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_OnTxPropertyBitsChange(self: *const T, dwMask: u32, dwBits: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).OnTxPropertyBitsChange(@ptrCast(*const ITextServices, self), dwMask, dwBits);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices_TxGetCachedSize(self: *const T, pdwWidth: ?*u32, pdwHeight: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices.VTable, self.vtable).TxGetCachedSize(@ptrCast(*const ITextServices, self), pdwWidth, pdwHeight);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const CARET_FLAGS = enum(i32) {
NONE = 0,
CUSTOM = 1,
RTL = 2,
ITALIC = 32,
NULL = 64,
ROTATE90 = 128,
};
pub const CARET_NONE = CARET_FLAGS.NONE;
pub const CARET_CUSTOM = CARET_FLAGS.CUSTOM;
pub const CARET_RTL = CARET_FLAGS.RTL;
pub const CARET_ITALIC = CARET_FLAGS.ITALIC;
pub const CARET_NULL = CARET_FLAGS.NULL;
pub const CARET_ROTATE90 = CARET_FLAGS.ROTATE90;
pub const CARET_INFO = extern union {
hbitmap: ?HBITMAP,
caretFlags: CARET_FLAGS,
};
pub const ITextHost = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
TxGetDC: fn(
self: *const ITextHost,
) callconv(@import("std").os.windows.WINAPI) ?HDC,
TxReleaseDC: fn(
self: *const ITextHost,
hdc: ?HDC,
) callconv(@import("std").os.windows.WINAPI) i32,
TxShowScrollBar: fn(
self: *const ITextHost,
fnBar: i32,
fShow: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxEnableScrollBar: fn(
self: *const ITextHost,
fuSBFlags: SCROLLBAR_CONSTANTS,
fuArrowflags: ENABLE_SCROLL_BAR_ARROWS,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxSetScrollRange: fn(
self: *const ITextHost,
fnBar: i32,
nMinPos: i32,
nMaxPos: i32,
fRedraw: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxSetScrollPos: fn(
self: *const ITextHost,
fnBar: i32,
nPos: i32,
fRedraw: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxInvalidateRect: fn(
self: *const ITextHost,
prc: ?*RECT,
fMode: BOOL,
) callconv(@import("std").os.windows.WINAPI) void,
TxViewChange: fn(
self: *const ITextHost,
fUpdate: BOOL,
) callconv(@import("std").os.windows.WINAPI) void,
TxCreateCaret: fn(
self: *const ITextHost,
hbmp: ?HBITMAP,
xWidth: i32,
yHeight: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxShowCaret: fn(
self: *const ITextHost,
fShow: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxSetCaretPos: fn(
self: *const ITextHost,
x: i32,
y: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxSetTimer: fn(
self: *const ITextHost,
idTimer: u32,
uTimeout: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxKillTimer: fn(
self: *const ITextHost,
idTimer: u32,
) callconv(@import("std").os.windows.WINAPI) void,
TxScrollWindowEx: fn(
self: *const ITextHost,
dx: i32,
dy: i32,
lprcScroll: ?*RECT,
lprcClip: ?*RECT,
hrgnUpdate: ?HRGN,
lprcUpdate: ?*RECT,
fuScroll: SHOW_WINDOW_CMD,
) callconv(@import("std").os.windows.WINAPI) void,
TxSetCapture: fn(
self: *const ITextHost,
fCapture: BOOL,
) callconv(@import("std").os.windows.WINAPI) void,
TxSetFocus: fn(
self: *const ITextHost,
) callconv(@import("std").os.windows.WINAPI) void,
TxSetCursor: fn(
self: *const ITextHost,
hcur: ?HCURSOR,
fText: BOOL,
) callconv(@import("std").os.windows.WINAPI) void,
TxScreenToClient: fn(
self: *const ITextHost,
lppt: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxClientToScreen: fn(
self: *const ITextHost,
lppt: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxActivate: fn(
self: *const ITextHost,
plOldState: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxDeactivate: fn(
self: *const ITextHost,
lNewState: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetClientRect: fn(
self: *const ITextHost,
prc: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetViewInset: fn(
self: *const ITextHost,
prc: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetCharFormat: fn(
self: *const ITextHost,
ppCF: ?*const ?*CHARFORMATW,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetParaFormat: fn(
self: *const ITextHost,
ppPF: ?*const ?*PARAFORMAT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetSysColor: fn(
self: *const ITextHost,
nIndex: i32,
) callconv(@import("std").os.windows.WINAPI) u32,
TxGetBackStyle: fn(
self: *const ITextHost,
pstyle: ?*TXTBACKSTYLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetMaxLength: fn(
self: *const ITextHost,
plength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetScrollBars: fn(
self: *const ITextHost,
pdwScrollBar: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetPasswordChar: fn(
self: *const ITextHost,
pch: ?*i8,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetAcceleratorPos: fn(
self: *const ITextHost,
pcp: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetExtent: fn(
self: *const ITextHost,
lpExtent: ?*SIZE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnTxCharFormatChange: fn(
self: *const ITextHost,
pCF: ?*const CHARFORMATW,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnTxParaFormatChange: fn(
self: *const ITextHost,
pPF: ?*const PARAFORMAT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetPropertyBits: fn(
self: *const ITextHost,
dwMask: u32,
pdwBits: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxNotify: fn(
self: *const ITextHost,
iNotify: u32,
pv: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxImmGetContext: fn(
self: *const ITextHost,
) callconv(@import("std").os.windows.WINAPI) ?HIMC,
TxImmReleaseContext: fn(
self: *const ITextHost,
himc: ?HIMC,
) callconv(@import("std").os.windows.WINAPI) void,
TxGetSelectionBarWidth: fn(
self: *const ITextHost,
lSelBarWidth: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetDC(self: *const T) callconv(.Inline) ?HDC {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetDC(@ptrCast(*const ITextHost, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxReleaseDC(self: *const T, hdc: ?HDC) callconv(.Inline) i32 {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxReleaseDC(@ptrCast(*const ITextHost, self), hdc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxShowScrollBar(self: *const T, fnBar: i32, fShow: BOOL) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxShowScrollBar(@ptrCast(*const ITextHost, self), fnBar, fShow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxEnableScrollBar(self: *const T, fuSBFlags: SCROLLBAR_CONSTANTS, fuArrowflags: ENABLE_SCROLL_BAR_ARROWS) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxEnableScrollBar(@ptrCast(*const ITextHost, self), fuSBFlags, fuArrowflags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxSetScrollRange(self: *const T, fnBar: i32, nMinPos: i32, nMaxPos: i32, fRedraw: BOOL) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxSetScrollRange(@ptrCast(*const ITextHost, self), fnBar, nMinPos, nMaxPos, fRedraw);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxSetScrollPos(self: *const T, fnBar: i32, nPos: i32, fRedraw: BOOL) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxSetScrollPos(@ptrCast(*const ITextHost, self), fnBar, nPos, fRedraw);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxInvalidateRect(self: *const T, prc: ?*RECT, fMode: BOOL) callconv(.Inline) void {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxInvalidateRect(@ptrCast(*const ITextHost, self), prc, fMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxViewChange(self: *const T, fUpdate: BOOL) callconv(.Inline) void {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxViewChange(@ptrCast(*const ITextHost, self), fUpdate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxCreateCaret(self: *const T, hbmp: ?HBITMAP, xWidth: i32, yHeight: i32) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxCreateCaret(@ptrCast(*const ITextHost, self), hbmp, xWidth, yHeight);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxShowCaret(self: *const T, fShow: BOOL) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxShowCaret(@ptrCast(*const ITextHost, self), fShow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxSetCaretPos(self: *const T, x: i32, y: i32) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxSetCaretPos(@ptrCast(*const ITextHost, self), x, y);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxSetTimer(self: *const T, idTimer: u32, uTimeout: u32) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxSetTimer(@ptrCast(*const ITextHost, self), idTimer, uTimeout);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxKillTimer(self: *const T, idTimer: u32) callconv(.Inline) void {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxKillTimer(@ptrCast(*const ITextHost, self), idTimer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxScrollWindowEx(self: *const T, dx: i32, dy: i32, lprcScroll: ?*RECT, lprcClip: ?*RECT, hrgnUpdate: ?HRGN, lprcUpdate: ?*RECT, fuScroll: SHOW_WINDOW_CMD) callconv(.Inline) void {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxScrollWindowEx(@ptrCast(*const ITextHost, self), dx, dy, lprcScroll, lprcClip, hrgnUpdate, lprcUpdate, fuScroll);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxSetCapture(self: *const T, fCapture: BOOL) callconv(.Inline) void {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxSetCapture(@ptrCast(*const ITextHost, self), fCapture);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxSetFocus(self: *const T) callconv(.Inline) void {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxSetFocus(@ptrCast(*const ITextHost, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxSetCursor(self: *const T, hcur: ?HCURSOR, fText: BOOL) callconv(.Inline) void {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxSetCursor(@ptrCast(*const ITextHost, self), hcur, fText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxScreenToClient(self: *const T, lppt: ?*POINT) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxScreenToClient(@ptrCast(*const ITextHost, self), lppt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxClientToScreen(self: *const T, lppt: ?*POINT) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxClientToScreen(@ptrCast(*const ITextHost, self), lppt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxActivate(self: *const T, plOldState: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxActivate(@ptrCast(*const ITextHost, self), plOldState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxDeactivate(self: *const T, lNewState: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxDeactivate(@ptrCast(*const ITextHost, self), lNewState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetClientRect(self: *const T, prc: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetClientRect(@ptrCast(*const ITextHost, self), prc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetViewInset(self: *const T, prc: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetViewInset(@ptrCast(*const ITextHost, self), prc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetCharFormat(self: *const T, ppCF: ?*const ?*CHARFORMATW) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetCharFormat(@ptrCast(*const ITextHost, self), ppCF);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetParaFormat(self: *const T, ppPF: ?*const ?*PARAFORMAT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetParaFormat(@ptrCast(*const ITextHost, self), ppPF);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetSysColor(self: *const T, nIndex: i32) callconv(.Inline) u32 {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetSysColor(@ptrCast(*const ITextHost, self), nIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetBackStyle(self: *const T, pstyle: ?*TXTBACKSTYLE) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetBackStyle(@ptrCast(*const ITextHost, self), pstyle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetMaxLength(self: *const T, plength: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetMaxLength(@ptrCast(*const ITextHost, self), plength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetScrollBars(self: *const T, pdwScrollBar: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetScrollBars(@ptrCast(*const ITextHost, self), pdwScrollBar);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetPasswordChar(self: *const T, pch: ?*i8) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetPasswordChar(@ptrCast(*const ITextHost, self), pch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetAcceleratorPos(self: *const T, pcp: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetAcceleratorPos(@ptrCast(*const ITextHost, self), pcp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetExtent(self: *const T, lpExtent: ?*SIZE) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetExtent(@ptrCast(*const ITextHost, self), lpExtent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_OnTxCharFormatChange(self: *const T, pCF: ?*const CHARFORMATW) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).OnTxCharFormatChange(@ptrCast(*const ITextHost, self), pCF);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_OnTxParaFormatChange(self: *const T, pPF: ?*const PARAFORMAT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).OnTxParaFormatChange(@ptrCast(*const ITextHost, self), pPF);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetPropertyBits(self: *const T, dwMask: u32, pdwBits: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetPropertyBits(@ptrCast(*const ITextHost, self), dwMask, pdwBits);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxNotify(self: *const T, iNotify: u32, pv: ?*c_void) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxNotify(@ptrCast(*const ITextHost, self), iNotify, pv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxImmGetContext(self: *const T) callconv(.Inline) ?HIMC {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxImmGetContext(@ptrCast(*const ITextHost, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxImmReleaseContext(self: *const T, himc: ?HIMC) callconv(.Inline) void {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxImmReleaseContext(@ptrCast(*const ITextHost, self), himc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost_TxGetSelectionBarWidth(self: *const T, lSelBarWidth: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost.VTable, self.vtable).TxGetSelectionBarWidth(@ptrCast(*const ITextHost, self), lSelBarWidth);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
pub const IRicheditWindowlessAccessibility = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
CreateProvider: fn(
self: *const IRicheditWindowlessAccessibility,
pSite: ?*IRawElementProviderWindowlessSite,
ppProvider: ?*?*IRawElementProviderSimple,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRicheditWindowlessAccessibility_CreateProvider(self: *const T, pSite: ?*IRawElementProviderWindowlessSite, ppProvider: ?*?*IRawElementProviderSimple) callconv(.Inline) HRESULT {
return @ptrCast(*const IRicheditWindowlessAccessibility.VTable, self.vtable).CreateProvider(@ptrCast(*const IRicheditWindowlessAccessibility, self), pSite, ppProvider);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
pub const IRichEditUiaInformation = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetBoundaryRectangle: fn(
self: *const IRichEditUiaInformation,
pUiaRect: ?*UiaRect,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsVisible: fn(
self: *const IRichEditUiaInformation,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditUiaInformation_GetBoundaryRectangle(self: *const T, pUiaRect: ?*UiaRect) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditUiaInformation.VTable, self.vtable).GetBoundaryRectangle(@ptrCast(*const IRichEditUiaInformation, self), pUiaRect);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRichEditUiaInformation_IsVisible(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IRichEditUiaInformation.VTable, self.vtable).IsVisible(@ptrCast(*const IRichEditUiaInformation, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
pub const IRicheditUiaOverrides = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetPropertyOverrideValue: fn(
self: *const IRicheditUiaOverrides,
propertyId: i32,
pRetValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IRicheditUiaOverrides_GetPropertyOverrideValue(self: *const T, propertyId: i32, pRetValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IRicheditUiaOverrides.VTable, self.vtable).GetPropertyOverrideValue(@ptrCast(*const IRicheditUiaOverrides, self), propertyId, pRetValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const PCreateTextServices = fn(
punkOuter: ?*IUnknown,
pITextHost: ?*ITextHost,
ppUnk: ?*?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const PShutdownTextServices = fn(
pTextServices: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub const ITextHost2 = extern struct {
pub const VTable = extern struct {
base: ITextHost.VTable,
TxIsDoubleClickPending: fn(
self: *const ITextHost2,
) callconv(@import("std").os.windows.WINAPI) BOOL,
TxGetWindow: fn(
self: *const ITextHost2,
phwnd: ?*?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxSetForegroundWindow: fn(
self: *const ITextHost2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetPalette: fn(
self: *const ITextHost2,
) callconv(@import("std").os.windows.WINAPI) ?HPALETTE,
TxGetEastAsianFlags: fn(
self: *const ITextHost2,
pFlags: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxSetCursor2: fn(
self: *const ITextHost2,
hcur: ?HCURSOR,
bText: BOOL,
) callconv(@import("std").os.windows.WINAPI) ?HCURSOR,
TxFreeTextServicesNotification: fn(
self: *const ITextHost2,
) callconv(@import("std").os.windows.WINAPI) void,
TxGetEditStyle: fn(
self: *const ITextHost2,
dwItem: u32,
pdwData: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetWindowStyles: fn(
self: *const ITextHost2,
pdwStyle: ?*u32,
pdwExStyle: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxShowDropCaret: fn(
self: *const ITextHost2,
fShow: BOOL,
hdc: ?HDC,
prc: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxDestroyCaret: fn(
self: *const ITextHost2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxGetHorzExtent: fn(
self: *const ITextHost2,
plHorzExtent: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextHost.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxIsDoubleClickPending(self: *const T) callconv(.Inline) BOOL {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxIsDoubleClickPending(@ptrCast(*const ITextHost2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxGetWindow(self: *const T, phwnd: ?*?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxGetWindow(@ptrCast(*const ITextHost2, self), phwnd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxSetForegroundWindow(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxSetForegroundWindow(@ptrCast(*const ITextHost2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxGetPalette(self: *const T) callconv(.Inline) ?HPALETTE {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxGetPalette(@ptrCast(*const ITextHost2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxGetEastAsianFlags(self: *const T, pFlags: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxGetEastAsianFlags(@ptrCast(*const ITextHost2, self), pFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxSetCursor2(self: *const T, hcur: ?HCURSOR, bText: BOOL) callconv(.Inline) ?HCURSOR {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxSetCursor2(@ptrCast(*const ITextHost2, self), hcur, bText);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxFreeTextServicesNotification(self: *const T) callconv(.Inline) void {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxFreeTextServicesNotification(@ptrCast(*const ITextHost2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxGetEditStyle(self: *const T, dwItem: u32, pdwData: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxGetEditStyle(@ptrCast(*const ITextHost2, self), dwItem, pdwData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxGetWindowStyles(self: *const T, pdwStyle: ?*u32, pdwExStyle: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxGetWindowStyles(@ptrCast(*const ITextHost2, self), pdwStyle, pdwExStyle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxShowDropCaret(self: *const T, fShow: BOOL, hdc: ?HDC, prc: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxShowDropCaret(@ptrCast(*const ITextHost2, self), fShow, hdc, prc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxDestroyCaret(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxDestroyCaret(@ptrCast(*const ITextHost2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextHost2_TxGetHorzExtent(self: *const T, plHorzExtent: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextHost2.VTable, self.vtable).TxGetHorzExtent(@ptrCast(*const ITextHost2, self), plHorzExtent);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const ITextServices2 = extern struct {
pub const VTable = extern struct {
base: ITextServices.VTable,
TxGetNaturalSize2: fn(
self: *const ITextServices2,
dwAspect: u32,
hdcDraw: ?HDC,
hicTargetDev: ?HDC,
ptd: ?*DVTARGETDEVICE,
dwMode: u32,
psizelExtent: ?*const SIZE,
pwidth: ?*i32,
pheight: ?*i32,
pascent: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TxDrawD2D: fn(
self: *const ITextServices2,
pRenderTarget: ?*ID2D1RenderTarget,
lprcBounds: ?*RECTL,
lprcUpdate: ?*RECT,
lViewId: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace ITextServices.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices2_TxGetNaturalSize2(self: *const T, dwAspect: u32, hdcDraw: ?HDC, hicTargetDev: ?HDC, ptd: ?*DVTARGETDEVICE, dwMode: u32, psizelExtent: ?*const SIZE, pwidth: ?*i32, pheight: ?*i32, pascent: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices2.VTable, self.vtable).TxGetNaturalSize2(@ptrCast(*const ITextServices2, self), dwAspect, hdcDraw, hicTargetDev, ptd, dwMode, psizelExtent, pwidth, pheight, pascent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ITextServices2_TxDrawD2D(self: *const T, pRenderTarget: ?*ID2D1RenderTarget, lprcBounds: ?*RECTL, lprcUpdate: ?*RECT, lViewId: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const ITextServices2.VTable, self.vtable).TxDrawD2D(@ptrCast(*const ITextServices2, self), pRenderTarget, lprcBounds, lprcUpdate, lViewId);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const TA_PROPERTY = enum(i32) {
FLAGS = 0,
TRANSFORMCOUNT = 1,
STAGGERDELAY = 2,
STAGGERDELAYCAP = 3,
STAGGERDELAYFACTOR = 4,
ZORDER = 5,
};
pub const TAP_FLAGS = TA_PROPERTY.FLAGS;
pub const TAP_TRANSFORMCOUNT = TA_PROPERTY.TRANSFORMCOUNT;
pub const TAP_STAGGERDELAY = TA_PROPERTY.STAGGERDELAY;
pub const TAP_STAGGERDELAYCAP = TA_PROPERTY.STAGGERDELAYCAP;
pub const TAP_STAGGERDELAYFACTOR = TA_PROPERTY.STAGGERDELAYFACTOR;
pub const TAP_ZORDER = TA_PROPERTY.ZORDER;
pub const TA_PROPERTY_FLAG = enum(u32) {
NONE = 0,
HASSTAGGER = 1,
ISRTLAWARE = 2,
ALLOWCOLLECTION = 4,
HASBACKGROUND = 8,
HASPERSPECTIVE = 16,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
HASSTAGGER: u1 = 0,
ISRTLAWARE: u1 = 0,
ALLOWCOLLECTION: u1 = 0,
HASBACKGROUND: u1 = 0,
HASPERSPECTIVE: u1 = 0,
}) TA_PROPERTY_FLAG {
return @intToEnum(TA_PROPERTY_FLAG,
(if (o.NONE == 1) @enumToInt(TA_PROPERTY_FLAG.NONE) else 0)
| (if (o.HASSTAGGER == 1) @enumToInt(TA_PROPERTY_FLAG.HASSTAGGER) else 0)
| (if (o.ISRTLAWARE == 1) @enumToInt(TA_PROPERTY_FLAG.ISRTLAWARE) else 0)
| (if (o.ALLOWCOLLECTION == 1) @enumToInt(TA_PROPERTY_FLAG.ALLOWCOLLECTION) else 0)
| (if (o.HASBACKGROUND == 1) @enumToInt(TA_PROPERTY_FLAG.HASBACKGROUND) else 0)
| (if (o.HASPERSPECTIVE == 1) @enumToInt(TA_PROPERTY_FLAG.HASPERSPECTIVE) else 0)
);
}
};
pub const TAPF_NONE = TA_PROPERTY_FLAG.NONE;
pub const TAPF_HASSTAGGER = TA_PROPERTY_FLAG.HASSTAGGER;
pub const TAPF_ISRTLAWARE = TA_PROPERTY_FLAG.ISRTLAWARE;
pub const TAPF_ALLOWCOLLECTION = TA_PROPERTY_FLAG.ALLOWCOLLECTION;
pub const TAPF_HASBACKGROUND = TA_PROPERTY_FLAG.HASBACKGROUND;
pub const TAPF_HASPERSPECTIVE = TA_PROPERTY_FLAG.HASPERSPECTIVE;
pub const TA_TRANSFORM_TYPE = enum(i32) {
TRANSLATE_2D = 0,
SCALE_2D = 1,
OPACITY = 2,
CLIP = 3,
};
pub const TATT_TRANSLATE_2D = TA_TRANSFORM_TYPE.TRANSLATE_2D;
pub const TATT_SCALE_2D = TA_TRANSFORM_TYPE.SCALE_2D;
pub const TATT_OPACITY = TA_TRANSFORM_TYPE.OPACITY;
pub const TATT_CLIP = TA_TRANSFORM_TYPE.CLIP;
pub const TA_TRANSFORM_FLAG = enum(i32) {
NONE = 0,
TARGETVALUES_USER = 1,
HASINITIALVALUES = 2,
HASORIGINVALUES = 4,
};
pub const TATF_NONE = TA_TRANSFORM_FLAG.NONE;
pub const TATF_TARGETVALUES_USER = TA_TRANSFORM_FLAG.TARGETVALUES_USER;
pub const TATF_HASINITIALVALUES = TA_TRANSFORM_FLAG.HASINITIALVALUES;
pub const TATF_HASORIGINVALUES = TA_TRANSFORM_FLAG.HASORIGINVALUES;
pub const TA_TRANSFORM = extern struct {
eTransformType: TA_TRANSFORM_TYPE,
dwTimingFunctionId: u32,
dwStartTime: u32,
dwDurationTime: u32,
eFlags: TA_TRANSFORM_FLAG,
};
pub const TA_TRANSFORM_2D = extern struct {
header: TA_TRANSFORM,
rX: f32,
rY: f32,
rInitialX: f32,
rInitialY: f32,
rOriginX: f32,
rOriginY: f32,
};
pub const TA_TRANSFORM_OPACITY = extern struct {
header: TA_TRANSFORM,
rOpacity: f32,
rInitialOpacity: f32,
};
pub const TA_TRANSFORM_CLIP = extern struct {
header: TA_TRANSFORM,
rLeft: f32,
rTop: f32,
rRight: f32,
rBottom: f32,
rInitialLeft: f32,
rInitialTop: f32,
rInitialRight: f32,
rInitialBottom: f32,
};
pub const TA_TIMINGFUNCTION_TYPE = enum(i32) {
UNDEFINED = 0,
CUBIC_BEZIER = 1,
};
pub const TTFT_UNDEFINED = TA_TIMINGFUNCTION_TYPE.UNDEFINED;
pub const TTFT_CUBIC_BEZIER = TA_TIMINGFUNCTION_TYPE.CUBIC_BEZIER;
pub const TA_TIMINGFUNCTION = extern struct {
eTimingFunctionType: TA_TIMINGFUNCTION_TYPE,
};
pub const TA_CUBIC_BEZIER = extern struct {
header: TA_TIMINGFUNCTION,
rX0: f32,
rY0: f32,
rX1: f32,
rY1: f32,
};
pub const DTBGOPTS = extern struct {
dwSize: u32,
dwFlags: u32,
rcClip: RECT,
};
pub const THEMESIZE = enum(i32) {
MIN = 0,
TRUE = 1,
DRAW = 2,
};
pub const TS_MIN = THEMESIZE.MIN;
pub const TS_TRUE = THEMESIZE.TRUE;
pub const TS_DRAW = THEMESIZE.DRAW;
pub const MARGINS = extern struct {
cxLeftWidth: i32,
cxRightWidth: i32,
cyTopHeight: i32,
cyBottomHeight: i32,
};
pub const INTLIST = extern struct {
iValueCount: i32,
iValues: [402]i32,
};
pub const PROPERTYORIGIN = enum(i32) {
STATE = 0,
PART = 1,
CLASS = 2,
GLOBAL = 3,
NOTFOUND = 4,
};
pub const PO_STATE = PROPERTYORIGIN.STATE;
pub const PO_PART = PROPERTYORIGIN.PART;
pub const PO_CLASS = PROPERTYORIGIN.CLASS;
pub const PO_GLOBAL = PROPERTYORIGIN.GLOBAL;
pub const PO_NOTFOUND = PROPERTYORIGIN.NOTFOUND;
pub const WINDOWTHEMEATTRIBUTETYPE = enum(i32) {
T = 1,
};
pub const WTA_NONCLIENT = WINDOWTHEMEATTRIBUTETYPE.T;
pub const WTA_OPTIONS = extern struct {
dwFlags: u32,
dwMask: u32,
};
pub const DTT_CALLBACK_PROC = fn(
hdc: ?HDC,
pszText: [*:0]u16,
cchText: i32,
prc: ?*RECT,
dwFlags: u32,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const DTTOPTS = extern struct {
dwSize: u32,
dwFlags: u32,
crText: u32,
crBorder: u32,
crShadow: u32,
iTextShadowType: i32,
ptShadowOffset: POINT,
iBorderSize: i32,
iFontPropId: i32,
iColorPropId: i32,
iStateId: i32,
fApplyOverlay: BOOL,
iGlowSize: i32,
pfnDrawTextCallback: ?DTT_CALLBACK_PROC,
lParam: LPARAM,
};
pub const BP_BUFFERFORMAT = enum(i32) {
COMPATIBLEBITMAP = 0,
DIB = 1,
TOPDOWNDIB = 2,
TOPDOWNMONODIB = 3,
};
pub const BPBF_COMPATIBLEBITMAP = BP_BUFFERFORMAT.COMPATIBLEBITMAP;
pub const BPBF_DIB = BP_BUFFERFORMAT.DIB;
pub const BPBF_TOPDOWNDIB = BP_BUFFERFORMAT.TOPDOWNDIB;
pub const BPBF_TOPDOWNMONODIB = BP_BUFFERFORMAT.TOPDOWNMONODIB;
pub const BP_ANIMATIONSTYLE = enum(i32) {
NONE = 0,
LINEAR = 1,
CUBIC = 2,
SINE = 3,
};
pub const BPAS_NONE = BP_ANIMATIONSTYLE.NONE;
pub const BPAS_LINEAR = BP_ANIMATIONSTYLE.LINEAR;
pub const BPAS_CUBIC = BP_ANIMATIONSTYLE.CUBIC;
pub const BPAS_SINE = BP_ANIMATIONSTYLE.SINE;
pub const BP_ANIMATIONPARAMS = extern struct {
cbSize: u32,
dwFlags: u32,
style: BP_ANIMATIONSTYLE,
dwDuration: u32,
};
pub const BP_PAINTPARAMS = extern struct {
cbSize: u32,
dwFlags: BP_PAINTPARAMS_FLAGS,
prcExclude: ?*const RECT,
pBlendFunction: ?*const BLENDFUNCTION,
};
pub const BGTYPE = enum(i32) {
IMAGEFILE = 0,
BORDERFILL = 1,
NONE = 2,
};
pub const BT_IMAGEFILE = BGTYPE.IMAGEFILE;
pub const BT_BORDERFILL = BGTYPE.BORDERFILL;
pub const BT_NONE = BGTYPE.NONE;
pub const IMAGELAYOUT = enum(i32) {
VERTICAL = 0,
HORIZONTAL = 1,
};
pub const IL_VERTICAL = IMAGELAYOUT.VERTICAL;
pub const IL_HORIZONTAL = IMAGELAYOUT.HORIZONTAL;
pub const BORDERTYPE = enum(i32) {
RECT = 0,
ROUNDRECT = 1,
ELLIPSE = 2,
};
pub const BT_RECT = BORDERTYPE.RECT;
pub const BT_ROUNDRECT = BORDERTYPE.ROUNDRECT;
pub const BT_ELLIPSE = BORDERTYPE.ELLIPSE;
pub const FILLTYPE = enum(i32) {
SOLID = 0,
VERTGRADIENT = 1,
HORZGRADIENT = 2,
RADIALGRADIENT = 3,
TILEIMAGE = 4,
};
pub const FT_SOLID = FILLTYPE.SOLID;
pub const FT_VERTGRADIENT = FILLTYPE.VERTGRADIENT;
pub const FT_HORZGRADIENT = FILLTYPE.HORZGRADIENT;
pub const FT_RADIALGRADIENT = FILLTYPE.RADIALGRADIENT;
pub const FT_TILEIMAGE = FILLTYPE.TILEIMAGE;
pub const SIZINGTYPE = enum(i32) {
TRUESIZE = 0,
STRETCH = 1,
TILE = 2,
};
pub const ST_TRUESIZE = SIZINGTYPE.TRUESIZE;
pub const ST_STRETCH = SIZINGTYPE.STRETCH;
pub const ST_TILE = SIZINGTYPE.TILE;
pub const HALIGN = enum(i32) {
LEFT = 0,
CENTER = 1,
RIGHT = 2,
};
pub const HA_LEFT = HALIGN.LEFT;
pub const HA_CENTER = HALIGN.CENTER;
pub const HA_RIGHT = HALIGN.RIGHT;
pub const CONTENTALIGNMENT = enum(i32) {
LEFT = 0,
CENTER = 1,
RIGHT = 2,
};
pub const CA_LEFT = CONTENTALIGNMENT.LEFT;
pub const CA_CENTER = CONTENTALIGNMENT.CENTER;
pub const CA_RIGHT = CONTENTALIGNMENT.RIGHT;
pub const VALIGN = enum(i32) {
TOP = 0,
CENTER = 1,
BOTTOM = 2,
};
pub const VA_TOP = VALIGN.TOP;
pub const VA_CENTER = VALIGN.CENTER;
pub const VA_BOTTOM = VALIGN.BOTTOM;
pub const OFFSETTYPE = enum(i32) {
TOPLEFT = 0,
TOPRIGHT = 1,
TOPMIDDLE = 2,
BOTTOMLEFT = 3,
BOTTOMRIGHT = 4,
BOTTOMMIDDLE = 5,
MIDDLELEFT = 6,
MIDDLERIGHT = 7,
LEFTOFCAPTION = 8,
RIGHTOFCAPTION = 9,
LEFTOFLASTBUTTON = 10,
RIGHTOFLASTBUTTON = 11,
ABOVELASTBUTTON = 12,
BELOWLASTBUTTON = 13,
};
pub const OT_TOPLEFT = OFFSETTYPE.TOPLEFT;
pub const OT_TOPRIGHT = OFFSETTYPE.TOPRIGHT;
pub const OT_TOPMIDDLE = OFFSETTYPE.TOPMIDDLE;
pub const OT_BOTTOMLEFT = OFFSETTYPE.BOTTOMLEFT;
pub const OT_BOTTOMRIGHT = OFFSETTYPE.BOTTOMRIGHT;
pub const OT_BOTTOMMIDDLE = OFFSETTYPE.BOTTOMMIDDLE;
pub const OT_MIDDLELEFT = OFFSETTYPE.MIDDLELEFT;
pub const OT_MIDDLERIGHT = OFFSETTYPE.MIDDLERIGHT;
pub const OT_LEFTOFCAPTION = OFFSETTYPE.LEFTOFCAPTION;
pub const OT_RIGHTOFCAPTION = OFFSETTYPE.RIGHTOFCAPTION;
pub const OT_LEFTOFLASTBUTTON = OFFSETTYPE.LEFTOFLASTBUTTON;
pub const OT_RIGHTOFLASTBUTTON = OFFSETTYPE.RIGHTOFLASTBUTTON;
pub const OT_ABOVELASTBUTTON = OFFSETTYPE.ABOVELASTBUTTON;
pub const OT_BELOWLASTBUTTON = OFFSETTYPE.BELOWLASTBUTTON;
pub const ICONEFFECT = enum(i32) {
NONE = 0,
GLOW = 1,
SHADOW = 2,
PULSE = 3,
ALPHA = 4,
};
pub const ICE_NONE = ICONEFFECT.NONE;
pub const ICE_GLOW = ICONEFFECT.GLOW;
pub const ICE_SHADOW = ICONEFFECT.SHADOW;
pub const ICE_PULSE = ICONEFFECT.PULSE;
pub const ICE_ALPHA = ICONEFFECT.ALPHA;
pub const TEXTSHADOWTYPE = enum(i32) {
NONE = 0,
SINGLE = 1,
CONTINUOUS = 2,
};
pub const TST_NONE = TEXTSHADOWTYPE.NONE;
pub const TST_SINGLE = TEXTSHADOWTYPE.SINGLE;
pub const TST_CONTINUOUS = TEXTSHADOWTYPE.CONTINUOUS;
pub const GLYPHTYPE = enum(i32) {
NONE = 0,
IMAGEGLYPH = 1,
FONTGLYPH = 2,
};
pub const GT_NONE = GLYPHTYPE.NONE;
pub const GT_IMAGEGLYPH = GLYPHTYPE.IMAGEGLYPH;
pub const GT_FONTGLYPH = GLYPHTYPE.FONTGLYPH;
pub const IMAGESELECTTYPE = enum(i32) {
NONE = 0,
SIZE = 1,
DPI = 2,
};
pub const IST_NONE = IMAGESELECTTYPE.NONE;
pub const IST_SIZE = IMAGESELECTTYPE.SIZE;
pub const IST_DPI = IMAGESELECTTYPE.DPI;
pub const TRUESIZESCALINGTYPE = enum(i32) {
NONE = 0,
SIZE = 1,
DPI = 2,
};
pub const TSST_NONE = TRUESIZESCALINGTYPE.NONE;
pub const TSST_SIZE = TRUESIZESCALINGTYPE.SIZE;
pub const TSST_DPI = TRUESIZESCALINGTYPE.DPI;
pub const GLYPHFONTSIZINGTYPE = enum(i32) {
NONE = 0,
SIZE = 1,
DPI = 2,
};
pub const GFST_NONE = GLYPHFONTSIZINGTYPE.NONE;
pub const GFST_SIZE = GLYPHFONTSIZINGTYPE.SIZE;
pub const GFST_DPI = GLYPHFONTSIZINGTYPE.DPI;
pub const LINKPARTS = enum(i32) {
K = 1,
};
pub const LP_HYPERLINK = LINKPARTS.K;
pub const HYPERLINKSTATES = enum(i32) {
NORMALTEXT = 1,
LINKTEXT = 2,
};
pub const HLS_NORMALTEXT = HYPERLINKSTATES.NORMALTEXT;
pub const HLS_LINKTEXT = HYPERLINKSTATES.LINKTEXT;
pub const EMPTYMARKUPPARTS = enum(i32) {
T = 1,
};
pub const EMP_MARKUPTEXT = EMPTYMARKUPPARTS.T;
pub const MARKUPTEXTSTATES = enum(i32) {
NORMALTEXT = 1,
LINKTEXT = 2,
};
pub const EMT_NORMALTEXT = MARKUPTEXTSTATES.NORMALTEXT;
pub const EMT_LINKTEXT = MARKUPTEXTSTATES.LINKTEXT;
pub const STATICPARTS = enum(i32) {
T = 1,
};
pub const STAT_TEXT = STATICPARTS.T;
pub const PAGEPARTS = enum(i32) {
UP = 1,
DOWN = 2,
UPHORZ = 3,
DOWNHORZ = 4,
};
pub const PGRP_UP = PAGEPARTS.UP;
pub const PGRP_DOWN = PAGEPARTS.DOWN;
pub const PGRP_UPHORZ = PAGEPARTS.UPHORZ;
pub const PGRP_DOWNHORZ = PAGEPARTS.DOWNHORZ;
pub const MONTHCALPARTS = enum(i32) {
BACKGROUND = 1,
BORDERS = 2,
GRIDBACKGROUND = 3,
COLHEADERSPLITTER = 4,
GRIDCELLBACKGROUND = 5,
GRIDCELL = 6,
GRIDCELLUPPER = 7,
TRAILINGGRIDCELL = 8,
TRAILINGGRIDCELLUPPER = 9,
NAVNEXT = 10,
NAVPREV = 11,
};
pub const MC_BACKGROUND = MONTHCALPARTS.BACKGROUND;
pub const MC_BORDERS = MONTHCALPARTS.BORDERS;
pub const MC_GRIDBACKGROUND = MONTHCALPARTS.GRIDBACKGROUND;
pub const MC_COLHEADERSPLITTER = MONTHCALPARTS.COLHEADERSPLITTER;
pub const MC_GRIDCELLBACKGROUND = MONTHCALPARTS.GRIDCELLBACKGROUND;
pub const MC_GRIDCELL = MONTHCALPARTS.GRIDCELL;
pub const MC_GRIDCELLUPPER = MONTHCALPARTS.GRIDCELLUPPER;
pub const MC_TRAILINGGRIDCELL = MONTHCALPARTS.TRAILINGGRIDCELL;
pub const MC_TRAILINGGRIDCELLUPPER = MONTHCALPARTS.TRAILINGGRIDCELLUPPER;
pub const MC_NAVNEXT = MONTHCALPARTS.NAVNEXT;
pub const MC_NAVPREV = MONTHCALPARTS.NAVPREV;
pub const GRIDCELLBACKGROUNDSTATES = enum(i32) {
SELECTED = 1,
HOT = 2,
SELECTEDHOT = 3,
SELECTEDNOTFOCUSED = 4,
TODAY = 5,
TODAYSELECTED = 6,
};
pub const MCGCB_SELECTED = GRIDCELLBACKGROUNDSTATES.SELECTED;
pub const MCGCB_HOT = GRIDCELLBACKGROUNDSTATES.HOT;
pub const MCGCB_SELECTEDHOT = GRIDCELLBACKGROUNDSTATES.SELECTEDHOT;
pub const MCGCB_SELECTEDNOTFOCUSED = GRIDCELLBACKGROUNDSTATES.SELECTEDNOTFOCUSED;
pub const MCGCB_TODAY = GRIDCELLBACKGROUNDSTATES.TODAY;
pub const MCGCB_TODAYSELECTED = GRIDCELLBACKGROUNDSTATES.TODAYSELECTED;
pub const GRIDCELLSTATES = enum(i32) {
HOT = 1,
HASSTATE = 2,
HASSTATEHOT = 3,
TODAY = 4,
TODAYSELECTED = 5,
SELECTED = 6,
SELECTEDHOT = 7,
};
pub const MCGC_HOT = GRIDCELLSTATES.HOT;
pub const MCGC_HASSTATE = GRIDCELLSTATES.HASSTATE;
pub const MCGC_HASSTATEHOT = GRIDCELLSTATES.HASSTATEHOT;
pub const MCGC_TODAY = GRIDCELLSTATES.TODAY;
pub const MCGC_TODAYSELECTED = GRIDCELLSTATES.TODAYSELECTED;
pub const MCGC_SELECTED = GRIDCELLSTATES.SELECTED;
pub const MCGC_SELECTEDHOT = GRIDCELLSTATES.SELECTEDHOT;
pub const GRIDCELLUPPERSTATES = enum(i32) {
HOT = 1,
HASSTATE = 2,
HASSTATEHOT = 3,
SELECTED = 4,
SELECTEDHOT = 5,
};
pub const MCGCU_HOT = GRIDCELLUPPERSTATES.HOT;
pub const MCGCU_HASSTATE = GRIDCELLUPPERSTATES.HASSTATE;
pub const MCGCU_HASSTATEHOT = GRIDCELLUPPERSTATES.HASSTATEHOT;
pub const MCGCU_SELECTED = GRIDCELLUPPERSTATES.SELECTED;
pub const MCGCU_SELECTEDHOT = GRIDCELLUPPERSTATES.SELECTEDHOT;
pub const TRAILINGGRIDCELLSTATES = enum(i32) {
HOT = 1,
HASSTATE = 2,
HASSTATEHOT = 3,
TODAY = 4,
TODAYSELECTED = 5,
SELECTED = 6,
SELECTEDHOT = 7,
};
pub const MCTGC_HOT = TRAILINGGRIDCELLSTATES.HOT;
pub const MCTGC_HASSTATE = TRAILINGGRIDCELLSTATES.HASSTATE;
pub const MCTGC_HASSTATEHOT = TRAILINGGRIDCELLSTATES.HASSTATEHOT;
pub const MCTGC_TODAY = TRAILINGGRIDCELLSTATES.TODAY;
pub const MCTGC_TODAYSELECTED = TRAILINGGRIDCELLSTATES.TODAYSELECTED;
pub const MCTGC_SELECTED = TRAILINGGRIDCELLSTATES.SELECTED;
pub const MCTGC_SELECTEDHOT = TRAILINGGRIDCELLSTATES.SELECTEDHOT;
pub const TRAILINGGRIDCELLUPPERSTATES = enum(i32) {
HOT = 1,
HASSTATE = 2,
HASSTATEHOT = 3,
SELECTED = 4,
SELECTEDHOT = 5,
};
pub const MCTGCU_HOT = TRAILINGGRIDCELLUPPERSTATES.HOT;
pub const MCTGCU_HASSTATE = TRAILINGGRIDCELLUPPERSTATES.HASSTATE;
pub const MCTGCU_HASSTATEHOT = TRAILINGGRIDCELLUPPERSTATES.HASSTATEHOT;
pub const MCTGCU_SELECTED = TRAILINGGRIDCELLUPPERSTATES.SELECTED;
pub const MCTGCU_SELECTEDHOT = TRAILINGGRIDCELLUPPERSTATES.SELECTEDHOT;
pub const NAVNEXTSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
PRESSED = 3,
DISABLED = 4,
};
pub const MCNN_NORMAL = NAVNEXTSTATES.NORMAL;
pub const MCNN_HOT = NAVNEXTSTATES.HOT;
pub const MCNN_PRESSED = NAVNEXTSTATES.PRESSED;
pub const MCNN_DISABLED = NAVNEXTSTATES.DISABLED;
pub const NAVPREVSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
PRESSED = 3,
DISABLED = 4,
};
pub const MCNP_NORMAL = NAVPREVSTATES.NORMAL;
pub const MCNP_HOT = NAVPREVSTATES.HOT;
pub const MCNP_PRESSED = NAVPREVSTATES.PRESSED;
pub const MCNP_DISABLED = NAVPREVSTATES.DISABLED;
pub const CLOCKPARTS = enum(i32) {
E = 1,
};
pub const CLP_TIME = CLOCKPARTS.E;
pub const CLOCKSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
PRESSED = 3,
};
pub const CLS_NORMAL = CLOCKSTATES.NORMAL;
pub const CLS_HOT = CLOCKSTATES.HOT;
pub const CLS_PRESSED = CLOCKSTATES.PRESSED;
pub const TRAYNOTIFYPARTS = enum(i32) {
BACKGROUND = 1,
ANIMBACKGROUND = 2,
};
pub const TNP_BACKGROUND = TRAYNOTIFYPARTS.BACKGROUND;
pub const TNP_ANIMBACKGROUND = TRAYNOTIFYPARTS.ANIMBACKGROUND;
pub const TASKBARPARTS = enum(i32) {
BACKGROUNDBOTTOM = 1,
BACKGROUNDRIGHT = 2,
BACKGROUNDTOP = 3,
BACKGROUNDLEFT = 4,
SIZINGBARBOTTOM = 5,
SIZINGBARRIGHT = 6,
SIZINGBARTOP = 7,
SIZINGBARLEFT = 8,
};
pub const TBP_BACKGROUNDBOTTOM = TASKBARPARTS.BACKGROUNDBOTTOM;
pub const TBP_BACKGROUNDRIGHT = TASKBARPARTS.BACKGROUNDRIGHT;
pub const TBP_BACKGROUNDTOP = TASKBARPARTS.BACKGROUNDTOP;
pub const TBP_BACKGROUNDLEFT = TASKBARPARTS.BACKGROUNDLEFT;
pub const TBP_SIZINGBARBOTTOM = TASKBARPARTS.SIZINGBARBOTTOM;
pub const TBP_SIZINGBARRIGHT = TASKBARPARTS.SIZINGBARRIGHT;
pub const TBP_SIZINGBARTOP = TASKBARPARTS.SIZINGBARTOP;
pub const TBP_SIZINGBARLEFT = TASKBARPARTS.SIZINGBARLEFT;
pub const TASKBANDPARTS = enum(i32) {
GROUPCOUNT = 1,
FLASHBUTTON = 2,
FLASHBUTTONGROUPMENU = 3,
};
pub const TDP_GROUPCOUNT = TASKBANDPARTS.GROUPCOUNT;
pub const TDP_FLASHBUTTON = TASKBANDPARTS.FLASHBUTTON;
pub const TDP_FLASHBUTTONGROUPMENU = TASKBANDPARTS.FLASHBUTTONGROUPMENU;
pub const STARTPANELPARTS = enum(i32) {
USERPANE = 1,
MOREPROGRAMS = 2,
MOREPROGRAMSARROW = 3,
PROGLIST = 4,
PROGLISTSEPARATOR = 5,
PLACESLIST = 6,
PLACESLISTSEPARATOR = 7,
LOGOFF = 8,
LOGOFFBUTTONS = 9,
USERPICTURE = 10,
PREVIEW = 11,
MOREPROGRAMSTAB = 12,
NSCHOST = 13,
SOFTWAREEXPLORER = 14,
OPENBOX = 15,
SEARCHVIEW = 16,
MOREPROGRAMSARROWBACK = 17,
TOPMATCH = 18,
LOGOFFSPLITBUTTONDROPDOWN = 19,
};
pub const SPP_USERPANE = STARTPANELPARTS.USERPANE;
pub const SPP_MOREPROGRAMS = STARTPANELPARTS.MOREPROGRAMS;
pub const SPP_MOREPROGRAMSARROW = STARTPANELPARTS.MOREPROGRAMSARROW;
pub const SPP_PROGLIST = STARTPANELPARTS.PROGLIST;
pub const SPP_PROGLISTSEPARATOR = STARTPANELPARTS.PROGLISTSEPARATOR;
pub const SPP_PLACESLIST = STARTPANELPARTS.PLACESLIST;
pub const SPP_PLACESLISTSEPARATOR = STARTPANELPARTS.PLACESLISTSEPARATOR;
pub const SPP_LOGOFF = STARTPANELPARTS.LOGOFF;
pub const SPP_LOGOFFBUTTONS = STARTPANELPARTS.LOGOFFBUTTONS;
pub const SPP_USERPICTURE = STARTPANELPARTS.USERPICTURE;
pub const SPP_PREVIEW = STARTPANELPARTS.PREVIEW;
pub const SPP_MOREPROGRAMSTAB = STARTPANELPARTS.MOREPROGRAMSTAB;
pub const SPP_NSCHOST = STARTPANELPARTS.NSCHOST;
pub const SPP_SOFTWAREEXPLORER = STARTPANELPARTS.SOFTWAREEXPLORER;
pub const SPP_OPENBOX = STARTPANELPARTS.OPENBOX;
pub const SPP_SEARCHVIEW = STARTPANELPARTS.SEARCHVIEW;
pub const SPP_MOREPROGRAMSARROWBACK = STARTPANELPARTS.MOREPROGRAMSARROWBACK;
pub const SPP_TOPMATCH = STARTPANELPARTS.TOPMATCH;
pub const SPP_LOGOFFSPLITBUTTONDROPDOWN = STARTPANELPARTS.LOGOFFSPLITBUTTONDROPDOWN;
pub const MOREPROGRAMSTABSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
SELECTED = 3,
DISABLED = 4,
FOCUSED = 5,
};
pub const SPMPT_NORMAL = MOREPROGRAMSTABSTATES.NORMAL;
pub const SPMPT_HOT = MOREPROGRAMSTABSTATES.HOT;
pub const SPMPT_SELECTED = MOREPROGRAMSTABSTATES.SELECTED;
pub const SPMPT_DISABLED = MOREPROGRAMSTABSTATES.DISABLED;
pub const SPMPT_FOCUSED = MOREPROGRAMSTABSTATES.FOCUSED;
pub const SOFTWAREEXPLORERSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
SELECTED = 3,
DISABLED = 4,
FOCUSED = 5,
};
pub const SPSE_NORMAL = SOFTWAREEXPLORERSTATES.NORMAL;
pub const SPSE_HOT = SOFTWAREEXPLORERSTATES.HOT;
pub const SPSE_SELECTED = SOFTWAREEXPLORERSTATES.SELECTED;
pub const SPSE_DISABLED = SOFTWAREEXPLORERSTATES.DISABLED;
pub const SPSE_FOCUSED = SOFTWAREEXPLORERSTATES.FOCUSED;
pub const OPENBOXSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
SELECTED = 3,
DISABLED = 4,
FOCUSED = 5,
};
pub const SPOB_NORMAL = OPENBOXSTATES.NORMAL;
pub const SPOB_HOT = OPENBOXSTATES.HOT;
pub const SPOB_SELECTED = OPENBOXSTATES.SELECTED;
pub const SPOB_DISABLED = OPENBOXSTATES.DISABLED;
pub const SPOB_FOCUSED = OPENBOXSTATES.FOCUSED;
pub const MOREPROGRAMSARROWSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
PRESSED = 3,
};
pub const SPS_NORMAL = MOREPROGRAMSARROWSTATES.NORMAL;
pub const SPS_HOT = MOREPROGRAMSARROWSTATES.HOT;
pub const SPS_PRESSED = MOREPROGRAMSARROWSTATES.PRESSED;
pub const MOREPROGRAMSARROWBACKSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
PRESSED = 3,
};
pub const SPSB_NORMAL = MOREPROGRAMSARROWBACKSTATES.NORMAL;
pub const SPSB_HOT = MOREPROGRAMSARROWBACKSTATES.HOT;
pub const SPSB_PRESSED = MOREPROGRAMSARROWBACKSTATES.PRESSED;
pub const LOGOFFBUTTONSSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
PRESSED = 3,
};
pub const SPLS_NORMAL = LOGOFFBUTTONSSTATES.NORMAL;
pub const SPLS_HOT = LOGOFFBUTTONSSTATES.HOT;
pub const SPLS_PRESSED = LOGOFFBUTTONSSTATES.PRESSED;
pub const MENUBANDPARTS = enum(i32) {
NEWAPPBUTTON = 1,
SEPERATOR = 2,
};
pub const MDP_NEWAPPBUTTON = MENUBANDPARTS.NEWAPPBUTTON;
pub const MDP_SEPERATOR = MENUBANDPARTS.SEPERATOR;
pub const MENUBANDSTATES = enum(i32) {
NORMAL = 1,
HOT = 2,
PRESSED = 3,
DISABLED = 4,
CHECKED = 5,
HOTCHECKED = 6,
};
pub const MDS_NORMAL = MENUBANDSTATES.NORMAL;
pub const MDS_HOT = MENUBANDSTATES.HOT;
pub const MDS_PRESSED = MENUBANDSTATES.PRESSED;
pub const MDS_DISABLED = MENUBANDSTATES.DISABLED;
pub const MDS_CHECKED = MENUBANDSTATES.CHECKED;
pub const MDS_HOTCHECKED = MENUBANDSTATES.HOTCHECKED;
pub const EDITWORDBREAKPROCA = fn(
lpch: ?PSTR,
ichCurrent: i32,
cch: i32,
code: WORD_BREAK_ACTION,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const EDITWORDBREAKPROCW = fn(
lpch: ?PWSTR,
ichCurrent: i32,
cch: i32,
code: WORD_BREAK_ACTION,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const NMHDR = extern struct {
hwndFrom: ?HWND,
idFrom: usize,
code: u32,
};
pub const MEASUREITEMSTRUCT = extern struct {
CtlType: u32,
CtlID: u32,
itemID: u32,
itemWidth: u32,
itemHeight: u32,
itemData: usize,
};
pub const DRAWITEMSTRUCT = extern struct {
CtlType: DRAWITEMSTRUCT_CTL_TYPE,
CtlID: u32,
itemID: u32,
itemAction: u32,
itemState: u32,
hwndItem: ?HWND,
hDC: ?HDC,
rcItem: RECT,
itemData: usize,
};
pub const DELETEITEMSTRUCT = extern struct {
CtlType: DRAWITEMSTRUCT_CTL_TYPE,
CtlID: u32,
itemID: u32,
hwndItem: ?HWND,
itemData: usize,
};
pub const COMPAREITEMSTRUCT = extern struct {
CtlType: u32,
CtlID: u32,
hwndItem: ?HWND,
itemID1: u32,
itemData1: usize,
itemID2: u32,
itemData2: usize,
dwLocaleId: u32,
};
pub const POINTER_FEEDBACK_MODE = enum(i32) {
DEFAULT = 1,
INDIRECT = 2,
NONE = 3,
};
pub const POINTER_FEEDBACK_DEFAULT = POINTER_FEEDBACK_MODE.DEFAULT;
pub const POINTER_FEEDBACK_INDIRECT = POINTER_FEEDBACK_MODE.INDIRECT;
pub const POINTER_FEEDBACK_NONE = POINTER_FEEDBACK_MODE.NONE;
pub const USAGE_PROPERTIES = extern struct {
level: u16,
page: u16,
usage: u16,
logicalMinimum: i32,
logicalMaximum: i32,
unit: u16,
exponent: u16,
count: u8,
physicalMinimum: i32,
physicalMaximum: i32,
};
pub const POINTER_TYPE_INFO = extern struct {
type: POINTER_INPUT_TYPE,
Anonymous: extern union {
touchInfo: POINTER_TOUCH_INFO,
penInfo: POINTER_PEN_INFO,
},
};
pub const INPUT_INJECTION_VALUE = extern struct {
page: u16,
usage: u16,
value: i32,
index: u16,
};
pub const TOUCH_HIT_TESTING_PROXIMITY_EVALUATION = extern struct {
score: u16,
adjustedPoint: POINT,
};
pub const TOUCH_HIT_TESTING_INPUT = extern struct {
pointerId: u32,
point: POINT,
boundingBox: RECT,
nonOccludedBoundingBox: RECT,
orientation: u32,
};
pub const FEEDBACK_TYPE = enum(i32) {
TOUCH_CONTACTVISUALIZATION = 1,
PEN_BARRELVISUALIZATION = 2,
PEN_TAP = 3,
PEN_DOUBLETAP = 4,
PEN_PRESSANDHOLD = 5,
PEN_RIGHTTAP = 6,
TOUCH_TAP = 7,
TOUCH_DOUBLETAP = 8,
TOUCH_PRESSANDHOLD = 9,
TOUCH_RIGHTTAP = 10,
GESTURE_PRESSANDTAP = 11,
MAX = -1,
};
pub const FEEDBACK_TOUCH_CONTACTVISUALIZATION = FEEDBACK_TYPE.TOUCH_CONTACTVISUALIZATION;
pub const FEEDBACK_PEN_BARRELVISUALIZATION = FEEDBACK_TYPE.PEN_BARRELVISUALIZATION;
pub const FEEDBACK_PEN_TAP = FEEDBACK_TYPE.PEN_TAP;
pub const FEEDBACK_PEN_DOUBLETAP = FEEDBACK_TYPE.PEN_DOUBLETAP;
pub const FEEDBACK_PEN_PRESSANDHOLD = FEEDBACK_TYPE.PEN_PRESSANDHOLD;
pub const FEEDBACK_PEN_RIGHTTAP = FEEDBACK_TYPE.PEN_RIGHTTAP;
pub const FEEDBACK_TOUCH_TAP = FEEDBACK_TYPE.TOUCH_TAP;
pub const FEEDBACK_TOUCH_DOUBLETAP = FEEDBACK_TYPE.TOUCH_DOUBLETAP;
pub const FEEDBACK_TOUCH_PRESSANDHOLD = FEEDBACK_TYPE.TOUCH_PRESSANDHOLD;
pub const FEEDBACK_TOUCH_RIGHTTAP = FEEDBACK_TYPE.TOUCH_RIGHTTAP;
pub const FEEDBACK_GESTURE_PRESSANDTAP = FEEDBACK_TYPE.GESTURE_PRESSANDTAP;
pub const FEEDBACK_MAX = FEEDBACK_TYPE.MAX;
pub const SCROLLINFO = extern struct {
cbSize: u32,
fMask: SCROLLINFO_MASK,
nMin: i32,
nMax: i32,
nPage: u32,
nPos: i32,
nTrackPos: i32,
};
pub const SCROLLBARINFO = extern struct {
cbSize: u32,
rcScrollBar: RECT,
dxyLineButton: i32,
xyThumbTop: i32,
xyThumbBottom: i32,
reserved: i32,
rgstate: [6]u32,
};
pub const COMBOBOXINFO = extern struct {
cbSize: u32,
rcItem: RECT,
rcButton: RECT,
stateButton: COMBOBOXINFO_BUTTON_STATE,
hwndCombo: ?HWND,
hwndItem: ?HWND,
hwndList: ?HWND,
};
pub const POINTER_DEVICE_TYPE = enum(i32) {
INTEGRATED_PEN = 1,
EXTERNAL_PEN = 2,
TOUCH = 3,
TOUCH_PAD = 4,
MAX = -1,
};
pub const POINTER_DEVICE_TYPE_INTEGRATED_PEN = POINTER_DEVICE_TYPE.INTEGRATED_PEN;
pub const POINTER_DEVICE_TYPE_EXTERNAL_PEN = POINTER_DEVICE_TYPE.EXTERNAL_PEN;
pub const POINTER_DEVICE_TYPE_TOUCH = POINTER_DEVICE_TYPE.TOUCH;
pub const POINTER_DEVICE_TYPE_TOUCH_PAD = POINTER_DEVICE_TYPE.TOUCH_PAD;
pub const POINTER_DEVICE_TYPE_MAX = POINTER_DEVICE_TYPE.MAX;
pub const POINTER_DEVICE_INFO = extern struct {
displayOrientation: u32,
device: ?HANDLE,
pointerDeviceType: POINTER_DEVICE_TYPE,
monitor: ?HMONITOR,
startingCursorId: u32,
maxActiveContacts: u16,
productString: [520]u16,
};
pub const POINTER_DEVICE_PROPERTY = extern struct {
logicalMin: i32,
logicalMax: i32,
physicalMin: i32,
physicalMax: i32,
unit: u32,
unitExponent: u32,
usagePageId: u16,
usageId: u16,
};
pub const POINTER_DEVICE_CURSOR_TYPE = enum(i32) {
UNKNOWN = 0,
TIP = 1,
ERASER = 2,
MAX = -1,
};
pub const POINTER_DEVICE_CURSOR_TYPE_UNKNOWN = POINTER_DEVICE_CURSOR_TYPE.UNKNOWN;
pub const POINTER_DEVICE_CURSOR_TYPE_TIP = POINTER_DEVICE_CURSOR_TYPE.TIP;
pub const POINTER_DEVICE_CURSOR_TYPE_ERASER = POINTER_DEVICE_CURSOR_TYPE.ERASER;
pub const POINTER_DEVICE_CURSOR_TYPE_MAX = POINTER_DEVICE_CURSOR_TYPE.MAX;
pub const POINTER_DEVICE_CURSOR_INFO = extern struct {
cursorId: u32,
cursor: POINTER_DEVICE_CURSOR_TYPE,
};
pub const INPUT_MESSAGE_DEVICE_TYPE = enum(i32) {
UNAVAILABLE = 0,
KEYBOARD = 1,
MOUSE = 2,
TOUCH = 4,
PEN = 8,
TOUCHPAD = 16,
};
pub const IMDT_UNAVAILABLE = INPUT_MESSAGE_DEVICE_TYPE.UNAVAILABLE;
pub const IMDT_KEYBOARD = INPUT_MESSAGE_DEVICE_TYPE.KEYBOARD;
pub const IMDT_MOUSE = INPUT_MESSAGE_DEVICE_TYPE.MOUSE;
pub const IMDT_TOUCH = INPUT_MESSAGE_DEVICE_TYPE.TOUCH;
pub const IMDT_PEN = INPUT_MESSAGE_DEVICE_TYPE.PEN;
pub const IMDT_TOUCHPAD = INPUT_MESSAGE_DEVICE_TYPE.TOUCHPAD;
pub const INPUT_MESSAGE_ORIGIN_ID = enum(i32) {
UNAVAILABLE = 0,
HARDWARE = 1,
INJECTED = 2,
SYSTEM = 4,
};
pub const IMO_UNAVAILABLE = INPUT_MESSAGE_ORIGIN_ID.UNAVAILABLE;
pub const IMO_HARDWARE = INPUT_MESSAGE_ORIGIN_ID.HARDWARE;
pub const IMO_INJECTED = INPUT_MESSAGE_ORIGIN_ID.INJECTED;
pub const IMO_SYSTEM = INPUT_MESSAGE_ORIGIN_ID.SYSTEM;
pub const INPUT_MESSAGE_SOURCE = extern struct {
deviceType: INPUT_MESSAGE_DEVICE_TYPE,
originId: INPUT_MESSAGE_ORIGIN_ID,
};
pub const TBBUTTON = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
iBitmap: i32,
idCommand: i32,
fsState: u8,
fsStyle: u8,
bReserved: [6]u8,
dwData: usize,
iString: isize,
},
.X86 => extern struct {
iBitmap: i32,
idCommand: i32,
fsState: u8,
fsStyle: u8,
bReserved: [2]u8,
dwData: usize,
iString: isize,
},
};
pub const RICHEDIT_IMAGE_PARAMETERS = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
xWidth: i32,
yHeight: i32,
Ascent: i32,
Type: TEXT_ALIGN_OPTIONS,
pwszAlternateText: ?[*:0]const u16,
pIStream: ?*IStream,
},
.X86 => extern struct {
xWidth: i32,
yHeight: i32,
Ascent: i32,
Type: TEXT_ALIGN_OPTIONS,
pwszAlternateText: ?[*:0]const u16,
pIStream: ?*IStream,
},
};
pub const ENDCOMPOSITIONNOTIFY = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
dwCode: ENDCOMPOSITIONNOTIFY_CODE,
},
.X86 => extern struct {
nmhdr: NMHDR,
dwCode: ENDCOMPOSITIONNOTIFY_CODE,
},
};
pub const TEXTRANGEA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
chrg: CHARRANGE,
lpstrText: ?PSTR,
},
.X86 => extern struct {
chrg: CHARRANGE,
lpstrText: ?PSTR,
},
};
pub const TEXTRANGEW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
chrg: CHARRANGE,
lpstrText: ?PWSTR,
},
.X86 => extern struct {
chrg: CHARRANGE,
lpstrText: ?PWSTR,
},
};
pub const EDITSTREAM = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
dwCookie: usize,
dwError: u32,
pfnCallback: ?EDITSTREAMCALLBACK,
},
.X86 => extern struct {
dwCookie: usize,
dwError: u32,
pfnCallback: ?EDITSTREAMCALLBACK,
},
};
pub const FINDTEXTA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
chrg: CHARRANGE,
lpstrText: ?[*:0]const u8,
},
.X86 => extern struct {
chrg: CHARRANGE,
lpstrText: ?[*:0]const u8,
},
};
pub const FINDTEXTW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
chrg: CHARRANGE,
lpstrText: ?[*:0]const u16,
},
.X86 => extern struct {
chrg: CHARRANGE,
lpstrText: ?[*:0]const u16,
},
};
pub const FINDTEXTEXA = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
chrg: CHARRANGE,
lpstrText: ?[*:0]const u8,
chrgText: CHARRANGE,
},
.X86 => extern struct {
chrg: CHARRANGE,
lpstrText: ?[*:0]const u8,
chrgText: CHARRANGE,
},
};
pub const FINDTEXTEXW = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
chrg: CHARRANGE,
lpstrText: ?[*:0]const u16,
chrgText: CHARRANGE,
},
.X86 => extern struct {
chrg: CHARRANGE,
lpstrText: ?[*:0]const u16,
chrgText: CHARRANGE,
},
};
pub const FORMATRANGE = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
hdc: ?HDC,
hdcTarget: ?HDC,
rc: RECT,
rcPage: RECT,
chrg: CHARRANGE,
},
.X86 => extern struct {
hdc: ?HDC,
hdcTarget: ?HDC,
rc: RECT,
rcPage: RECT,
chrg: CHARRANGE,
},
};
pub const MSGFILTER = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
msg: u32,
wParam: WPARAM,
lParam: LPARAM,
},
.X86 => extern struct {
nmhdr: NMHDR,
msg: u32,
wParam: WPARAM,
lParam: LPARAM,
},
};
pub const REQRESIZE = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
rc: RECT,
},
.X86 => extern struct {
nmhdr: NMHDR,
rc: RECT,
},
};
pub const SELCHANGE = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
chrg: CHARRANGE,
seltyp: RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE,
},
.X86 => extern struct {
nmhdr: NMHDR,
chrg: CHARRANGE,
seltyp: RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE,
},
};
pub const _grouptypingchange = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
fGroupTyping: BOOL,
},
.X86 => extern struct {
nmhdr: NMHDR,
fGroupTyping: BOOL,
},
};
pub const CLIPBOARDFORMAT = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
cf: u16,
},
.X86 => extern struct {
nmhdr: NMHDR,
cf: u16,
},
};
pub const GETCONTEXTMENUEX = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
chrg: CHARRANGE,
dwFlags: u32,
pt: POINT,
pvReserved: ?*c_void,
},
.X86 => extern struct {
chrg: CHARRANGE,
dwFlags: u32,
pt: POINT,
pvReserved: ?*c_void,
},
};
pub const ENDROPFILES = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
hDrop: ?HANDLE,
cp: i32,
fProtected: BOOL,
},
.X86 => extern struct {
nmhdr: NMHDR,
hDrop: ?HANDLE,
cp: i32,
fProtected: BOOL,
},
};
pub const ENPROTECTED = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
msg: u32,
wParam: WPARAM,
lParam: LPARAM,
chrg: CHARRANGE,
},
.X86 => extern struct {
nmhdr: NMHDR,
msg: u32,
wParam: WPARAM,
lParam: LPARAM,
chrg: CHARRANGE,
},
};
pub const ENSAVECLIPBOARD = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
cObjectCount: i32,
cch: i32,
},
.X86 => extern struct {
nmhdr: NMHDR,
cObjectCount: i32,
cch: i32,
},
};
pub const ENOLEOPFAILED = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
iob: i32,
lOper: i32,
hr: HRESULT,
},
.X86 => extern struct {
nmhdr: NMHDR,
iob: i32,
lOper: i32,
hr: HRESULT,
},
};
pub const OBJECTPOSITIONS = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
cObjectCount: i32,
pcpPositions: ?*i32,
},
.X86 => extern struct {
nmhdr: NMHDR,
cObjectCount: i32,
pcpPositions: ?*i32,
},
};
pub const ENLINK = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
msg: u32,
wParam: WPARAM,
lParam: LPARAM,
chrg: CHARRANGE,
},
.X86 => extern struct {
nmhdr: NMHDR,
msg: u32,
wParam: WPARAM,
lParam: LPARAM,
chrg: CHARRANGE,
},
};
pub const ENLOWFIRTF = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
szControl: ?PSTR,
},
.X86 => extern struct {
nmhdr: NMHDR,
szControl: ?PSTR,
},
};
pub const ENCORRECTTEXT = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
nmhdr: NMHDR,
chrg: CHARRANGE,
seltyp: RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE,
},
.X86 => extern struct {
nmhdr: NMHDR,
chrg: CHARRANGE,
seltyp: RICH_EDIT_GET_CONTEXT_MENU_SEL_TYPE,
},
};
pub const PUNCTUATION = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
iSize: u32,
szPunctuation: ?PSTR,
},
.X86 => extern struct {
iSize: u32,
szPunctuation: ?PSTR,
},
};
pub const REPASTESPECIAL = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
dwAspect: DVASPECT,
dwParam: usize,
},
.X86 => extern struct {
dwAspect: DVASPECT,
dwParam: usize,
},
};
pub const GETTEXTEX = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
cb: u32,
flags: GETTEXTEX_FLAGS,
codepage: u32,
lpDefaultChar: ?[*:0]const u8,
lpUsedDefChar: ?*i32,
},
.X86 => extern struct {
cb: u32,
flags: GETTEXTEX_FLAGS,
codepage: u32,
lpDefaultChar: ?[*:0]const u8,
lpUsedDefChar: ?*i32,
},
};
pub const HYPHENATEINFO = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
// WARNING: unable to add field alignment because it's causing a compiler bug
cbSize: i16,
dxHyphenateZone: i16,
pfnHyphenate: isize,
},
.X86 => extern struct {
cbSize: i16,
dxHyphenateZone: i16,
pfnHyphenate: isize,
},
};
//--------------------------------------------------------------------------------
// Section: Functions (229)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn CreatePropertySheetPageA(
constPropSheetPagePointer: ?*PROPSHEETPAGEA,
) callconv(@import("std").os.windows.WINAPI) ?HPROPSHEETPAGE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn CreatePropertySheetPageW(
constPropSheetPagePointer: ?*PROPSHEETPAGEW,
) callconv(@import("std").os.windows.WINAPI) ?HPROPSHEETPAGE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DestroyPropertySheetPage(
param0: ?HPROPSHEETPAGE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn PropertySheetA(
param0: ?*PROPSHEETHEADERA_V2,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn PropertySheetW(
param0: ?*PROPSHEETHEADERW_V2,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn InitCommonControls(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn InitCommonControlsEx(
picce: ?*const INITCOMMONCONTROLSEX,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Create(
cx: i32,
cy: i32,
flags: IMAGELIST_CREATION_FLAGS,
cInitial: i32,
cGrow: i32,
) callconv(@import("std").os.windows.WINAPI) ?HIMAGELIST;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Destroy(
himl: ?HIMAGELIST,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_GetImageCount(
himl: ?HIMAGELIST,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_SetImageCount(
himl: ?HIMAGELIST,
uNewCount: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Add(
himl: ?HIMAGELIST,
hbmImage: ?HBITMAP,
hbmMask: ?HBITMAP,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_ReplaceIcon(
himl: ?HIMAGELIST,
i: i32,
hicon: ?HICON,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_SetBkColor(
himl: ?HIMAGELIST,
clrBk: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_GetBkColor(
himl: ?HIMAGELIST,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_SetOverlayImage(
himl: ?HIMAGELIST,
iImage: i32,
iOverlay: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Draw(
himl: ?HIMAGELIST,
i: i32,
hdcDst: ?HDC,
x: i32,
y: i32,
fStyle: IMAGE_LIST_DRAW_STYLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Replace(
himl: ?HIMAGELIST,
i: i32,
hbmImage: ?HBITMAP,
hbmMask: ?HBITMAP,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_AddMasked(
himl: ?HIMAGELIST,
hbmImage: ?HBITMAP,
crMask: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_DrawEx(
himl: ?HIMAGELIST,
i: i32,
hdcDst: ?HDC,
x: i32,
y: i32,
dx: i32,
dy: i32,
rgbBk: u32,
rgbFg: u32,
fStyle: IMAGE_LIST_DRAW_STYLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_DrawIndirect(
pimldp: ?*IMAGELISTDRAWPARAMS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Remove(
himl: ?HIMAGELIST,
i: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_GetIcon(
himl: ?HIMAGELIST,
i: i32,
flags: u32,
) callconv(@import("std").os.windows.WINAPI) ?HICON;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_LoadImageA(
hi: ?HINSTANCE,
lpbmp: ?[*:0]const u8,
cx: i32,
cGrow: i32,
crMask: u32,
uType: u32,
uFlags: IMAGE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?HIMAGELIST;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_LoadImageW(
hi: ?HINSTANCE,
lpbmp: ?[*:0]const u16,
cx: i32,
cGrow: i32,
crMask: u32,
uType: u32,
uFlags: IMAGE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?HIMAGELIST;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Copy(
himlDst: ?HIMAGELIST,
iDst: i32,
himlSrc: ?HIMAGELIST,
iSrc: i32,
uFlags: IMAGE_LIST_COPY_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_BeginDrag(
himlTrack: ?HIMAGELIST,
iTrack: i32,
dxHotspot: i32,
dyHotspot: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_EndDrag(
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_DragEnter(
hwndLock: ?HWND,
x: i32,
y: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_DragLeave(
hwndLock: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_DragMove(
x: i32,
y: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_SetDragCursorImage(
himlDrag: ?HIMAGELIST,
iDrag: i32,
dxHotspot: i32,
dyHotspot: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_DragShowNolock(
fShow: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_GetDragImage(
ppt: ?*POINT,
pptHotspot: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) ?HIMAGELIST;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Read(
pstm: ?*IStream,
) callconv(@import("std").os.windows.WINAPI) ?HIMAGELIST;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Write(
himl: ?HIMAGELIST,
pstm: ?*IStream,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_ReadEx(
dwFlags: u32,
pstm: ?*IStream,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_WriteEx(
himl: ?HIMAGELIST,
dwFlags: u32,
pstm: ?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_GetIconSize(
himl: ?HIMAGELIST,
cx: ?*i32,
cy: ?*i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_SetIconSize(
himl: ?HIMAGELIST,
cx: i32,
cy: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_GetImageInfo(
himl: ?HIMAGELIST,
i: i32,
pImageInfo: ?*IMAGEINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Merge(
himl1: ?HIMAGELIST,
i1: i32,
himl2: ?HIMAGELIST,
i2: i32,
dx: i32,
dy: i32,
) callconv(@import("std").os.windows.WINAPI) ?HIMAGELIST;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_Duplicate(
himl: ?HIMAGELIST,
) callconv(@import("std").os.windows.WINAPI) ?HIMAGELIST;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn HIMAGELIST_QueryInterface(
himl: ?HIMAGELIST,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn CreateToolbarEx(
hwnd: ?HWND,
ws: u32,
wID: u32,
nBitmaps: i32,
hBMInst: ?HINSTANCE,
wBMID: usize,
lpButtons: ?*TBBUTTON,
iNumButtons: i32,
dxButton: i32,
dyButton: i32,
dxBitmap: i32,
dyBitmap: i32,
uStructSize: u32,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn CreateMappedBitmap(
hInstance: ?HINSTANCE,
idBitmap: isize,
wFlags: u32,
lpColorMap: ?*COLORMAP,
iNumMaps: i32,
) callconv(@import("std").os.windows.WINAPI) ?HBITMAP;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DrawStatusTextA(
hDC: ?HDC,
lprc: ?*RECT,
pszText: ?[*:0]const u8,
uFlags: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DrawStatusTextW(
hDC: ?HDC,
lprc: ?*RECT,
pszText: ?[*:0]const u16,
uFlags: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn CreateStatusWindowA(
style: i32,
lpszText: ?[*:0]const u8,
hwndParent: ?HWND,
wID: u32,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn CreateStatusWindowW(
style: i32,
lpszText: ?[*:0]const u16,
hwndParent: ?HWND,
wID: u32,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn MenuHelp(
uMsg: u32,
wParam: WPARAM,
lParam: LPARAM,
hMainMenu: ?HMENU,
hInst: ?HINSTANCE,
hwndStatus: ?HWND,
lpwIDs: ?*u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ShowHideMenuCtl(
hWnd: ?HWND,
uFlags: usize,
lpInfo: ?*i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn GetEffectiveClientRect(
hWnd: ?HWND,
lprc: ?*RECT,
lpInfo: ?*const i32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn MakeDragList(
hLB: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DrawInsert(
handParent: ?HWND,
hLB: ?HWND,
nItem: i32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn LBItemFromPt(
hLB: ?HWND,
pt: POINT,
bAutoScroll: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn CreateUpDownControl(
dwStyle: u32,
x: i32,
y: i32,
cx: i32,
cy: i32,
hParent: ?HWND,
nID: i32,
hInst: ?HINSTANCE,
hBuddy: ?HWND,
nUpper: i32,
nLower: i32,
nPos: i32,
) callconv(@import("std").os.windows.WINAPI) ?HWND;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn TaskDialogIndirect(
pTaskConfig: ?*const TASKDIALOGCONFIG,
pnButton: ?*i32,
pnRadioButton: ?*i32,
pfVerificationFlagChecked: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn TaskDialog(
hwndOwner: ?HWND,
hInstance: ?HINSTANCE,
pszWindowTitle: ?[*:0]const u16,
pszMainInstruction: ?[*:0]const u16,
pszContent: ?[*:0]const u16,
dwCommonButtons: TASKDIALOG_COMMON_BUTTON_FLAGS,
pszIcon: ?[*:0]const u16,
pnButton: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn InitMUILanguage(
uiLang: u16,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn GetMUILanguage(
) callconv(@import("std").os.windows.WINAPI) u16;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_Create(
cbItem: i32,
cItemGrow: i32,
) callconv(@import("std").os.windows.WINAPI) ?*_DSA;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_Destroy(
hdsa: ?*_DSA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_DestroyCallback(
hdsa: ?*_DSA,
pfnCB: ?PFNDAENUMCALLBACK,
pData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_DeleteItem(
hdsa: ?*_DSA,
i: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_DeleteAllItems(
hdsa: ?*_DSA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_EnumCallback(
hdsa: ?*_DSA,
pfnCB: ?PFNDAENUMCALLBACK,
pData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_InsertItem(
hdsa: ?*_DSA,
i: i32,
pitem: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_GetItemPtr(
hdsa: ?*_DSA,
i: i32,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_GetItem(
hdsa: ?*_DSA,
i: i32,
pitem: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_SetItem(
hdsa: ?*_DSA,
i: i32,
pitem: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_Clone(
hdsa: ?*_DSA,
) callconv(@import("std").os.windows.WINAPI) ?*_DSA;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_GetSize(
hdsa: ?*_DSA,
) callconv(@import("std").os.windows.WINAPI) u64;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DSA_Sort(
pdsa: ?*_DSA,
pfnCompare: ?PFNDACOMPARE,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_Create(
cItemGrow: i32,
) callconv(@import("std").os.windows.WINAPI) ?*_DPA;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_CreateEx(
cpGrow: i32,
hheap: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) ?*_DPA;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_Clone(
hdpa: ?*const _DPA,
hdpaNew: ?*_DPA,
) callconv(@import("std").os.windows.WINAPI) ?*_DPA;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_Destroy(
hdpa: ?*_DPA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_DestroyCallback(
hdpa: ?*_DPA,
pfnCB: ?PFNDAENUMCALLBACK,
pData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_DeletePtr(
hdpa: ?*_DPA,
i: i32,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_DeleteAllPtrs(
hdpa: ?*_DPA,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_EnumCallback(
hdpa: ?*_DPA,
pfnCB: ?PFNDAENUMCALLBACK,
pData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_Grow(
pdpa: ?*_DPA,
cp: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_InsertPtr(
hdpa: ?*_DPA,
i: i32,
p: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_SetPtr(
hdpa: ?*_DPA,
i: i32,
p: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_GetPtr(
hdpa: ?*_DPA,
i: isize,
) callconv(@import("std").os.windows.WINAPI) ?*c_void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_GetPtrIndex(
hdpa: ?*_DPA,
p: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_GetSize(
hdpa: ?*_DPA,
) callconv(@import("std").os.windows.WINAPI) u64;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_Sort(
hdpa: ?*_DPA,
pfnCompare: ?PFNDACOMPARE,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_LoadStream(
phdpa: ?*?*_DPA,
pfn: ?PFNDPASTREAM,
pstream: ?*IStream,
pvInstData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_SaveStream(
hdpa: ?*_DPA,
pfn: ?PFNDPASTREAM,
pstream: ?*IStream,
pvInstData: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_Merge(
hdpaDest: ?*_DPA,
hdpaSrc: ?*_DPA,
dwFlags: u32,
pfnCompare: ?PFNDACOMPARE,
pfnMerge: ?PFNDPAMERGE,
lParam: LPARAM,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DPA_Search(
hdpa: ?*_DPA,
pFind: ?*c_void,
iStart: i32,
pfnCompare: ?PFNDACOMPARE,
lParam: LPARAM,
options: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn Str_SetPtrW(
ppsz: ?*?PWSTR,
psz: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_EnableScrollBar(
param0: ?HWND,
param1: i32,
param2: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_ShowScrollBar(
param0: ?HWND,
code: SCROLLBAR_CONSTANTS,
param2: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_GetScrollRange(
param0: ?HWND,
code: SCROLLBAR_CONSTANTS,
param2: ?*i32,
param3: ?*i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_GetScrollInfo(
param0: ?HWND,
code: SCROLLBAR_CONSTANTS,
param2: ?*SCROLLINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_GetScrollPos(
param0: ?HWND,
code: SCROLLBAR_CONSTANTS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_GetScrollProp(
param0: ?HWND,
propIndex: WSB_PROP,
param2: ?*i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_SetScrollPos(
param0: ?HWND,
code: SCROLLBAR_CONSTANTS,
pos: i32,
fRedraw: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_SetScrollInfo(
param0: ?HWND,
code: SCROLLBAR_CONSTANTS,
psi: ?*SCROLLINFO,
fRedraw: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_SetScrollRange(
param0: ?HWND,
code: SCROLLBAR_CONSTANTS,
min: i32,
max: i32,
fRedraw: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn FlatSB_SetScrollProp(
param0: ?HWND,
index: WSB_PROP,
newValue: isize,
param3: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn InitializeFlatSB(
param0: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn UninitializeFlatSB(
param0: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn LoadIconMetric(
hinst: ?HINSTANCE,
pszName: ?[*:0]const u16,
lims: _LI_METRIC,
phico: ?*?HICON,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn LoadIconWithScaleDown(
hinst: ?HINSTANCE,
pszName: ?[*:0]const u16,
cx: i32,
cy: i32,
phico: ?*?HICON,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn DrawShadowText(
hdc: ?HDC,
pszText: [*:0]const u16,
cch: u32,
prc: ?*RECT,
dwFlags: u32,
crText: u32,
crShadow: u32,
ixOffset: i32,
iyOffset: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "COMCTL32" fn ImageList_CoCreateInstance(
rclsid: ?*const Guid,
punkOuter: ?*IUnknown,
riid: ?*const Guid,
ppv: ?*?*c_void,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "UXTHEME" fn GetThemeAnimationProperty(
hTheme: isize,
iStoryboardId: i32,
iTargetId: i32,
eProperty: TA_PROPERTY,
// TODO: what to do with BytesParamIndex 5?
pvProperty: ?*c_void,
cbSize: u32,
pcbSizeOut: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "UXTHEME" fn GetThemeAnimationTransform(
hTheme: isize,
iStoryboardId: i32,
iTargetId: i32,
dwTransformIndex: u32,
// TODO: what to do with BytesParamIndex 5?
pTransform: ?*TA_TRANSFORM,
cbSize: u32,
pcbSizeOut: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "UXTHEME" fn GetThemeTimingFunction(
hTheme: isize,
iTimingFunctionId: i32,
// TODO: what to do with BytesParamIndex 3?
pTimingFunction: ?*TA_TIMINGFUNCTION,
cbSize: u32,
pcbSizeOut: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn OpenThemeData(
hwnd: ?HWND,
pszClassList: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn OpenThemeDataEx(
hwnd: ?HWND,
pszClassList: ?[*:0]const u16,
dwFlags: OPEN_THEME_DATA_FLAGS,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn CloseThemeData(
hTheme: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn DrawThemeBackground(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pRect: ?*RECT,
pClipRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn DrawThemeBackgroundEx(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pRect: ?*RECT,
pOptions: ?*const DTBGOPTS,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn DrawThemeText(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pszText: [*:0]const u16,
cchText: i32,
dwTextFlags: u32,
dwTextFlags2: u32,
pRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeBackgroundContentRect(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pBoundingRect: ?*RECT,
pContentRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeBackgroundExtent(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pContentRect: ?*RECT,
pExtentRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeBackgroundRegion(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pRect: ?*RECT,
pRegion: ?*?HRGN,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemePartSize(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
prc: ?*RECT,
eSize: THEMESIZE,
psz: ?*SIZE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeTextExtent(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pszText: [*:0]const u16,
cchCharCount: i32,
dwTextFlags: u32,
pBoundingRect: ?*RECT,
pExtentRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeTextMetrics(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
ptm: ?*TEXTMETRICW,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn HitTestThemeBackground(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
dwOptions: u32,
pRect: ?*RECT,
hrgn: ?HRGN,
ptTest: POINT,
pwHitTestCode: ?*u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn DrawThemeEdge(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pDestRect: ?*RECT,
uEdge: u32,
uFlags: u32,
pContentRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn DrawThemeIcon(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pRect: ?*RECT,
himl: ?HIMAGELIST,
iImageIndex: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn IsThemePartDefined(
hTheme: isize,
iPartId: i32,
iStateId: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn IsThemeBackgroundPartiallyTransparent(
hTheme: isize,
iPartId: i32,
iStateId: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeColor(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
pColor: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeMetric(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
iPropId: THEME_PROPERTY_SYMBOL_ID,
piVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeString(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
pszBuff: [*:0]u16,
cchMaxBuffChars: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeBool(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: THEME_PROPERTY_SYMBOL_ID,
pfVal: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeInt(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
piVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeEnumValue(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
piVal: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemePosition(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
pPoint: ?*POINT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeFont(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
iPropId: i32,
pFont: ?*LOGFONTW,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeRect(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
pRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeMargins(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
iPropId: i32,
prc: ?*RECT,
pMargins: ?*MARGINS,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeIntList(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
pIntList: ?*INTLIST,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemePropertyOrigin(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
pOrigin: ?*PROPERTYORIGIN,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn SetWindowTheme(
hwnd: ?HWND,
pszSubAppName: ?[*:0]const u16,
pszSubIdList: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeFilename(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
pszThemeFileName: [*:0]u16,
cchMaxBuffChars: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeSysColor(
hTheme: isize,
iColorId: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeSysColorBrush(
hTheme: isize,
iColorId: THEME_PROPERTY_SYMBOL_ID,
) callconv(@import("std").os.windows.WINAPI) ?HBRUSH;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeSysBool(
hTheme: isize,
iBoolId: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeSysSize(
hTheme: isize,
iSizeId: i32,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeSysFont(
hTheme: isize,
iFontId: THEME_PROPERTY_SYMBOL_ID,
plf: ?*LOGFONTW,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeSysString(
hTheme: isize,
iStringId: THEME_PROPERTY_SYMBOL_ID,
pszStringBuff: [*:0]u16,
cchMaxStringChars: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeSysInt(
hTheme: isize,
iIntId: i32,
piValue: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn IsThemeActive(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn IsAppThemed(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetWindowTheme(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn EnableThemeDialogTexture(
hwnd: ?HWND,
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn IsThemeDialogTextureEnabled(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeAppProperties(
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn SetThemeAppProperties(
dwFlags: u32,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetCurrentThemeName(
pszThemeFileName: [*:0]u16,
cchMaxNameChars: i32,
pszColorBuff: ?[*:0]u16,
cchMaxColorChars: i32,
pszSizeBuff: ?[*:0]u16,
cchMaxSizeChars: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeDocumentationProperty(
pszThemeName: ?[*:0]const u16,
pszPropertyName: ?[*:0]const u16,
pszValueBuff: [*:0]u16,
cchMaxValChars: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn DrawThemeParentBackground(
hwnd: ?HWND,
hdc: ?HDC,
prc: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn EnableTheming(
fEnable: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn DrawThemeParentBackgroundEx(
hwnd: ?HWND,
hdc: ?HDC,
dwFlags: DRAW_THEME_PARENT_BACKGROUND_FLAGS,
prc: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn SetWindowThemeAttribute(
hwnd: ?HWND,
eAttribute: WINDOWTHEMEATTRIBUTETYPE,
// TODO: what to do with BytesParamIndex 3?
pvAttribute: ?*c_void,
cbAttribute: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn DrawThemeTextEx(
hTheme: isize,
hdc: ?HDC,
iPartId: i32,
iStateId: i32,
pszText: [*:0]const u16,
cchText: i32,
dwTextFlags: u32,
pRect: ?*RECT,
pOptions: ?*const DTTOPTS,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeBitmap(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: THEME_PROPERTY_SYMBOL_ID,
dwFlags: GET_THEME_BITMAP_FLAGS,
phBitmap: ?*?HBITMAP,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetThemeStream(
hTheme: isize,
iPartId: i32,
iStateId: i32,
iPropId: i32,
ppvStream: ?*?*c_void,
pcbStream: ?*u32,
hInst: ?HINSTANCE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn BufferedPaintInit(
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn BufferedPaintUnInit(
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn BeginBufferedPaint(
hdcTarget: ?HDC,
prcTarget: ?*const RECT,
dwFormat: BP_BUFFERFORMAT,
pPaintParams: ?*BP_PAINTPARAMS,
phdc: ?*?HDC,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn EndBufferedPaint(
hBufferedPaint: isize,
fUpdateTarget: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetBufferedPaintTargetRect(
hBufferedPaint: isize,
prc: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetBufferedPaintTargetDC(
hBufferedPaint: isize,
) callconv(@import("std").os.windows.WINAPI) ?HDC;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetBufferedPaintDC(
hBufferedPaint: isize,
) callconv(@import("std").os.windows.WINAPI) ?HDC;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn GetBufferedPaintBits(
hBufferedPaint: isize,
ppbBuffer: ?*?*RGBQUAD,
pcxRow: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn BufferedPaintClear(
hBufferedPaint: isize,
prc: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn BufferedPaintSetAlpha(
hBufferedPaint: isize,
prc: ?*const RECT,
alpha: u8,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn BufferedPaintStopAllAnimations(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn BeginBufferedAnimation(
hwnd: ?HWND,
hdcTarget: ?HDC,
prcTarget: ?*const RECT,
dwFormat: BP_BUFFERFORMAT,
pPaintParams: ?*BP_PAINTPARAMS,
pAnimationParams: ?*BP_ANIMATIONPARAMS,
phdcFrom: ?*?HDC,
phdcTo: ?*?HDC,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn EndBufferedAnimation(
hbpAnimation: isize,
fUpdateTarget: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn BufferedPaintRenderAnimation(
hwnd: ?HWND,
hdcTarget: ?HDC,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UXTHEME" fn IsCompositionActive(
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "UxTheme" fn GetThemeTransitionDuration(
hTheme: isize,
iPartId: i32,
iStateIdFrom: i32,
iStateIdTo: i32,
iPropId: i32,
pdwDuration: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn CheckDlgButton(
hDlg: ?HWND,
nIDButton: i32,
uCheck: DLG_BUTTON_CHECK_STATE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn CheckRadioButton(
hDlg: ?HWND,
nIDFirstButton: i32,
nIDLastButton: i32,
nIDCheckButton: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn IsDlgButtonChecked(
hDlg: ?HWND,
nIDButton: i32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "USER32" fn IsCharLowerW(
ch: u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn InitializeTouchInjection(
maxCount: u32,
dwMode: TOUCH_FEEDBACK_MODE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn InjectTouchInput(
count: u32,
contacts: [*]const POINTER_TOUCH_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.17763'
pub extern "USER32" fn CreateSyntheticPointerDevice(
pointerType: POINTER_INPUT_TYPE,
maxCount: u32,
mode: POINTER_FEEDBACK_MODE,
) callconv(@import("std").os.windows.WINAPI) ?HSYNTHETICPOINTERDEVICE;
// TODO: this type is limited to platform 'windows10.0.17763'
pub extern "USER32" fn InjectSyntheticPointerInput(
device: ?HSYNTHETICPOINTERDEVICE,
pointerInfo: [*]const POINTER_TYPE_INFO,
count: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.17763'
pub extern "USER32" fn DestroySyntheticPointerDevice(
device: ?HSYNTHETICPOINTERDEVICE,
) callconv(@import("std").os.windows.WINAPI) void;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn RegisterTouchHitTestingWindow(
hwnd: ?HWND,
value: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn EvaluateProximityToRect(
controlBoundingBox: ?*const RECT,
pHitTestingInput: ?*const TOUCH_HIT_TESTING_INPUT,
pProximityEval: ?*TOUCH_HIT_TESTING_PROXIMITY_EVALUATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn EvaluateProximityToPolygon(
numVertices: u32,
controlPolygon: [*]const POINT,
pHitTestingInput: ?*const TOUCH_HIT_TESTING_INPUT,
pProximityEval: ?*TOUCH_HIT_TESTING_PROXIMITY_EVALUATION,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn PackTouchHitTestingProximityEvaluation(
pHitTestingInput: ?*const TOUCH_HIT_TESTING_INPUT,
pProximityEval: ?*const TOUCH_HIT_TESTING_PROXIMITY_EVALUATION,
) callconv(@import("std").os.windows.WINAPI) LRESULT;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetWindowFeedbackSetting(
hwnd: ?HWND,
feedback: FEEDBACK_TYPE,
dwFlags: u32,
pSize: ?*u32,
// TODO: what to do with BytesParamIndex 3?
config: ?*c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn SetWindowFeedbackSetting(
hwnd: ?HWND,
feedback: FEEDBACK_TYPE,
dwFlags: u32,
size: u32,
// TODO: what to do with BytesParamIndex 3?
configuration: ?*const c_void,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn ScrollWindow(
hWnd: ?HWND,
XAmount: i32,
YAmount: i32,
lpRect: ?*const RECT,
lpClipRect: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn ScrollDC(
hDC: ?HDC,
dx: i32,
dy: i32,
lprcScroll: ?*const RECT,
lprcClip: ?*const RECT,
hrgnUpdate: ?HRGN,
lprcUpdate: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn ScrollWindowEx(
hWnd: ?HWND,
dx: i32,
dy: i32,
prcScroll: ?*const RECT,
prcClip: ?*const RECT,
hrgnUpdate: ?HRGN,
prcUpdate: ?*RECT,
flags: SHOW_WINDOW_CMD,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn SetScrollPos(
hWnd: ?HWND,
nBar: SCROLLBAR_CONSTANTS,
nPos: i32,
bRedraw: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetScrollPos(
hWnd: ?HWND,
nBar: SCROLLBAR_CONSTANTS,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn SetScrollRange(
hWnd: ?HWND,
nBar: SCROLLBAR_CONSTANTS,
nMinPos: i32,
nMaxPos: i32,
bRedraw: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetScrollRange(
hWnd: ?HWND,
nBar: SCROLLBAR_CONSTANTS,
lpMinPos: ?*i32,
lpMaxPos: ?*i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn ShowScrollBar(
hWnd: ?HWND,
wBar: SCROLLBAR_CONSTANTS,
bShow: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn EnableScrollBar(
hWnd: ?HWND,
wSBflags: SCROLLBAR_CONSTANTS,
wArrows: ENABLE_SCROLL_BAR_ARROWS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn DlgDirListA(
hDlg: ?HWND,
lpPathSpec: ?PSTR,
nIDListBox: i32,
nIDStaticPath: i32,
uFileType: DLG_DIR_LIST_FILE_TYPE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn DlgDirListW(
hDlg: ?HWND,
lpPathSpec: ?PWSTR,
nIDListBox: i32,
nIDStaticPath: i32,
uFileType: DLG_DIR_LIST_FILE_TYPE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn DlgDirSelectExA(
hwndDlg: ?HWND,
lpString: [*:0]u8,
chCount: i32,
idListBox: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn DlgDirSelectExW(
hwndDlg: ?HWND,
lpString: [*:0]u16,
chCount: i32,
idListBox: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn DlgDirListComboBoxA(
hDlg: ?HWND,
lpPathSpec: ?PSTR,
nIDComboBox: i32,
nIDStaticPath: i32,
uFiletype: DLG_DIR_LIST_FILE_TYPE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn DlgDirListComboBoxW(
hDlg: ?HWND,
lpPathSpec: ?PWSTR,
nIDComboBox: i32,
nIDStaticPath: i32,
uFiletype: DLG_DIR_LIST_FILE_TYPE,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn DlgDirSelectComboBoxExA(
hwndDlg: ?HWND,
lpString: [*:0]u8,
cchOut: i32,
idComboBox: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn DlgDirSelectComboBoxExW(
hwndDlg: ?HWND,
lpString: [*:0]u16,
cchOut: i32,
idComboBox: i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn SetScrollInfo(
hwnd: ?HWND,
nBar: SCROLLBAR_CONSTANTS,
lpsi: ?*SCROLLINFO,
redraw: BOOL,
) callconv(@import("std").os.windows.WINAPI) i32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetScrollInfo(
hwnd: ?HWND,
nBar: SCROLLBAR_CONSTANTS,
lpsi: ?*SCROLLINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetScrollBarInfo(
hwnd: ?HWND,
idObject: OBJECT_IDENTIFIER,
psbi: ?*SCROLLBARINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetComboBoxInfo(
hwndCombo: ?HWND,
pcbi: ?*COMBOBOXINFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "USER32" fn GetListBoxInfo(
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetPointerDevices(
deviceCount: ?*u32,
pointerDevices: ?[*]POINTER_DEVICE_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetPointerDevice(
device: ?HANDLE,
pointerDevice: ?*POINTER_DEVICE_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetPointerDeviceProperties(
device: ?HANDLE,
propertyCount: ?*u32,
pointerProperties: ?[*]POINTER_DEVICE_PROPERTY,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn RegisterPointerDeviceNotifications(
window: ?HWND,
notifyRange: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetPointerDeviceRects(
device: ?HANDLE,
pointerDeviceRect: ?*RECT,
displayRect: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetPointerDeviceCursors(
device: ?HANDLE,
cursorCount: ?*u32,
deviceCursors: ?[*]POINTER_DEVICE_CURSOR_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetRawPointerDeviceData(
pointerId: u32,
historyCount: u32,
propertiesCount: u32,
pProperties: [*]POINTER_DEVICE_PROPERTY,
pValues: ?*i32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetCurrentInputMessageSource(
inputMessageSource: ?*INPUT_MESSAGE_SOURCE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "USER32" fn GetCIMSSM(
inputMessageSource: ?*INPUT_MESSAGE_SOURCE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (54)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const TEXTRANGE = thismodule.TEXTRANGEA;
pub const FINDTEXT = thismodule.FINDTEXTA;
pub const FINDTEXTEX = thismodule.FINDTEXTEXA;
pub const LPFNPSPCALLBACK = thismodule.LPFNPSPCALLBACKA;
pub const PROPSHEETPAGE = thismodule.PROPSHEETPAGEA;
pub const HD_TEXTFILTER = thismodule.HD_TEXTFILTERA;
pub const HDITEM = thismodule.HDITEMA;
pub const NMHEADER = thismodule.NMHEADERA;
pub const NMHDDISPINFO = thismodule.NMHDDISPINFOA;
pub const TBSAVEPARAMS = thismodule.TBSAVEPARAMSA;
pub const TBBUTTONINFO = thismodule.TBBUTTONINFOA;
pub const NMTBGETINFOTIP = thismodule.NMTBGETINFOTIPA;
pub const NMTBDISPINFO = thismodule.NMTBDISPINFOA;
pub const NMTOOLBAR = thismodule.NMTOOLBARA;
pub const REBARBANDINFO = thismodule.REBARBANDINFOA;
pub const TTTOOLINFO = thismodule.TTTOOLINFOA;
pub const TTHITTESTINFO = thismodule.TTHITTESTINFOA;
pub const NMTTDISPINFO = thismodule.NMTTDISPINFOA;
pub const LVITEM = thismodule.LVITEMA;
pub const LVFINDINFO = thismodule.LVFINDINFOA;
pub const LVCOLUMN = thismodule.LVCOLUMNA;
pub const LVBKIMAGE = thismodule.LVBKIMAGEA;
pub const NMLVFINDITEM = thismodule.NMLVFINDITEMA;
pub const NMLVDISPINFO = thismodule.NMLVDISPINFOA;
pub const NMLVGETINFOTIP = thismodule.NMLVGETINFOTIPA;
pub const TVITEM = thismodule.TVITEMA;
pub const TVITEMEX = thismodule.TVITEMEXA;
pub const TVINSERTSTRUCT = thismodule.TVINSERTSTRUCTA;
pub const NMTREEVIEW = thismodule.NMTREEVIEWA;
pub const NMTVDISPINFO = thismodule.NMTVDISPINFOA;
pub const NMTVDISPINFOEX = thismodule.NMTVDISPINFOEXA;
pub const NMTVGETINFOTIP = thismodule.NMTVGETINFOTIPA;
pub const COMBOBOXEXITEM = thismodule.COMBOBOXEXITEMA;
pub const NMCOMBOBOXEX = thismodule.NMCOMBOBOXEXA;
pub const NMCBEDRAGBEGIN = thismodule.NMCBEDRAGBEGINA;
pub const NMCBEENDEDIT = thismodule.NMCBEENDEDITA;
pub const TCITEMHEADER = thismodule.TCITEMHEADERA;
pub const TCITEM = thismodule.TCITEMA;
pub const NMDATETIMESTRING = thismodule.NMDATETIMESTRINGA;
pub const NMDATETIMEWMKEYDOWN = thismodule.NMDATETIMEWMKEYDOWNA;
pub const NMDATETIMEFORMAT = thismodule.NMDATETIMEFORMATA;
pub const NMDATETIMEFORMATQUERY = thismodule.NMDATETIMEFORMATQUERYA;
pub const CHARFORMAT = thismodule.CHARFORMATA;
pub const CHARFORMAT2 = thismodule.CHARFORMAT2A;
pub const EDITWORDBREAKPROC = thismodule.EDITWORDBREAKPROCA;
pub const CreatePropertySheetPage = thismodule.CreatePropertySheetPageA;
pub const PropertySheet = thismodule.PropertySheetA;
pub const ImageList_LoadImage = thismodule.ImageList_LoadImageA;
pub const DrawStatusText = thismodule.DrawStatusTextA;
pub const CreateStatusWindow = thismodule.CreateStatusWindowA;
pub const DlgDirList = thismodule.DlgDirListA;
pub const DlgDirSelectEx = thismodule.DlgDirSelectExA;
pub const DlgDirListComboBox = thismodule.DlgDirListComboBoxA;
pub const DlgDirSelectComboBoxEx = thismodule.DlgDirSelectComboBoxExA;
},
.wide => struct {
pub const TEXTRANGE = thismodule.TEXTRANGEW;
pub const FINDTEXT = thismodule.FINDTEXTW;
pub const FINDTEXTEX = thismodule.FINDTEXTEXW;
pub const LPFNPSPCALLBACK = thismodule.LPFNPSPCALLBACKW;
pub const PROPSHEETPAGE = thismodule.PROPSHEETPAGEW;
pub const HD_TEXTFILTER = thismodule.HD_TEXTFILTERW;
pub const HDITEM = thismodule.HDITEMW;
pub const NMHEADER = thismodule.NMHEADERW;
pub const NMHDDISPINFO = thismodule.NMHDDISPINFOW;
pub const TBSAVEPARAMS = thismodule.TBSAVEPARAMSW;
pub const TBBUTTONINFO = thismodule.TBBUTTONINFOW;
pub const NMTBGETINFOTIP = thismodule.NMTBGETINFOTIPW;
pub const NMTBDISPINFO = thismodule.NMTBDISPINFOW;
pub const NMTOOLBAR = thismodule.NMTOOLBARW;
pub const REBARBANDINFO = thismodule.REBARBANDINFOW;
pub const TTTOOLINFO = thismodule.TTTOOLINFOW;
pub const TTHITTESTINFO = thismodule.TTHITTESTINFOW;
pub const NMTTDISPINFO = thismodule.NMTTDISPINFOW;
pub const LVITEM = thismodule.LVITEMW;
pub const LVFINDINFO = thismodule.LVFINDINFOW;
pub const LVCOLUMN = thismodule.LVCOLUMNW;
pub const LVBKIMAGE = thismodule.LVBKIMAGEW;
pub const NMLVFINDITEM = thismodule.NMLVFINDITEMW;
pub const NMLVDISPINFO = thismodule.NMLVDISPINFOW;
pub const NMLVGETINFOTIP = thismodule.NMLVGETINFOTIPW;
pub const TVITEM = thismodule.TVITEMW;
pub const TVITEMEX = thismodule.TVITEMEXW;
pub const TVINSERTSTRUCT = thismodule.TVINSERTSTRUCTW;
pub const NMTREEVIEW = thismodule.NMTREEVIEWW;
pub const NMTVDISPINFO = thismodule.NMTVDISPINFOW;
pub const NMTVDISPINFOEX = thismodule.NMTVDISPINFOEXW;
pub const NMTVGETINFOTIP = thismodule.NMTVGETINFOTIPW;
pub const COMBOBOXEXITEM = thismodule.COMBOBOXEXITEMW;
pub const NMCOMBOBOXEX = thismodule.NMCOMBOBOXEXW;
pub const NMCBEDRAGBEGIN = thismodule.NMCBEDRAGBEGINW;
pub const NMCBEENDEDIT = thismodule.NMCBEENDEDITW;
pub const TCITEMHEADER = thismodule.TCITEMHEADERW;
pub const TCITEM = thismodule.TCITEMW;
pub const NMDATETIMESTRING = thismodule.NMDATETIMESTRINGW;
pub const NMDATETIMEWMKEYDOWN = thismodule.NMDATETIMEWMKEYDOWNW;
pub const NMDATETIMEFORMAT = thismodule.NMDATETIMEFORMATW;
pub const NMDATETIMEFORMATQUERY = thismodule.NMDATETIMEFORMATQUERYW;
pub const CHARFORMAT = thismodule.CHARFORMATW;
pub const CHARFORMAT2 = thismodule.CHARFORMAT2W;
pub const EDITWORDBREAKPROC = thismodule.EDITWORDBREAKPROCW;
pub const CreatePropertySheetPage = thismodule.CreatePropertySheetPageW;
pub const PropertySheet = thismodule.PropertySheetW;
pub const ImageList_LoadImage = thismodule.ImageList_LoadImageW;
pub const DrawStatusText = thismodule.DrawStatusTextW;
pub const CreateStatusWindow = thismodule.CreateStatusWindowW;
pub const DlgDirList = thismodule.DlgDirListW;
pub const DlgDirSelectEx = thismodule.DlgDirSelectExW;
pub const DlgDirListComboBox = thismodule.DlgDirListComboBoxW;
pub const DlgDirSelectComboBoxEx = thismodule.DlgDirSelectComboBoxExW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const TEXTRANGE = *opaque{};
pub const FINDTEXT = *opaque{};
pub const FINDTEXTEX = *opaque{};
pub const LPFNPSPCALLBACK = *opaque{};
pub const PROPSHEETPAGE = *opaque{};
pub const HD_TEXTFILTER = *opaque{};
pub const HDITEM = *opaque{};
pub const NMHEADER = *opaque{};
pub const NMHDDISPINFO = *opaque{};
pub const TBSAVEPARAMS = *opaque{};
pub const TBBUTTONINFO = *opaque{};
pub const NMTBGETINFOTIP = *opaque{};
pub const NMTBDISPINFO = *opaque{};
pub const NMTOOLBAR = *opaque{};
pub const REBARBANDINFO = *opaque{};
pub const TTTOOLINFO = *opaque{};
pub const TTHITTESTINFO = *opaque{};
pub const NMTTDISPINFO = *opaque{};
pub const LVITEM = *opaque{};
pub const LVFINDINFO = *opaque{};
pub const LVCOLUMN = *opaque{};
pub const LVBKIMAGE = *opaque{};
pub const NMLVFINDITEM = *opaque{};
pub const NMLVDISPINFO = *opaque{};
pub const NMLVGETINFOTIP = *opaque{};
pub const TVITEM = *opaque{};
pub const TVITEMEX = *opaque{};
pub const TVINSERTSTRUCT = *opaque{};
pub const NMTREEVIEW = *opaque{};
pub const NMTVDISPINFO = *opaque{};
pub const NMTVDISPINFOEX = *opaque{};
pub const NMTVGETINFOTIP = *opaque{};
pub const COMBOBOXEXITEM = *opaque{};
pub const NMCOMBOBOXEX = *opaque{};
pub const NMCBEDRAGBEGIN = *opaque{};
pub const NMCBEENDEDIT = *opaque{};
pub const TCITEMHEADER = *opaque{};
pub const TCITEM = *opaque{};
pub const NMDATETIMESTRING = *opaque{};
pub const NMDATETIMEWMKEYDOWN = *opaque{};
pub const NMDATETIMEFORMAT = *opaque{};
pub const NMDATETIMEFORMATQUERY = *opaque{};
pub const CHARFORMAT = *opaque{};
pub const CHARFORMAT2 = *opaque{};
pub const EDITWORDBREAKPROC = *opaque{};
pub const CreatePropertySheetPage = *opaque{};
pub const PropertySheet = *opaque{};
pub const ImageList_LoadImage = *opaque{};
pub const DrawStatusText = *opaque{};
pub const CreateStatusWindow = *opaque{};
pub const DlgDirList = *opaque{};
pub const DlgDirSelectEx = *opaque{};
pub const DlgDirListComboBox = *opaque{};
pub const DlgDirSelectComboBoxEx = *opaque{};
} else struct {
pub const TEXTRANGE = @compileError("'TEXTRANGE' requires that UNICODE be set to true or false in the root module");
pub const FINDTEXT = @compileError("'FINDTEXT' requires that UNICODE be set to true or false in the root module");
pub const FINDTEXTEX = @compileError("'FINDTEXTEX' requires that UNICODE be set to true or false in the root module");
pub const LPFNPSPCALLBACK = @compileError("'LPFNPSPCALLBACK' requires that UNICODE be set to true or false in the root module");
pub const PROPSHEETPAGE = @compileError("'PROPSHEETPAGE' requires that UNICODE be set to true or false in the root module");
pub const HD_TEXTFILTER = @compileError("'HD_TEXTFILTER' requires that UNICODE be set to true or false in the root module");
pub const HDITEM = @compileError("'HDITEM' requires that UNICODE be set to true or false in the root module");
pub const NMHEADER = @compileError("'NMHEADER' requires that UNICODE be set to true or false in the root module");
pub const NMHDDISPINFO = @compileError("'NMHDDISPINFO' requires that UNICODE be set to true or false in the root module");
pub const TBSAVEPARAMS = @compileError("'TBSAVEPARAMS' requires that UNICODE be set to true or false in the root module");
pub const TBBUTTONINFO = @compileError("'TBBUTTONINFO' requires that UNICODE be set to true or false in the root module");
pub const NMTBGETINFOTIP = @compileError("'NMTBGETINFOTIP' requires that UNICODE be set to true or false in the root module");
pub const NMTBDISPINFO = @compileError("'NMTBDISPINFO' requires that UNICODE be set to true or false in the root module");
pub const NMTOOLBAR = @compileError("'NMTOOLBAR' requires that UNICODE be set to true or false in the root module");
pub const REBARBANDINFO = @compileError("'REBARBANDINFO' requires that UNICODE be set to true or false in the root module");
pub const TTTOOLINFO = @compileError("'TTTOOLINFO' requires that UNICODE be set to true or false in the root module");
pub const TTHITTESTINFO = @compileError("'TTHITTESTINFO' requires that UNICODE be set to true or false in the root module");
pub const NMTTDISPINFO = @compileError("'NMTTDISPINFO' requires that UNICODE be set to true or false in the root module");
pub const LVITEM = @compileError("'LVITEM' requires that UNICODE be set to true or false in the root module");
pub const LVFINDINFO = @compileError("'LVFINDINFO' requires that UNICODE be set to true or false in the root module");
pub const LVCOLUMN = @compileError("'LVCOLUMN' requires that UNICODE be set to true or false in the root module");
pub const LVBKIMAGE = @compileError("'LVBKIMAGE' requires that UNICODE be set to true or false in the root module");
pub const NMLVFINDITEM = @compileError("'NMLVFINDITEM' requires that UNICODE be set to true or false in the root module");
pub const NMLVDISPINFO = @compileError("'NMLVDISPINFO' requires that UNICODE be set to true or false in the root module");
pub const NMLVGETINFOTIP = @compileError("'NMLVGETINFOTIP' requires that UNICODE be set to true or false in the root module");
pub const TVITEM = @compileError("'TVITEM' requires that UNICODE be set to true or false in the root module");
pub const TVITEMEX = @compileError("'TVITEMEX' requires that UNICODE be set to true or false in the root module");
pub const TVINSERTSTRUCT = @compileError("'TVINSERTSTRUCT' requires that UNICODE be set to true or false in the root module");
pub const NMTREEVIEW = @compileError("'NMTREEVIEW' requires that UNICODE be set to true or false in the root module");
pub const NMTVDISPINFO = @compileError("'NMTVDISPINFO' requires that UNICODE be set to true or false in the root module");
pub const NMTVDISPINFOEX = @compileError("'NMTVDISPINFOEX' requires that UNICODE be set to true or false in the root module");
pub const NMTVGETINFOTIP = @compileError("'NMTVGETINFOTIP' requires that UNICODE be set to true or false in the root module");
pub const COMBOBOXEXITEM = @compileError("'COMBOBOXEXITEM' requires that UNICODE be set to true or false in the root module");
pub const NMCOMBOBOXEX = @compileError("'NMCOMBOBOXEX' requires that UNICODE be set to true or false in the root module");
pub const NMCBEDRAGBEGIN = @compileError("'NMCBEDRAGBEGIN' requires that UNICODE be set to true or false in the root module");
pub const NMCBEENDEDIT = @compileError("'NMCBEENDEDIT' requires that UNICODE be set to true or false in the root module");
pub const TCITEMHEADER = @compileError("'TCITEMHEADER' requires that UNICODE be set to true or false in the root module");
pub const TCITEM = @compileError("'TCITEM' requires that UNICODE be set to true or false in the root module");
pub const NMDATETIMESTRING = @compileError("'NMDATETIMESTRING' requires that UNICODE be set to true or false in the root module");
pub const NMDATETIMEWMKEYDOWN = @compileError("'NMDATETIMEWMKEYDOWN' requires that UNICODE be set to true or false in the root module");
pub const NMDATETIMEFORMAT = @compileError("'NMDATETIMEFORMAT' requires that UNICODE be set to true or false in the root module");
pub const NMDATETIMEFORMATQUERY = @compileError("'NMDATETIMEFORMATQUERY' requires that UNICODE be set to true or false in the root module");
pub const CHARFORMAT = @compileError("'CHARFORMAT' requires that UNICODE be set to true or false in the root module");
pub const CHARFORMAT2 = @compileError("'CHARFORMAT2' requires that UNICODE be set to true or false in the root module");
pub const EDITWORDBREAKPROC = @compileError("'EDITWORDBREAKPROC' requires that UNICODE be set to true or false in the root module");
pub const CreatePropertySheetPage = @compileError("'CreatePropertySheetPage' requires that UNICODE be set to true or false in the root module");
pub const PropertySheet = @compileError("'PropertySheet' requires that UNICODE be set to true or false in the root module");
pub const ImageList_LoadImage = @compileError("'ImageList_LoadImage' requires that UNICODE be set to true or false in the root module");
pub const DrawStatusText = @compileError("'DrawStatusText' requires that UNICODE be set to true or false in the root module");
pub const CreateStatusWindow = @compileError("'CreateStatusWindow' requires that UNICODE be set to true or false in the root module");
pub const DlgDirList = @compileError("'DlgDirList' requires that UNICODE be set to true or false in the root module");
pub const DlgDirSelectEx = @compileError("'DlgDirSelectEx' requires that UNICODE be set to true or false in the root module");
pub const DlgDirListComboBox = @compileError("'DlgDirListComboBox' requires that UNICODE be set to true or false in the root module");
pub const DlgDirSelectComboBoxEx = @compileError("'DlgDirSelectComboBoxEx' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (60)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BLENDFUNCTION = @import("../graphics/gdi.zig").BLENDFUNCTION;
const BOOL = @import("../foundation.zig").BOOL;
const BSTR = @import("../foundation.zig").BSTR;
const CHAR = @import("../system/system_services.zig").CHAR;
const DLGPROC = @import("../ui/windows_and_messaging.zig").DLGPROC;
const DLGTEMPLATE = @import("../ui/windows_and_messaging.zig").DLGTEMPLATE;
const DVASPECT = @import("../system/com.zig").DVASPECT;
const DVTARGETDEVICE = @import("../system/com.zig").DVTARGETDEVICE;
const HANDLE = @import("../foundation.zig").HANDLE;
const HBITMAP = @import("../graphics/gdi.zig").HBITMAP;
const HBRUSH = @import("../graphics/gdi.zig").HBRUSH;
const HCURSOR = @import("../ui/windows_and_messaging.zig").HCURSOR;
const HDC = @import("../graphics/gdi.zig").HDC;
const HICON = @import("../ui/windows_and_messaging.zig").HICON;
const HIMC = @import("../globalization.zig").HIMC;
const HINSTANCE = @import("../foundation.zig").HINSTANCE;
const HKEY = @import("../system/registry.zig").HKEY;
const HMENU = @import("../ui/windows_and_messaging.zig").HMENU;
const HMONITOR = @import("../graphics/gdi.zig").HMONITOR;
const HPALETTE = @import("../graphics/gdi.zig").HPALETTE;
const HPEN = @import("../graphics/gdi.zig").HPEN;
const HRESULT = @import("../foundation.zig").HRESULT;
const HRGN = @import("../graphics/gdi.zig").HRGN;
const HWND = @import("../foundation.zig").HWND;
const ID2D1RenderTarget = @import("../graphics/direct2d.zig").ID2D1RenderTarget;
const IDataObject = @import("../system/com.zig").IDataObject;
const IDispatch = @import("../system/ole_automation.zig").IDispatch;
const IDropTarget = @import("../system/com.zig").IDropTarget;
const IOleClientSite = @import("../system/com.zig").IOleClientSite;
const IOleInPlaceFrame = @import("../system/com.zig").IOleInPlaceFrame;
const IOleInPlaceUIWindow = @import("../system/com.zig").IOleInPlaceUIWindow;
const IOleObject = @import("../system/com.zig").IOleObject;
const IRawElementProviderSimple = @import("../ui/accessibility.zig").IRawElementProviderSimple;
const IRawElementProviderWindowlessSite = @import("../ui/accessibility.zig").IRawElementProviderWindowlessSite;
const IStorage = @import("../storage/structured_storage.zig").IStorage;
const IStream = @import("../storage/structured_storage.zig").IStream;
const IUnknown = @import("../system/com.zig").IUnknown;
const LOGFONTW = @import("../graphics/gdi.zig").LOGFONTW;
const LPARAM = @import("../foundation.zig").LPARAM;
const LRESULT = @import("../foundation.zig").LRESULT;
const OIFI = @import("../system/com.zig").OIFI;
const POINT = @import("../foundation.zig").POINT;
const POINTER_INPUT_TYPE = @import("../ui/windows_and_messaging.zig").POINTER_INPUT_TYPE;
const POINTER_PEN_INFO = @import("../ui/pointer_input.zig").POINTER_PEN_INFO;
const POINTER_TOUCH_INFO = @import("../ui/pointer_input.zig").POINTER_TOUCH_INFO;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const RECTL = @import("../foundation.zig").RECTL;
const RGBQUAD = @import("../graphics/gdi.zig").RGBQUAD;
const SHOW_WINDOW_CMD = @import("../ui/windows_and_messaging.zig").SHOW_WINDOW_CMD;
const SIZE = @import("../foundation.zig").SIZE;
const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME;
const TEXTMETRICW = @import("../graphics/gdi.zig").TEXTMETRICW;
const TTTOOLINFO_FLAGS = @import("../system/system_services.zig").TTTOOLINFO_FLAGS;
const UiaRect = @import("../ui/accessibility.zig").UiaRect;
const VARIANT = @import("../system/ole_automation.zig").VARIANT;
const WINDOWPOS = @import("../ui/windows_and_messaging.zig").WINDOWPOS;
const WPARAM = @import("../foundation.zig").WPARAM;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "LPFNPSPCALLBACKA")) { _ = LPFNPSPCALLBACKA; }
if (@hasDecl(@This(), "LPFNPSPCALLBACKW")) { _ = LPFNPSPCALLBACKW; }
if (@hasDecl(@This(), "PFNPROPSHEETCALLBACK")) { _ = PFNPROPSHEETCALLBACK; }
if (@hasDecl(@This(), "LPFNSVADDPROPSHEETPAGE")) { _ = LPFNSVADDPROPSHEETPAGE; }
if (@hasDecl(@This(), "LPFNADDPROPSHEETPAGES")) { _ = LPFNADDPROPSHEETPAGES; }
if (@hasDecl(@This(), "PFNLVCOMPARE")) { _ = PFNLVCOMPARE; }
if (@hasDecl(@This(), "PFNLVGROUPCOMPARE")) { _ = PFNLVGROUPCOMPARE; }
if (@hasDecl(@This(), "PFNTVCOMPARE")) { _ = PFNTVCOMPARE; }
if (@hasDecl(@This(), "PFTASKDIALOGCALLBACK")) { _ = PFTASKDIALOGCALLBACK; }
if (@hasDecl(@This(), "PFNDAENUMCALLBACK")) { _ = PFNDAENUMCALLBACK; }
if (@hasDecl(@This(), "PFNDAENUMCALLBACKCONST")) { _ = PFNDAENUMCALLBACKCONST; }
if (@hasDecl(@This(), "PFNDACOMPARE")) { _ = PFNDACOMPARE; }
if (@hasDecl(@This(), "PFNDACOMPARECONST")) { _ = PFNDACOMPARECONST; }
if (@hasDecl(@This(), "PFNDPASTREAM")) { _ = PFNDPASTREAM; }
if (@hasDecl(@This(), "PFNDPAMERGE")) { _ = PFNDPAMERGE; }
if (@hasDecl(@This(), "PFNDPAMERGECONST")) { _ = PFNDPAMERGECONST; }
if (@hasDecl(@This(), "AutoCorrectProc")) { _ = AutoCorrectProc; }
if (@hasDecl(@This(), "EDITWORDBREAKPROCEX")) { _ = EDITWORDBREAKPROCEX; }
if (@hasDecl(@This(), "EDITSTREAMCALLBACK")) { _ = EDITSTREAMCALLBACK; }
if (@hasDecl(@This(), "PCreateTextServices")) { _ = PCreateTextServices; }
if (@hasDecl(@This(), "PShutdownTextServices")) { _ = PShutdownTextServices; }
if (@hasDecl(@This(), "DTT_CALLBACK_PROC")) { _ = DTT_CALLBACK_PROC; }
if (@hasDecl(@This(), "EDITWORDBREAKPROCA")) { _ = EDITWORDBREAKPROCA; }
if (@hasDecl(@This(), "EDITWORDBREAKPROCW")) { _ = EDITWORDBREAKPROCW; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
deps/zigwin32/win32/ui/controls.zig
|
const std = @import("std");
const DOUBLE_QUOTE = '\"';
const BACKSLASH = '\\';
const BACKSPACE = 0x08;
const TAB = '\t';
const NEWLINE = '\n';
const FORM_FEED = 0x0C;
const CARRIAGE_RETURN = '\r';
const HEX_DIGITS = [_]u8{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/// Escapes a UTF-8 encoded code point using JSON escape sequences.
pub fn escapeChar(codepoint: u21, writer: anytype) !void {
switch (codepoint) {
DOUBLE_QUOTE => try writer.writeAll("\\\""),
BACKSLASH => try writer.writeAll("\\\\"),
BACKSPACE => try writer.writeAll("\\b"),
TAB => try writer.writeAll("\\t"),
NEWLINE => try writer.writeAll("\\n"),
FORM_FEED => try writer.writeAll("\\f"),
CARRIAGE_RETURN => try writer.writeAll("\\r"),
else => switch (codepoint) {
0x00...0x1F, 0x7F, 0x2028, 0x2029 => {
try writer.writeAll(&[_]u8{
'\\',
'u',
HEX_DIGITS[codepoint >> 12 & 0xF],
HEX_DIGITS[codepoint >> 8 & 0xF],
HEX_DIGITS[codepoint >> 4 & 0xF],
HEX_DIGITS[codepoint & 0xF],
});
},
else => if (codepoint > 0xFFFF) {
std.debug.assert(codepoint <= 0x10FFFF);
const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;
const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;
try writer.writeAll(&[_]u8{
'\\',
'u',
HEX_DIGITS[high >> 12 & 0xF],
HEX_DIGITS[high >> 8 & 0xF],
HEX_DIGITS[high >> 4 & 0xF],
HEX_DIGITS[high & 0xF],
'\\',
'u',
HEX_DIGITS[low >> 12 & 0xF],
HEX_DIGITS[low >> 8 & 0xF],
HEX_DIGITS[low >> 4 & 0xF],
HEX_DIGITS[low & 0xF],
});
} else {
@panic("Received code point that does not require escaping.");
},
},
}
}
/// Escapes characters of a UTF-8 encoded string using JSON escape sequences.
pub fn escape(bytes: []const u8, writer: anytype, formatter: anytype) !void {
var i: usize = 0;
var start: usize = 0;
while (i < bytes.len) : (i += 1) {
const byte = bytes[i];
const length = std.unicode.utf8ByteSequenceLength(byte) catch unreachable;
const codepoint = std.unicode.utf8Decode(bytes[i .. i + length]) catch unreachable;
// Skip code points that do not require escaping.
switch (codepoint) {
0x00...0x1F, DOUBLE_QUOTE, BACKSLASH, 0x7F, 0x2028, 0x2029 => {},
else => if (codepoint <= 0xFFFF) {
i += length - 1;
continue;
},
}
// Write out any buffered non-escaped code points.
if (start < i) {
try formatter.writeRawFragment(writer, bytes[start..i]);
}
// Escape and write out the current code point.
try formatter.writeCharEscape(writer, codepoint);
i += length - 1;
start = i + 1;
}
// If the input string is suffixed by code points that do not require
// escaping, then they've been buffered, but not written. So, we must write
// them out.
if (start != bytes.len) {
try formatter.writeRawFragment(writer, bytes[start..]);
}
}
|
src/ser/impl/formatter/details/escape.zig
|
const std = @import("std");
pub fn Stalloc(comptime B: type, comptime T: type, comptime S: usize) type {
return struct {
entries: [S]Entry,
const Self = @This();
const Entry = struct {
in_use: bool,
index: usize,
belongs_to: *B,
value: T,
};
pub const Iterator = struct {
stalloc: *Self,
index: usize,
pub fn next(it: *Iterator) ?*T {
while (it.index < it.stalloc.entries.len) {
var entry: *Entry = &it.stalloc.entries[it.index];
if (entry.in_use) {
it.index += 1;
return &entry.value;
}
it.index += 1;
}
return null;
}
pub fn reset(it: *Iterator) void {
it.index = 0;
}
};
pub fn new(self: *Self, belongs_to: *B) !*T {
var i: usize = 0;
while (i < S) {
var e: *Entry = &self.entries[i];
if (e.in_use == false) {
e.index = i;
e.in_use = true;
e.belongs_to = belongs_to;
return &e.value;
} else {
i = i + 1;
continue;
}
}
return error.StallocExhausted;
}
pub fn deinit(self: *Self, t: *T) usize {
var entry: *Entry = @fieldParentPtr(Entry, "value", t);
entry.in_use = false;
return entry.index;
}
pub fn releaseBelongingTo(self: *Self, b: *B) !void {
var i: usize = 0;
while (i < S) {
var entry: *Entry = &self.entries[i];
if (entry.in_use and entry.belongs_to == b) {
entry.in_use = false;
entry.value.deinit() catch |err| {
if (std.builtin.mode == std.builtin.Mode.Debug) {
return err;
} else {
std.debug.warn("warning: error in releaseBelongingTo\n", .{});
}
};
}
i = i + 1;
}
}
pub fn getAtIndex(self: *Self, index: usize) ?*T {
if (index < 0 and index >= S) {
return null;
}
if (self.entries[index].in_use == false) {
return null;
}
var e: *Entry = &self.entries[index];
return &e.value;
}
// TODO: is this safe?
pub fn getIndexOf(self: *Self, t: *T) usize {
var entry: *Entry = @fieldParentPtr(Entry, "value", t);
return entry.index;
}
pub fn freeCount(self: *Self) usize {
var i: usize = 0;
var count: usize = 0;
while (i < S) {
var entry: *Entry = &self.entries[i];
if (!entry.in_use) {
count += 1;
}
i += 1;
}
return count;
}
pub fn iterator(self: *Self) Iterator {
return Iterator{
.stalloc = self,
.index = 0,
};
}
};
}
const TestClient = struct {
i: u32,
};
const Payload = struct {
data: i32,
pub fn deinit(self: *Payload) !void {
self.data = 0;
}
};
var memory: Stalloc(TestClient, Payload, 4) = undefined;
test "stalloc test" {
var test_client_1 = TestClient{
.i = 1,
};
var test_client_2 = TestClient{
.i = 2,
};
std.debug.assert(memory.freeCount() == 4);
var x1 = try memory.new(&test_client_1);
std.debug.assert(memory.freeCount() == 3);
var x2 = try memory.new(&test_client_1);
std.debug.assert(memory.freeCount() == 2);
var x3 = try memory.new(&test_client_2);
std.debug.assert(memory.freeCount() == 1);
var x4 = try memory.new(&test_client_2);
std.debug.assert(memory.freeCount() == 0);
memory.deinit(x1);
std.debug.assert(memory.freeCount() == 1);
x1 = try memory.new(&test_client_1);
std.debug.assert(memory.freeCount() == 0);
var a: anyerror!*Payload = memory.new(&test_client_1);
if (a) |_| {} else |err| {
std.debug.assert(err == error.StallocExhausted);
}
try memory.releaseBelongingTo(&test_client_1);
std.debug.assert(memory.freeCount() == 2);
}
|
src/stalloc.zig
|
const std = @import("std");
pub const wasm = @import("log_wasm.zig");
const builtin = @import("builtin");
const UseStd = !builtin.target.isWasm();
const UseTimer = builtin.mode == .Debug and true;
var timer: ?std.time.Timer = null;
fn initTimerOnce() void {
if (timer == null) {
timer = std.time.Timer.start() catch unreachable;
}
}
pub fn scoped(comptime Scope: @Type(.EnumLiteral)) type {
return struct {
pub fn debug(comptime format: []const u8, args: anytype) void {
if (UseStd) {
if (UseTimer) {
initTimerOnce();
const elapsed = timer.?.read();
const secs = elapsed / 1000000000;
const msecs = (elapsed % 1000000000)/1000000;
std.log.scoped(Scope).debug("{}.{}: " ++ format, .{secs, msecs} ++ args);
} else {
std.log.scoped(Scope).debug(format, args);
}
} else {
wasm.scoped(Scope).debug(format, args);
}
}
pub fn info(comptime format: []const u8, args: anytype) void {
if (UseStd) {
std.log.scoped(Scope).info(format, args);
} else {
wasm.scoped(Scope).info(format, args);
}
}
pub fn warn(comptime format: []const u8, args: anytype) void {
if (UseStd) {
std.log.scoped(Scope).warn(format, args);
} else {
wasm.scoped(Scope).warn(format, args);
}
}
pub fn err(comptime format: []const u8, args: anytype) void {
if (UseStd) {
std.log.scoped(Scope).err(format, args);
} else {
wasm.scoped(Scope).err(format, args);
}
}
};
}
const default = if (UseStd) std.log.default else wasm.scoped(.default);
pub fn debug(comptime format: []const u8, args: anytype) void {
default.info(format, args);
}
pub fn info(comptime format: []const u8, args: anytype) void {
default.info(format, args);
}
pub fn err(comptime format: []const u8, args: anytype) void {
default.err(format, args);
}
/// Exported for C to call into zig.
export fn zig_log_debug(msg: [*c]const u8) void {
debug("{s}", .{msg});
}
|
stdx/log.zig
|
const std = @import("std");
const math = std.math;
const mem = std.mem;
const meta = std.meta;
// XXX: Why is this necessary?
comptime {
_ = ColorblindnessFlavor;
_ = RGB;
_ = HSV;
_ = HSL;
_ = XYZ;
_ = LMS;
_ = hsl_to_rgb;
_ = rgb_to_hsv;
_ = rgb_to_hsl;
_ = rgb_to_xyz;
_ = hsv_to_rgb;
_ = xyz_to_rgb;
_ = xyz_to_lms;
_ = lms_adjust_for_colorblindness;
_ = lms_to_xyz;
}
pub const ColorblindnessFlavor = extern enum {
Protanopia = 1, Deuteranopia = 2, Tritanopia = 3
};
// XXX: stahp reformatting my space alignment !!!
// {{{
pub const RGB = extern struct {
r: u8,
g: u8,
b: u8,
pub fn to_hsv(rgb: *const RGB) HSV {
// XXX: guh type inference is a thing
var hue: f64 = 0.0;
var saturation: f64 = 0.0;
var value: f64 = 0.0;
const tr = @intToFloat(f64, rgb.r) / 255.0;
const tg = @intToFloat(f64, rgb.g) / 255.0;
const tb = @intToFloat(f64, rgb.b) / 255.0;
// XXX: why is max in mem
const Cmax = mem.max(f64, &[_]f64{ tr, tg, tb });
const Cmin = mem.min(f64, &[_]f64{ tr, tg, tb });
const C = Cmax - Cmin;
value = Cmax;
saturation = if (Cmax == 0) 0 else C / Cmax;
if (C == 0.0) {
hue = 0;
} else if (Cmax == tr) {
hue = 60.0 * (((tg - tb) / C) + 0.0);
} else if (Cmax == tg) {
hue = 60.0 * (((tb - tr) / C) + 2.0);
} else if (Cmax == tb) {
hue = 60.0 * (((tr - tg) / C) + 4.0);
}
if (hue < 0.0) hue += 360.0;
return .{
.h = hue,
.s = saturation * 100,
.v = value * 100,
};
}
pub fn to_hsl(rgb: *const RGB) HSL {
var hsl: HSL = HSL{ .h = 0.0, .s = 0.0, .l = 0.0 };
const tr = @intToFloat(f64, rgb.r) / 255.0;
const tg = @intToFloat(f64, rgb.g) / 255.0;
const tb = @intToFloat(f64, rgb.b) / 255.0;
// XXX: Why do I have to pass the type along everywhere
const Cmax = mem.max(f64, &[_]f64{ tr, tg, tb });
const Cmin = mem.min(f64, &[_]f64{ tr, tg, tb });
const C = Cmax - Cmin;
hsl.l = (Cmax + Cmin) / 2;
if (C == 0) { // achromatic
hsl.h = 0.0;
hsl.s = 0.0;
} else {
hsl.s = C / (1.0 - math.fabs(2.0 * hsl.l - 1.0));
hsl.h = if (Cmax == tr)
(tg - tb) / C
else if (Cmax == tg)
(tb - tr) / C + 2.0
else if (Cmax == tb)
(tr - tg) / C + 4.0
else
@panic("The sky is falling~");
hsl.h = @mod(hsl.h / 6.0, 1.0);
}
hsl.h *= 360.0;
hsl.s *= 100.0;
hsl.l *= 100.0;
return hsl;
}
pub fn expectNearlyEq(want: RGB, have: RGB) void {
if ((@as(isize, want.r) - @as(isize, have.r)) >= 1.0) {
std.debug.panic("Expect RGB.r {}, found {}", .{ want.r, have.r });
}
if ((@as(isize, want.g) - @as(isize, have.g)) >= 1.0) {
std.debug.panic("Expect RGB.g {}, found {}", .{ want.g, have.g });
}
if ((@as(isize, want.b) - @as(isize, have.b)) >= 1.0) {
std.debug.panic("Expect RGB.b {}, found {}", .{ want.b, have.b });
}
}
pub fn to_xyz(rgb: *const RGB) XYZ {
var r = @intToFloat(f64, rgb.r) / 255.0;
var g = @intToFloat(f64, rgb.g) / 255.0;
var b = @intToFloat(f64, rgb.b) / 255.0;
r = if (r > 0.04045) math.pow(f64, ((r + 0.055) / 1.055), 2.4) else r / 12.92;
g = if (g > 0.04045) math.pow(f64, ((g + 0.055) / 1.055), 2.4) else g / 12.92;
b = if (b > 0.04045) math.pow(f64, ((b + 0.055) / 1.055), 2.4) else b / 12.92;
// observer = 2°; illuminant = D65
return .{
.x = r * 0.4124 + g * 0.3576 + b * 0.1805,
.y = r * 0.2126 + g * 0.7152 + b * 0.0722,
.z = r * 0.0193 + g * 0.1192 + b * 0.9505,
};
}
pub fn as_hex(s: *RGB) usize {
return @as(usize, s.r) << 16 | @as(usize, s.g) << 8 | @as(usize, s.b);
}
pub fn from_hex(rgb: usize) RGB {
return .{
.r = @intCast(u8, (rgb >> 16) & 0xFF),
.g = @intCast(u8, (rgb >> 08) & 0xFF),
.b = @intCast(u8, (rgb >> 00) & 0xFF),
};
}
}; // XXX: et tu, zig?
// }}}
// Hue, Saturation, Value
// {{{
pub const HSV = extern struct {
h: f64,
s: f64,
v: f64,
pub fn new(h: f64, s: f64, v: f64) HSV {
return .{ .h = h, .s = s, .v = v };
}
pub fn expectNearlyEq(want: HSV, have: HSV) void {
if ((want.h - have.h) >= 1.0) {
std.debug.panic("Expect HSV.h {}, found {}", .{ want.h, have.h });
}
if ((want.s - have.s) >= 1.0) {
std.debug.panic("Expect HSV.s {}, found {}", .{ want.s, have.s });
}
if ((want.v - have.v) >= 1.0) {
std.debug.panic("Expect HSV.v {}, found {}", .{ want.v, have.v });
}
}
pub fn to_rgb(hsv: *const HSV) RGB {
const h = hsv.h;
const s = hsv.s / 100;
const v = hsv.v / 100;
if (s <= 0.0) {
return .{
.r = @floatToInt(u8, v),
.g = @floatToInt(u8, v),
.b = @floatToInt(u8, v),
};
}
const hh = (if (h >= 360.0) 0.0 else h) / 60.0;
const i = @floatToInt(usize, hh);
const ff = hh - @intToFloat(f64, i);
const p = v * (1.0 - s);
const q = v * (1.0 - (s * ff));
const t = v * (1.0 - (s * (1.0 - ff)));
var tr: f64 = 0.0;
var tg: f64 = 0.0;
var tb: f64 = 0.0;
// XXX: switch cases are lovely
switch (@floatToInt(usize, math.round(h / 60.0))) {
0 => {
tr = v;
tg = t;
tb = p;
},
1 => {
tr = q;
tg = v;
tb = p;
},
2 => {
tr = p;
tg = v;
tb = t;
},
3 => {
tr = p;
tg = q;
tb = v;
},
else => {
tr = v;
tg = p;
tb = q;
},
}
return .{
.r = @floatToInt(u8, math.round(tr * 255.0)),
.g = @floatToInt(u8, math.round(tg * 255.0)),
.b = @floatToInt(u8, math.round(tb * 255.0)),
};
}
};
// }}}
// Hue, Saturation, Lightness
/// {{{
pub const HSL = extern struct {
h: f64,
s: f64,
l: f64,
pub fn new(h: f64, s: f64, l: f64) HSL {
return .{ .h = h, .s = s, .l = l };
}
fn _hue_to_rgb(p: f64, q: f64, _t: f64) f64 {
// XXX: let me assign to my params!
var t = _t;
if (t < 0.0) t += 1.0;
if (t > 1.0) t -= 1.0;
if (t < 1.0 / 6.0)
return p + (q - p) * 6.0 * t;
if (t < 1.0 / 2.0)
return q;
if (t < 2.0 / 3.0)
return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
return p;
}
pub fn to_rgb(hsl: *const HSL) RGB {
const h = hsl.h / 360.0;
const s = hsl.s / 100.0;
const l = hsl.l / 100.0;
var r: f64 = 0.0;
var g: f64 = 0.0;
var b: f64 = 0.0;
if (s == 0.0) { // achromatic
r = l;
g = l;
b = l;
} else {
var q = if (l < 0.5) l * (1.0 + s) else l + s - l * s;
var p = 2.0 * l - q;
r = _hue_to_rgb(p, q, h + (1.0 / 3.0));
g = _hue_to_rgb(p, q, h);
b = _hue_to_rgb(p, q, h - (1.0 / 3.0));
}
return .{
.r = @floatToInt(u8, math.round(r * 255.0)),
.g = @floatToInt(u8, math.round(g * 255.0)),
.b = @floatToInt(u8, math.round(b * 255.0)),
};
}
pub fn expectNearlyEq(want: HSL, have: HSL) void {
if ((want.h - have.h) >= 1.0) {
std.debug.panic("Expect hsl({}, {}, {}), found hsl({}, {}, {})", .{ want.h, want.s, want.l, have.h, have.s, have.l });
}
if ((want.s - have.s) >= 1.0) {
std.debug.panic("Expect hsl({}, {}, {}), found hsl({}, {}, {})", .{ want.h, want.s, want.l, have.h, have.s, have.l });
}
if ((want.l - have.l) >= 1.0) {
std.debug.panic("Expect hsl({}, {}, {}), found hsl({}, {}, {})", .{ want.h, want.s, want.l, have.h, have.s, have.l });
}
}
};
// }}}
// CIE 1931 colorspace
// https://en.wikipedia.org/wiki/CIE_1931_color_space
// {{{
pub const XYZ = extern struct {
x: f64,
y: f64,
z: f64,
pub fn new(x: f64, y: f64, z: f64) XYZ {
return .{ .x = x, .y = y, .z = z };
}
pub fn to_lms(xyz: *const XYZ) LMS {
return .{
.l = 0.38971 * xyz.x + 0.68898 * xyz.y - 0.07868 * xyz.z,
.m = -0.22981 * xyz.x + 1.18340 * xyz.y + 0.04641 * xyz.z,
.s = 0.00000 * xyz.x + 0.00000 * xyz.y + 1.00000 * xyz.z,
};
}
fn _adj(f: f64) f64 {
// if (math.fabs(f) < 0.0031308) {
// return 12.92 * f;
// }
// return 1.055 * math.pow(f64, f, 0.41666) - 0.055;
return f;
}
pub fn to_rgb(xyz: *const XYZ) RGB {
const r = 3.2404542 * xyz.x - 1.5371385 * xyz.y - 0.4985314 * xyz.z;
const g = -0.9692660 * xyz.x + 1.8760108 * xyz.y + 0.0415560 * xyz.z;
const b = 0.0556434 * xyz.x - 0.2040259 * xyz.y + 1.0572252 * xyz.z;
return .{
.r = @floatToInt(u8, math.clamp(math.round(r * 255), 0, 255)),
.g = @floatToInt(u8, math.clamp(math.round(g * 255), 0, 255)),
.b = @floatToInt(u8, math.clamp(math.round(b * 255), 0, 255)),
};
}
pub fn expectNearlyEq(want: XYZ, have: XYZ) void {
const diff = .{ .x = want.x - have.x, .y = want.y - have.y, .z = want.z - have.z };
if (diff.x >= 1.0 or diff.y >= 1.0 or diff.z >= 1.0) {
std.debug.panic("Expect xyz({:.2}, {:.2}, {:.2}), found xyz({:.2}, {:.2}, {:.2})", .{ want.x, want.y, want.z, have.x, have.y, have.z });
}
}
};
// }}}
// LMS (long, medium, short) colorspace
// https://en.wikipedia.org/wiki/LMS_color_space
// {{{
pub const LMS = extern struct {
l: f64,
m: f64,
s: f64,
pub fn to_xyz(lms: *const LMS) XYZ {
return .{
.x = 1.91020 * lms.l - 1.112_120 * lms.m + 0.201_908 * lms.s,
.y = 0.37095 * lms.l + 0.629_054 * lms.m + 0.000_000 * lms.s,
.z = 0.00000 * lms.l + 0.000_000 * lms.m + 1.000_000 * lms.s,
};
}
// https://ixora.io/projects/colorblindness/color-blindness-simulation-research/
pub fn adjust_for_colorblindness(lms: *LMS, cb: ColorblindnessFlavor) LMS {
return switch (cb) {
.Protanopia => .{
// Missing L cones
.l = 1.051_182_94 * lms.m - 0.051_160_99 * lms.s,
.m = lms.m,
.s = lms.s,
},
.Deuteranopia => .{
// Missing M cones
.l = lms.l,
.m = 0.951_309_2 * lms.l + 0.048_669_92 * lms.s,
.s = lms.s,
},
.Tritanopia => .{
// Missing S cones
.l = lms.l,
.m = lms.m,
.s = -0.867_447_36 * lms.l + 1.867_270_89 * lms.m,
},
};
}
};
// }}}
// C wrapper functions, works around ABI problems
// {{{
// XXX: No C ABI, huh?
export fn rgb_to_hsv(rgb: *RGB, out: *HSV) void {
const tmp = rgb.to_hsv();
out.h = tmp.h;
out.s = tmp.s;
out.v = tmp.v;
}
export fn rgb_to_hsl(rgb: *RGB, out: *HSL) void {
const tmp = rgb.to_hsl();
out.h = tmp.h;
out.s = tmp.s;
out.l = tmp.l;
}
export fn rgb_to_xyz(rgb: *RGB, out: *XYZ) void {
const tmp = rgb.to_xyz();
out.x = tmp.x;
out.y = tmp.y;
out.z = tmp.z;
}
export fn hsv_to_rgb(hsv: *HSV, out: *RGB) void {
const tmp = hsv.to_rgb();
out.r = tmp.r;
out.g = tmp.g;
out.b = tmp.b;
}
export fn hsl_to_rgb(hsl: *HSL, out: *RGB) void {
const tmp = hsl.to_rgb();
out.r = tmp.r;
out.g = tmp.g;
out.b = tmp.b;
}
export fn xyz_to_rgb(xyz: *XYZ, out: *RGB) void {
const tmp = xyz.to_rgb();
out.r = tmp.r;
out.g = tmp.g;
out.b = tmp.b;
}
export fn xyz_to_lms(xyz: *XYZ, out: *LMS) void {
const tmp = xyz.to_lms();
out.l = tmp.l;
out.m = tmp.m;
out.s = tmp.s;
}
export fn lms_adjust_for_colorblindness(lms: *LMS, cb: ColorblindnessFlavor, out: *LMS) void {
const tmp = lms.adjust_for_colorblindness(cb);
out.l = tmp.l;
out.m = tmp.m;
out.s = tmp.s;
}
export fn lms_to_xyz(lms: *LMS, out: *XYZ) void {
const tmp = lms.to_xyz();
out.x = tmp.x;
out.y = tmp.y;
out.z = tmp.z;
}
// }}}
// Tests
// {{{
test "hsv->rgb" {
RGB.from_hex(0x1fc8d1).expectNearlyEq(HSV.new(183, 85, 82).to_rgb());
RGB.from_hex(0x8c3183).expectNearlyEq(HSV.new(306, 65, 55).to_rgb());
RGB.from_hex(0xf2f5a6).expectNearlyEq(HSV.new(62, 32, 96).to_rgb());
RGB.from_hex(0x32a852).expectNearlyEq(HSV.new(136, 70, 66).to_rgb());
}
test "rgb->hsv" {
HSV.new(183, 85, 82).expectNearlyEq(RGB.from_hex(0x1fc8d1).to_hsv());
HSV.new(306, 65, 55).expectNearlyEq(RGB.from_hex(0x8c3183).to_hsv());
HSV.new(62, 32, 96).expectNearlyEq(RGB.from_hex(0xf2f5a6).to_hsv());
HSV.new(136, 70, 66).expectNearlyEq(RGB.from_hex(0x32a852).to_hsv());
}
test "hsl->rgb" {
RGB.from_hex(0xe6b3b3).expectNearlyEq(HSL.new(359, 50, 80).to_rgb());
RGB.from_hex(0x1fc8d1).expectNearlyEq(HSL.new(183, 74, 47).to_rgb());
RGB.from_hex(0xffffff).expectNearlyEq(HSL.new(0, 0, 100).to_rgb());
RGB.from_hex(0x8c3183).expectNearlyEq(HSL.new(306, 48, 37).to_rgb());
RGB.from_hex(0xf2f5a6).expectNearlyEq(HSL.new(62, 79, 81).to_rgb());
RGB.from_hex(0x32a852).expectNearlyEq(HSL.new(136, 54, 43).to_rgb());
}
test "rgb->hsl" {
HSL.new(0, 50, 80).expectNearlyEq(RGB.from_hex(0xe6b3b3).to_hsl());
HSL.new(183, 74, 47).expectNearlyEq(RGB.from_hex(0x1fc8d1).to_hsl());
HSL.new(0, 0, 100).expectNearlyEq(RGB.from_hex(0xffffff).to_hsl());
HSL.new(306, 48, 37).expectNearlyEq(RGB.from_hex(0x8c3183).to_hsl());
HSL.new(62, 79, 81).expectNearlyEq(RGB.from_hex(0xf2f5a6).to_hsl());
HSL.new(136, 54, 43).expectNearlyEq(RGB.from_hex(0x32a852).to_hsl());
}
test "xyz->rgb" {
RGB.from_hex(0xffffff).expectNearlyEq(XYZ.new(0.9505, 1.0000, 1.08900).to_rgb());
RGB.from_hex(0xff0000).expectNearlyEq(XYZ.new(0.4123, 0.2126, 0.01933).to_rgb());
}
test "rgb->hsl->rgb" {
var hue: usize = 359;
while (hue > 0) : (hue -= 1) {
const hsl1 = HSL.new(@intToFloat(f64, hue), 50, 80);
const rgb1 = hsl1.to_rgb();
const hsl2 = rgb1.to_hsl();
const rgb2 = hsl2.to_rgb();
rgb1.expectNearlyEq(rgb2);
}
}
test "rgb->xyz->rgb" {
var hue: usize = 359;
while (hue > 0) : (hue -= 1) {
const hsl = HSL.new(@intToFloat(f64, hue), 50, 80);
const rgb1 = hsl.to_rgb();
const xyz = rgb1.to_xyz();
const rgb2 = xyz.to_rgb();
rgb1.expectNearlyEq(rgb2);
}
}
test "rgb->xyz->lms->xyz->rgb" {
var hue: usize = 359;
while (hue > 0) : (hue -= 1) {
const hsl = HSL.new(@intToFloat(f64, hue), 50, 80);
const rgb1 = hsl.to_rgb();
const xyz1 = rgb1.to_xyz();
const lms = xyz1.to_lms();
const xyz2 = lms.to_xyz();
const rgb2 = xyz2.to_rgb();
xyz1.expectNearlyEq(xyz2);
rgb1.expectNearlyEq(rgb2);
}
}
// }}}
// XXX: test framework stops on first failed test?
|
color.zig
|