code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const Interpreter = @import("Interpreter.zig"); const utils = @import("utils.zig"); const zig_arg = @import("zig-arg"); const pga = std.heap.page_allocator; const flag = zig_arg.flag; const Command = zig_arg.Command; const usage = \\ Usage: zbfi [option] \\ \\ Option: \\ --file, -f <NAME> Interpret from file \\ --help, -h Show this help \\ \\ To run REPL mode run without any option ; pub fn main() anyerror!void { var zbfi = try initCliArgs(pga); defer zbfi.deinit(); var args = try zbfi.parseProcess(); defer args.deinit(); if (args.isPresent("help")) { std.debug.print("{s}\n", .{usage}); return; } if (args.valueOf("file")) |file_name| { var src = readSrcFile(pga, file_name) catch |err| switch (err) { error.InvalidFileFormat => { std.debug.print("Error: Invalid file format\n", .{}); std.process.exit(1); }, error.FileNotFound => { std.debug.print("Error: Src file not found\n", .{}); std.process.exit(1); }, else => |e| return e, }; _ = Interpreter.interpret(pga, src); return; } try runInteractiveMode(pga); } fn initCliArgs(allocator: std.mem.Allocator) !Command { var zbfi = Command.new(allocator, "zbfi"); try zbfi.addArg(flag.boolean("help", 'h')); try zbfi.addArg(flag.argOne("file", 'f')); return zbfi; } fn readSrcFile(allocator: std.mem.Allocator, file_path: []const u8) ![]u8 { if (!isValidExtension(file_path)) return error.InvalidFileFormat; var file = try std.fs.cwd().openFile(file_path, .{ .read = true }); defer file.close(); var content = try file.reader().readAllAlloc(allocator, 1024); return content; } fn isValidExtension(file_path: []const u8) bool { const file_ext = std.fs.path.extension(file_path); if (!std.mem.eql(u8, file_ext, ".b") and !std.mem.eql(u8, file_ext, ".bf")) return false; return true; } fn runInteractiveMode(allocator: std.mem.Allocator) !void { std.debug.print( \\ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— \\ β•šβ•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘ \\ β–‘β–‘β–ˆβ–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•¦β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ•‘ \\ β–ˆβ–ˆβ•”β•β•β•β–‘β–‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β–‘β–‘β–ˆβ–ˆβ•‘ \\ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•¦β•β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘ \\ β•šβ•β•β•β•β•β•β•β•šβ•β•β•β•β•β•β–‘β•šβ•β•β–‘β–‘β–‘β–‘β–‘β•šβ•β• \\ \\ Welcome to Zbfi REPL mode \\ Run ;quit to close REPL mode \\ , .{}); while (true) { std.debug.print("> ", .{}); var src_input = try utils.stdin.readUntilDelimiterOrEofAlloc(allocator, '\n', 1024); if (src_input) |src| { if (std.mem.eql(u8, src, ";quit")) { break; } _ = Interpreter.interpret(allocator, src); std.debug.print("\n", .{}); } } std.debug.print("[Interpreter Ended]\n", .{}); }
src/main.zig
const fun = @import("fun"); const std = @import("std"); const debug = std.debug; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const scan = fun.scan.scan; pub fn main() !void { const stdin = &(try io.getStdIn()).inStream().stream; const stdout = &(try io.getStdOut()).outStream().stream; var ps = io.PeekStream(1, os.File.InStream.Error).init(stdin); var direct_allocator = heap.DirectAllocator.init(); const allocator = &direct_allocator.allocator; defer direct_allocator.deinit(); const claims = try readClaims(allocator, &ps); defer allocator.free(claims); const overlaps = try fabricOverlaps(allocator, claims); defer allocator.free(overlaps); try stdout.print("{}\n", count(usize, overlaps, above1)); const claim = firstNoneIntersectingClaim(claims) orelse return error.NoPerfectClaim; try stdout.print("{}\n", claim.id); } fn readClaims(allocator: *mem.Allocator, ps: var) ![]Claim { var claims = std.ArrayList(Claim).init(allocator); defer claims.deinit(); while (scan(ps, "#{} @ {},{}: {}x{}\n", Claim)) |claim| { try claims.append(claim); } else |err| switch (err) { error.EndOfStream => {}, else => return err, } return claims.toOwnedSlice(); } fn fabricOverlaps(allocator: *mem.Allocator, claims: []const Claim) ![]usize { var fabric_width: usize = 0; var fabric_height: usize = 0; for (claims) |claim| { fabric_width = math.max(fabric_width, claim.width + claim.x); fabric_height = math.max(fabric_height, claim.height + claim.y); } const fabric = try allocator.alloc(usize, fabric_width * fabric_height); errdefer allocator.free(fabric); mem.set(usize, fabric, 0); for (claims) |claim| { var x: usize = claim.x; while (x < claim.width + claim.x) : (x += 1) { var y: usize = claim.y; while (y < claim.height + claim.y) : (y += 1) { fabric[x + (fabric_width * y)] += 1; } } } return fabric; } fn count(comptime T: type, slice: []const T, predicate: fn (T) bool) usize { var res: usize = 0; for (slice) |item| res += @boolToInt(predicate(item)); return res; } fn above1(i: usize) bool { return i > 1; } fn firstNoneIntersectingClaim(claims: []const Claim) ?Claim { outer: for (claims) |a, i| { for (claims) |b, j| { if (i == j) continue; if (a.intersects(b)) continue :outer; } return a; } return null; } const Claim = struct { id: usize, x: usize, y: usize, width: usize, height: usize, fn intersects(a: Claim, b: Claim) bool { const Point = struct { x: usize, y: usize, }; const top_left = Point{ .x = math.max(a.x, b.x), .y = math.max(a.y, b.y), }; const bot_right = Point{ .x = math.min(a.x + a.width, b.x + b.width), .y = math.min(a.y + a.height, b.y + b.height), }; return top_left.x < bot_right.x and top_left.y < bot_right.y; } };
src/day3.zig
const std = @import("std"); const mem = std.mem; const warn = std.debug.warn; const gallocator = std.heap.page_allocator; pub fn Graph(comptime T: type) type { return struct { N: usize, connected: usize, root: ?*Node, vertices: ?std.StringHashMap(*Node), graph: ?std.AutoHashMap(*Node, std.ArrayList(*Edge)), allocator: *mem.Allocator, const Self = @This(); pub const Node = struct { name: []const u8, data: T, pub fn init(n: []const u8, d: T) Node { return Node{ .name = n, .data = d }; } }; pub const Edge = struct { node: *Node, weight: u32, pub fn init(n1: *Node, w: u32) Edge { return Edge { .node = n1, .weight = w }; } }; pub fn init(alloc: *std.mem.Allocator) Self { return Self{ .N = 0, .connected = 0, .root = undefined, .vertices = undefined, .graph = undefined, .allocator = alloc }; } pub fn deinit(self: *Self) void { for (self.graph.?.entries) |entry| { if (entry.used == true) { self.allocator.destroy(entry.kv.key); for (entry.kv.value.items) |v| { self.allocator.destroy(v.node); self.allocator.destroy(v); } } } self.graph.?.deinit(); for (self.vertices.?.entries) |entry| { if (entry.used == true) { self.allocator.destroy(entry.kv.value); } } self.vertices.?.deinit(); self.N = 0; } pub fn addVertex(self: *Self, n: []const u8, d: T) !void { if (self.N == 0) { var rt = try self.allocator.create(Node); errdefer self.allocator.destroy(rt); rt.* = Node.init(n, d); self.root = rt; self.vertices = std.StringHashMap(*Node).init(self.allocator); _ = try self.vertices.?.put(rt.name, rt); self.graph = std.AutoHashMap(*Node, std.ArrayList(*Edge)).init(self.allocator); _ = try self.graph.?.put(rt, std.ArrayList(*Edge).init(self.allocator)); self.N += 1; return; } if (self.vertices.?.contains(n) == false) { var node = try self.allocator.create(Node); errdefer self.allocator.destroy(node); node.* = Node.init(n, d); _ = try self.vertices.?.put(node.name, node); _ = try self.graph.?.put(node, std.ArrayList(*Edge).init(self.allocator)); } self.N += 1; } pub fn addEdge(self: *Self, n1: []const u8, d1: T, n2: []const u8, d2: T, w: u32) !void { if (self.N == 0 or self.vertices.?.contains(n1) == false ) { try self.addVertex(n1, d1); } if (self.vertices.?.contains(n2) == false) { try self.addVertex(n2, d2); } var node1: *Node = self.vertices.?.getValue(n1).?; var node2: *Node = self.vertices.?.getValue(n2).?; var arr: std.ArrayList(*Edge) = self.graph.?.getValue(node1).?; var edge = try self.allocator.create(Edge); errdefer self.allocator.destroy(edge); edge.* = Edge.init(node2, w); try arr.append(edge); _ = try self.graph.?.put(node1, arr); } pub fn print(self: *Self) void { warn("\r\n", .{}); warn("Size: {}\r\n", .{self.N}); warn("\r\n", .{}); warn("Root: {}\r\n", .{self.root}); warn("\r\n", .{}); warn("Vertices:\r\n", .{}); for (self.vertices.?.entries) |entry| { if (entry.used == true) { warn("\r\n{}\r\n", .{entry.kv.key}); } } warn("\r\n", .{}); warn("Graph:\r\n", .{}); for (self.graph.?.entries) |entry| { if (entry.used == true) { warn("\r\nConnections: {} =>", .{entry.kv.key}); for (entry.kv.value.items) |v, i| { warn(" {} =>", .{v.*}); } warn("|| \r\n", .{}); } } warn("\r\n", .{}); } fn topoDriver(self: *Self, node: []const u8, visited: *std.StringHashMap(i32), stack: *std.ArrayList(*Node)) !bool { // In the process of visiting this vertex, we reach the same vertex again. // Return to stop the process. (#cond1) if (visited.getValue(node).? == 1) { return false; } // Finished visiting this vertex, it is now marked 2. (#cond2) if (visited.getValue(node).? == 2) { return true; } // Color the node 1, indicating that it is being processed, and initiate a loop // to visit all its neighbors. If we reach the same vertex again, return (#cond1) _ = try visited.put(node, 1); var nodePtr: *Node = self.vertices.?.getValue(node).?; var neighbors: std.ArrayList(*Edge) = self.graph.?.getValue(nodePtr).?; for (neighbors.items) |n| { // warn("\r\n nbhr: {} ", .{n}); if (visited.getValue(n.node.name).? == 0 ) { var check: bool = self.topoDriver(n.node.name, visited, stack) catch unreachable; if (check == false) { return false; } } } // Finish processing the current node and mark it 2. _ = try visited.put(node, 2); // Add node to stack of visited nodes. try stack.append(nodePtr); // warn("\r\n reach {} ", .{nodePtr}); return true; } pub fn topoSort(self: *Self) !std.ArrayList(*Node) { var visited = std.StringHashMap(i32).init(self.allocator); defer visited.deinit(); var stack = std.ArrayList(*Node).init(self.allocator); defer stack.deinit(); var result = std.ArrayList(*Node).init(self.allocator); // Initially, color all the nodes 0, to mark them unvisited. for (self.vertices.?.entries) |entry| { if (entry.used == true) { _ = try visited.put(entry.kv.key, 0); } } for (self.vertices.?.entries) |entry| { if (entry.used == true) { if (visited.getValue(entry.kv.key).? == 0 ) { var check: bool = self.topoDriver(entry.kv.key, &visited, &stack) catch unreachable; if (check == false) { for (stack.items) |n| { try result.append(n); } return result; } self.connected += 1; } } } self.connected -= 1; for (stack.items) |n| { try result.append(n); } return result; } pub fn dfs(self: *Self) !std.ArrayList(*Node) { var visited = std.StringHashMap(i32).init(self.allocator); defer visited.deinit(); var result = std.ArrayList(*Node).init(self.allocator); // Initially, color all the nodes 0, to mark them unvisited. for (self.vertices.?.entries) |entry| { if (entry.used == true) { _ = try visited.put(entry.kv.key, 0); } } var stack = std.ArrayList(*Node).init(self.allocator); defer stack.deinit(); try stack.append(self.root.?); while (stack.items.len > 0) { var current: *Node = stack.pop(); var neighbors: std.ArrayList(*Edge) = self.graph.?.getValue(current).?; for (neighbors.items) |n| { // warn("\r\n nbhr: {} ", .{n}); if (visited.getValue(n.node.name).? == 0 ) { try stack.append(n.node); _ = try visited.put(n.node.name, 1); try result.append(n.node); } } } return result; } pub fn bfs(self: *Self) !std.ArrayList(*Node) { var visited = std.StringHashMap(i32).init(self.allocator); defer visited.deinit(); var result = std.ArrayList(*Node).init(self.allocator); // Initially, color all the nodes 0, to mark them unvisited. for (self.vertices.?.entries) |entry| { if (entry.used == true) { _ = try visited.put(entry.kv.key, 0); } } var qu = std.ArrayList(*Node).init(self.allocator); defer qu.deinit(); try qu.append(self.root.?); while (qu.items.len > 0) { var current: *Node = qu.orderedRemove(0); var neighbors: std.ArrayList(*Edge) = self.graph.?.getValue(current).?; for (neighbors.items) |n| { // warn("\r\n nbhr: {} ", .{n}); if (visited.getValue(n.node.name).? == 0 ) { try qu.append(n.node); _ = try visited.put(n.node.name, 1); try result.append(n.node); } } } return result; } // pub fn kruskal(self: *Self) !std.ArrayList(*Node) { // } pub const Element = struct { name: []const u8, distance: i32 }; pub fn minCompare(a: Element, b: Element) bool { return a.distance < b.distance; } pub fn dijikstra(self: *Self, src: []const u8, dst: []const u8) !std.ArrayList(Element) { var result = std.StringHashMap(i32).init(self.allocator); var path = std.ArrayList(Element).init(self.allocator); if ( (self.vertices.?.contains(src) == false) or (self.vertices.?.contains(dst) == false) ){ return path; } var source: *Node = self.vertices.?.getValue(src).?; var pq = std.PriorityQueue(Element).init(self.allocator, minCompare); defer pq.deinit(); var visited = std.StringHashMap(i32).init(self.allocator); defer visited.deinit(); var distances = std.StringHashMap(i32).init(self.allocator); defer distances.deinit(); var prev = std.StringHashMap(*Node).init(self.allocator); defer prev.deinit(); // Initially, push all the nodes into the distances hashmap with a distance of infinity. for (self.vertices.?.entries) |entry| { if (entry.used == true and !mem.eql(u8, source.name, entry.kv.key)) { _ = try distances.put(entry.kv.key, 9999); try pq.add(Element{.name= entry.kv.key, .distance= 9999}); } } _ = try distances.put(src, 0); try pq.add(Element{.name= source.name, .distance= 0}); while (pq.count() > 0) { var current: Element = pq.remove(); if (mem.eql(u8, current.name, dst)) { break; } if (!visited.contains(current.name)) { var currentPtr: *Node = self.vertices.?.getValue(current.name).?; var neighbors: std.ArrayList(*Edge) = self.graph.?.getValue(currentPtr).?; for (neighbors.items) |n| { // Update the distance values from all neighbors, to the current node // and obtain the shortest distance to the current node from all of its neighbors. var best_dist = distances.getValue(n.node.name).?; var n_dist = @intCast(i32, current.distance + @intCast(i32, n.weight)); // warn("\r\n n1 {} nbhr {} ndist {} best {}", .{current.node, n.node.name, n_dist, best_dist}); if (n_dist < best_dist) { // Shortest way to reach current node is through this neighbor. // Update the node's distance from source, and add it to prev. _ = try distances.put(n.node.name, n_dist); _ = try prev.put(n.node.name, currentPtr); // Update the priority queue with the new, shorter distance. var modIndex: usize = 0; for (pq.items) |item, i| { if (mem.eql(u8, item.name, n.node.name)) { modIndex = i; break; } } _ = pq.removeIndex(modIndex); try pq.add(Element{.name= n.node.name, .distance= n_dist}); } } // After updating all the distances to all neighbors, get the // best leading edge from the closest neighbor to this node. Mark that // distance as the best distance to this node, and add it to the results. var best = distances.getValue(current.name).?; _ = try result.put(current.name, best); _ = try visited.put(current.name, 1); } } // Path tracing, to return a list of nodes from src to dst. var x: []const u8 = dst; while(prev.contains(x)) { var temp: *Node = prev.getValue(x).?; try path.append(Element{.name= temp.name, .distance= result.getValue(temp.name).?}); x = temp.name; } return path; } pub const Pair = struct { n1: []const u8, n2: []const u8 }; pub fn prim(self: *Self, src: []const u8) !std.ArrayList(std.ArrayList(*Node)) { // Start with a vertex, and pick the minimum weight edge that belongs to that // vertex. Traverse the edge and then repeat the same procedure, till an entire // spannning tree is formed. var path = std.ArrayList(std.ArrayList(*Node)).init(self.allocator); if (self.vertices.?.contains(src) == false) { return path; } var source: *Node = self.vertices.?.getValue(src).?; var dest = std.ArrayList(Pair).init(self.allocator); defer dest.deinit(); var pq = std.PriorityQueue(Element).init(self.allocator, minCompare); defer pq.deinit(); var visited = std.StringHashMap(bool).init(self.allocator); defer visited.deinit(); var distances = std.StringHashMap(i32).init(self.allocator); defer distances.deinit(); var prev = std.StringHashMap(?std.ArrayList(*Node)).init(self.allocator); defer prev.deinit(); // Initially, push all the nodes into the distances hashmap with a distance of infinity. for (self.vertices.?.entries) |entry| { if (entry.used == true and !mem.eql(u8, source.name, entry.kv.key)) { _ = try distances.put(entry.kv.key, 9999); try pq.add(Element{.name= entry.kv.key, .distance= 9999}); } } _ = try distances.put(src, 0); try pq.add(Element{.name= source.name, .distance= 0}); while (pq.count() > 0) { var current: Element = pq.remove(); if (!visited.contains(current.name)) { var currentPtr: *Node = self.vertices.?.getValue(current.name).?; var neighbors: std.ArrayList(*Edge) = self.graph.?.getValue(currentPtr).?; for (neighbors.items) |n| { // If the PQ contains this vertex (meaning, it hasn't been considered yet), then the // then check if the edge between the current and this neighbor is the min. spanning edge // from current. Choose the edge, mark the distance map and fill the prev vector. // Contains: var pqcontains: bool = false; for (pq.items) |item, i| { if (mem.eql(u8, item.name, n.node.name)) { pqcontains = true; break; } } // Distance of current vertex with its neighbors (best_so_far) var best_dist = distances.getValue(n.node.name).?; // Distance between current vertex and this neighbor n var n_dist = @intCast(i32, n.weight); // warn("\r\n current {} nbhr {} ndist {} best {}", .{current.node, n.node.name, n_dist, best_dist}); if (pqcontains == true and n_dist < best_dist) { // We have found the edge that needs to be added to our MST, add it to path, // set distance and prev. and update the priority queue with the new weight. (n_dist) _ = try distances.put(n.node.name, n_dist); var prevArr: ?std.ArrayList(*Node) = undefined; if (prev.contains(n.node.name) == true) { prevArr = prev.getValue(n.node.name).?; } else { prevArr = std.ArrayList(*Node).init(self.allocator); } try prevArr.?.append(currentPtr); // for (prevArr.?.items) |y| { // warn("\r\n prev: {}", .{y}); // } // warn("\r\n next\r\n", .{}); _ = try prev.put(n.node.name, prevArr); // Update the priority queue with the new edge weight. var modIndex: usize = 0; for (pq.items) |item, i| { if (mem.eql(u8, item.name, n.node.name)) { modIndex = i; break; } } _ = pq.removeIndex(modIndex); try pq.add(Element{.name= n.node.name, .distance= n_dist}); } // Identify leaf nodes for path tracing // pull out the neighbors list for the current neighbor, and check length. var cPtr: *Node = self.vertices.?.getValue(n.node.name).?; var nbhr: std.ArrayList(*Edge) = self.graph.?.getValue(cPtr).?; if (nbhr.items.len == 0) { // warn("\r\n last node: {} {}", .{current.name, n.node.name}); try dest.append(Pair{.n1= current.name, .n2= n.node.name}); } } } _ = try visited.put(current.name, true); } // Path tracing, to return the MST as an arraylist of arraylist. for (dest.items) |item| { var spacer = try self.allocator.create(Node); errdefer self.allocator.destroy(spacer); spacer.* = Node.init("spacer", 1); var t0 = std.ArrayList(*Node).init(self.allocator); try t0.append(spacer); try path.append(t0); var t1 = std.ArrayList(*Node).init(self.allocator); try t1.append(self.vertices.?.getValue(item.n2).?); try path.append(t1); var dst = item.n1; var t2 = std.ArrayList(*Node).init(self.allocator); try t2.append(self.vertices.?.getValue(dst).?); try path.append(t2); while(prev.contains(dst)) { var temp: ?std.ArrayList(*Node) = prev.getValue(dst).?; // for (temp.?.items) |k| { // warn("\r\n path: {}", .{k}); // } try path.append(temp.?); dst = temp.?.items[0].name; } } return path; } fn arrayContains(arr: std.ArrayList(*Node), node: *Node) bool { for (arr.items) | item | { if (mem.eql(u8, item.name, node.name)) { return true; } } return false; } fn min(a: i32, b: i32) i32 { if (a < b) { return a; } return b; } fn tarjanDriver (self: *Self, current: *Node, globalIndexCounter: *i32, index: *std.StringHashMap(i32), low: *std.StringHashMap(i32), stack: *std.ArrayList(*Node), result: *std.ArrayList(std.ArrayList(*Node)) ) !void { // Set the indices for the current recursion, increment the global index, mark the index // for the node, mark low, and append the node to the recursion stack. _ = try index.put(current.name, globalIndexCounter.*); _ = try low.put(current.name, globalIndexCounter.*); try stack.append(current); globalIndexCounter.* += 1; // Get the neighbors of the current node. var neighbors: std.ArrayList(*Edge) = self.graph.?.getValue(current).?; // warn("\r\n begin iteration for node: {}\r\n", .{current}); for (neighbors.items) |n| { if (index.contains(n.node.name) == false) { self.tarjanDriver(n.node, globalIndexCounter, index, low, stack, result) catch unreachable; // Update the low index after the recursion, set low index to the min of // prev and current recursive calls. var currLow: i32 = low.getValue(current.name).?; var nLow: i32 = low.getValue(n.node.name).?; _ = try low.put(current.name, min(currLow, nLow)); } else if (arrayContains(stack.*, current)) { // Update the low index after the recursion, set low index to the min of // prev and current recursive calls. var currLow: i32 = low.getValue(current.name).?; // IMP: notice that 'index' is being used here, not low. var nIndex: i32 = index.getValue(n.node.name).?; _ = try low.put(current.name, min(currLow, nIndex)); } } // for(low.entries) |entry|{ // if (entry.used) { // warn("\r\n low entry: {}", .{entry}); // } // } // warn("\r\n end iteration for node: {}", .{current}); var currentLow: i32 = low.getValue(current.name).?; var currentIndex: i32 = index.getValue(current.name).?; // warn("\r\n current {} index {} low {}", .{current, currentIndex, currentLow}); if (currentLow == currentIndex) { var scc = std.ArrayList(*Node).init(self.allocator); while (true) { // for (stack.items) |k| { // warn("\r\n stack: {}", .{k}); // } var successor: *Node = stack.pop(); try scc.append(successor); if ( mem.eql(u8, successor.name, current.name) ) { try result.append(scc); break; } } } } pub fn tarjan(self: *Self) !std.ArrayList(std.ArrayList(*Node)) { // Tarjan uses dfs in order to traverse a graph, and return all the strongly connected components in it. // The algorithm uses two markers called index and low. Index marks the order in which the node has been visited. The // count of nodes from the start vertex. The other marker, low, marks the lowest index value // seen by the algorithm so far. Once the recursion unwraps, the key of this algorithm // is to compare the current stack 'low' (c1) with the previous stack 'low' (c0) // while it collapses the stacks. If c1 < c0, then the low for the previous node is updated // to low[prev] = c1, if c1 > c0 then we have found a min-cut edge for the graph. These edges // separate the strongly connected components from each other. var result = std.ArrayList(std.ArrayList(*Node)).init(self.allocator); var globalIndexCounter: i32 = 0; var stack = std.ArrayList(*Node).init(self.allocator); defer stack.deinit(); var index = std.StringHashMap(i32).init(self.allocator); defer index.deinit(); var low = std.StringHashMap(i32).init(self.allocator); defer low.deinit(); for (self.vertices.?.entries) |entry| { if (entry.used == true) { if (index.contains(entry.kv.value.name) == false) { self.tarjanDriver(entry.kv.value, &globalIndexCounter, &index, &low, &stack, &result) catch unreachable; } } } return result; } }; } test "basic graph insertion and printing" { var graph = Graph(i32).init(gallocator); defer graph.deinit(); try graph.addEdge("A", 10, "B", 20, 1); try graph.addEdge("B", 20, "C", 40, 2); try graph.addEdge("C", 110, "A", 10, 3); try graph.addEdge("A", 10, "A", 10, 0); try graph.addEdge("J", 1, "K", 1, 1); graph.print(); warn("\r\n", .{}); warn("\r\n", .{}); } test "basic graph toposort" { var graph = Graph(i32).init(gallocator); defer graph.deinit(); try graph.addEdge("A", 10, "B", 20, 1); try graph.addEdge("B", 20, "C", 40, 2); try graph.addEdge("C", 110, "A", 10, 3); try graph.addEdge("A", 10, "A", 10, 0); try graph.addEdge("J", 1, "K", 1, 1); graph.print(); warn("\r\nTopoSort: ", .{}); var res = try graph.topoSort(); defer res.deinit(); for (res.items) |n| { warn("\r\n stack: {} ", .{n}); } warn("\r\n", .{}); warn("\r\nConnected components: {}", .{graph.connected}); warn("\r\n", .{}); warn("\r\n", .{}); } test "basic graph bfs" { var graph = Graph(i32).init(gallocator); defer graph.deinit(); try graph.addEdge("A", 10, "B", 20, 1); try graph.addEdge("B", 20, "C", 40, 2); try graph.addEdge("C", 110, "A", 10, 3); try graph.addEdge("A", 10, "A", 10, 0); try graph.addEdge("J", 1, "K", 1, 1); graph.print(); warn("\r\n", .{}); warn("\r\nBFS: ", .{}); var res1 = try graph.bfs(); defer res1.deinit(); for (res1.items) |n| { warn("\r\n bfs result: {} ", .{n}); } warn("\r\n", .{}); warn("\r\n", .{}); } test "basic graph dfs" { var graph = Graph(i32).init(gallocator); defer graph.deinit(); try graph.addEdge("A", 10, "B", 20, 1); try graph.addEdge("B", 20, "C", 40, 2); try graph.addEdge("C", 110, "A", 10, 3); try graph.addEdge("A", 10, "A", 10, 0); try graph.addEdge("J", 1, "K", 1, 1); graph.print(); warn("\r\n", .{}); warn("\r\nBFS: ", .{}); var res1 = try graph.dfs(); defer res1.deinit(); for (res1.items) |n| { warn("\r\n dfs result: {} ", .{n}); } warn("\r\n", .{}); warn("\r\n", .{}); } test "basic graph dijikstra" { // Graph with no self loops for dijiksta. var graph2 = Graph(i32).init(gallocator); defer graph2.deinit(); try graph2.addEdge("A", 1, "B", 1, 1); try graph2.addEdge("B", 1, "C", 1, 2); try graph2.addEdge("C", 1, "D", 1, 5); try graph2.addEdge("D", 1, "E", 1, 4); // try graph2.addEdge("B", 1, "E", 1, 1); graph2.print(); _ = try graph2.topoSort(); warn("\r\nConnected components: {}", .{graph2.connected}); warn("\r\n", .{}); warn("\r\nDijikstra: ", .{}); var res3 = try graph2.dijikstra("A", "E"); defer res3.deinit(); for (res3.items) |n| { warn("\r\n dijikstra: {} ", .{n}); } warn("\r\n", .{}); warn("\r\n", .{}); } test "basic graph prim" { // Graph for prim. var graph3 = Graph(i32).init(gallocator); defer graph3.deinit(); try graph3.addEdge("A", 1, "B", 1, 1); try graph3.addEdge("B", 1, "C", 1, 2); try graph3.addEdge("C", 1, "D", 1, 5); try graph3.addEdge("D", 1, "E", 1, 4); try graph3.addEdge("B", 1, "E", 1, 1); graph3.print(); _ = try graph3.topoSort(); warn("\r\nConnected components: {}", .{graph3.connected}); warn("\r\n", .{}); warn("\r\nPrim: ", .{}); var res4 = try graph3.prim("A"); defer res4.deinit(); for (res4.items) |n| { for (n.items) |x| { warn("\r\n prim: {} ", .{x}); } } warn("\r\n", .{}); warn("\r\n", .{}); } test "basic graph tarjan" { // Graph for tarjan. var graph4 = Graph(i32).init(gallocator); defer graph4.deinit(); try graph4.addEdge("A", 1, "B", 1, 1); try graph4.addEdge("B", 1, "A", 1, 1); try graph4.addEdge("B", 1, "C", 1, 2); try graph4.addEdge("C", 1, "B", 1, 1); try graph4.addEdge("C", 1, "D", 1, 5); try graph4.addEdge("D", 1, "E", 1, 4); try graph4.addEdge("B", 1, "E", 1, 1); try graph4.addEdge("J", 1, "K", 1, 1); try graph4.addEdge("M", 1, "N", 1, 1); graph4.print(); _ = try graph4.topoSort(); warn("\r\nConnected components: {}", .{graph4.connected}); warn("\r\n", .{}); warn("\r\nTarjan: ", .{}); var res5 = try graph4.tarjan(); defer res5.deinit(); for (res5.items) |n| { warn("\r\n begin component:", .{}); for (n.items) |x| { warn("\r\n tarjan: {} ", .{x}); } warn("\r\n end component.", .{}); } warn("\r\n", .{}); warn("\r\n", .{}); }
src/main.zig
const std = @import("std"); const Arena = std.heap.ArenaAllocator; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const yeti = @import("yeti"); const initCodebase = yeti.initCodebase; const tokenize = yeti.tokenize; const parse = yeti.parse; const analyzeSemantics = yeti.analyzeSemantics; const codegen = yeti.codegen; const printWasm = yeti.printWasm; const components = yeti.components; const literalOf = yeti.query.literalOf; const typeOf = yeti.query.typeOf; const MockFileSystem = yeti.FileSystem; test "tokenize string" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\"hello" "world" ; var tokens = try tokenize(module, code); { const token = tokens.next().?; try expectEqual(token.get(components.TokenKind), .string); try expectEqualStrings(literalOf(token), "hello"); try expectEqual(token.get(components.Span), .{ .begin = .{ .column = 0, .row = 0 }, .end = .{ .column = 6, .row = 0 }, }); } { const token = tokens.next().?; try expectEqual(token.get(components.TokenKind), .string); try expectEqualStrings(literalOf(token), "world"); try expectEqual(token.get(components.Span), .{ .begin = .{ .column = 8, .row = 0 }, .end = .{ .column = 14, .row = 0 }, }); } try expectEqual(tokens.next(), null); } test "tokenize multiline string" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\"hello \\world" ; var tokens = try tokenize(module, code); { const token = tokens.next().?; try expectEqual(token.get(components.TokenKind), .string); try expectEqualStrings(literalOf(token), "hello\nworld"); try expectEqual(token.get(components.Span), .{ .begin = .{ .column = 0, .row = 0 }, .end = .{ .column = 6, .row = 1 }, }); } try expectEqual(tokens.next(), null); } test "parse string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\start() []u8 { \\ "hello world" \\} ; var tokens = try tokenize(module, code); try parse(module, &tokens); const top_level = module.get(components.TopLevel); const overloads = top_level.findString("start").get(components.Overloads).slice(); try expectEqual(overloads.len, 1); const start = overloads[0]; const return_type = start.get(components.ReturnTypeAst).entity; try expectEqual(return_type.get(components.AstKind), .array); try expectEqualStrings(literalOf(return_type.get(components.Value).entity), "u8"); const body = overloads[0].get(components.Body).slice(); try expectEqual(body.len, 1); const hello_world = body[0]; try expectEqual(hello_world.get(components.AstKind), .string); try expectEqualStrings(literalOf(hello_world), "hello world"); } test "parse array index" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\start() u8 { \\ text = "hello world" \\ text[0] \\} ; var tokens = try tokenize(module, code); try parse(module, &tokens); const top_level = module.get(components.TopLevel); const overloads = top_level.findString("start").get(components.Overloads).slice(); try expectEqual(overloads.len, 1); const start = overloads[0]; const return_type = start.get(components.ReturnTypeAst).entity; try expectEqual(return_type.get(components.AstKind), .symbol); try expectEqualStrings(literalOf(return_type), "u8"); const body = overloads[0].get(components.Body).slice(); try expectEqual(body.len, 2); const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqualStrings(literalOf(define.get(components.Name).entity), "text"); const hello_world = define.get(components.Value).entity; try expectEqual(hello_world.get(components.AstKind), .string); try expectEqualStrings(literalOf(hello_world), "hello world"); const index = body[1]; try expectEqual(index.get(components.AstKind), .index); const arguments = index.get(components.Arguments).slice(); try expectEqual(arguments.len, 2); try expectEqualStrings(literalOf(arguments[0]), "text"); try expectEqualStrings(literalOf(arguments[1]), "0"); } test "analyze semantics of string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ "hello world" \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); const return_type = start.get(components.ReturnType).entity; try expectEqualStrings(literalOf(return_type), "[]u8"); const body = start.get(components.Body).slice(); try expectEqual(body.len, 1); const hello_world = body[0]; try expectEqual(hello_world.get(components.AstKind), .string); try expectEqual(typeOf(hello_world), return_type); try expectEqualStrings(literalOf(hello_world), "hello world"); } test "analyze semantics of array index" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() u8 { \\ text = "hello world" \\ text[0] \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); try expectEqual(start.get(components.ReturnType).entity, builtins.U8); const body = start.get(components.Body).slice(); try expectEqual(body.len, 2); const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqual(typeOf(define), builtins.Void); const local = define.get(components.Local).entity; try expectEqual(local.get(components.AstKind), .local); try expectEqualStrings(literalOf(local.get(components.Name).entity), "text"); const hello_world = define.get(components.Value).entity; try expectEqual(hello_world.get(components.AstKind), .string); try expectEqualStrings(literalOf(typeOf(hello_world)), "[]u8"); try expectEqualStrings(literalOf(hello_world), "hello world"); const index = body[1]; try expectEqual(index.get(components.AstKind), .index); try expectEqual(typeOf(index), builtins.U8); const arguments = index.get(components.Arguments).slice(); try expectEqual(arguments[0], local); try expectEqualStrings(literalOf(arguments[1]), "0"); } test "codegen of string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ "hello world" \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 2); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const constant = wasm_instructions[1]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "11"); } const data_segment = codebase.get(components.DataSegment); try expectEqual(data_segment.end, 88); const entities = data_segment.entities.slice(); try expectEqual(entities.len, 1); try expectEqualStrings(literalOf(entities[0]), "hello world"); } test "codegen of array index" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() u8 { \\ text = "hello world" \\ text[0] \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 9); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const constant = wasm_instructions[1]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "11"); } { const local_set = wasm_instructions[2]; try expectEqual(local_set.get(components.WasmInstructionKind), .local_set); try expectEqualStrings(literalOf(local_set.get(components.Local).entity.get(components.Name).entity), "text"); } { const field = wasm_instructions[3]; try expectEqual(field.get(components.WasmInstructionKind), .field); try expectEqualStrings(literalOf(field.get(components.Local).entity.get(components.Name).entity), "text"); try expectEqualStrings(literalOf(field.get(components.Field).entity), "ptr"); } { const constant = wasm_instructions[4]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const constant = wasm_instructions[5]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "1"); } try expectEqual(wasm_instructions[6].get(components.WasmInstructionKind), .i32_mul); try expectEqual(wasm_instructions[7].get(components.WasmInstructionKind), .i32_add); try expectEqual(wasm_instructions[8].get(components.WasmInstructionKind), .i32_load8_u); const data_segment = codebase.get(components.DataSegment); try expectEqual(data_segment.end, 88); const entities = data_segment.entities.slice(); try expectEqual(entities.len, 1); try expectEqualStrings(literalOf(entities[0]), "hello world"); } test "print wasm string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ "hello world" \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32 i32) \\ (i32.const 0) \\ (i32.const 11)) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm multi line string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ " \\ hello \\ world \\ " \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32 i32) \\ (i32.const 0) \\ (i32.const 19)) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "\n hello\n world\n ") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm assign string literal to variable" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ text = "hello world" \\ text \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32 i32) \\ (local $text.ptr i32) \\ (local $text.len i32) \\ (i32.const 0) \\ (i32.const 11) \\ (local.set $text.len) \\ (local.set $text.ptr) \\ (local.get $text.ptr) \\ (local.get $text.len)) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm pass string literal as argument" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\first(text: []u8) u8 { \\ *text.ptr \\} \\ \\start() u8 { \\ first("hello world") \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32) \\ (i32.const 0) \\ (i32.const 11) \\ (call $foo/first..text.array.u8)) \\ \\ (func $foo/first..text.array.u8 (param $text.ptr i32) (param $text.len i32) (result i32) \\ (local.get $text.ptr) \\ i32.load8_u) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm dereference string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() u8 { \\ text = "hello world" \\ *text.ptr \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32) \\ (local $text.ptr i32) \\ (local $text.len i32) \\ (i32.const 0) \\ (i32.const 11) \\ (local.set $text.len) \\ (local.set $text.ptr) \\ (local.get $text.ptr) \\ i32.load8_u) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm write through **u8" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() void { \\ text = "<NAME>" \\ ptr = cast(**u8, 100) \\ *ptr = text.ptr \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start \\ (local $text.ptr i32) \\ (local $text.len i32) \\ (local $ptr i32) \\ (i32.const 0) \\ (i32.const 11) \\ (local.set $text.len) \\ (local.set $text.ptr) \\ (i32.const 100) \\ (local.set $ptr) \\ (local.get $ptr) \\ (local.get $text.ptr) \\ i32.store) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); }
src/tests/test_strings.zig
pub const EventType = enum(u8) { Resize, MouseMove, MouseDown, MouseUp, MouseWheel, TouchPan, TouchZoom, KeyDown, KeyUp, TextInput, Focus, Blur, Enter, Leave, ClipboardUpdate, }; pub const Event = struct { type: EventType, is_accepted: bool = true, pub fn accept(self: *Event) void { self.is_accepted = true; } pub fn ignore(self: *Event) void { self.is_accepted = false; } }; pub const ResizeEvent = struct { event: Event = Event{ .type = .Resize }, old_width: f32, old_height: f32, new_width: f32, new_height: f32, }; pub const MouseButton = enum(u4) { none, left, middle, right, back, forward, }; pub const Modifier = enum(u2) { alt, ctrl, shift, super, }; pub const MouseEvent = struct { event: Event, button: MouseButton, click_count: u32, state: u32, modifiers: u4, x: f32, y: f32, wheel_x: i32, wheel_y: i32, pub fn isButtonPressed(self: MouseEvent, button: MouseButton) bool { if (button == .none) return false; const flag = @as(u32, 1) << (@enumToInt(button) - 1); return (self.state & flag) != 0; } pub fn isModifierPressed(self: MouseEvent, modifier: Modifier) bool { const flag = @as(@TypeOf(self.modifiers), 1) << @enumToInt(modifier); return (self.modifiers & flag) != 0; } }; pub const TouchEvent = struct { event: Event, x: f32, y: f32, dx: f32, dy: f32, zoom: f32, }; pub const KeyCode = enum(u8) { Return, D0, D1, D2, D3, D4, D5, D6, D7, D8, D9, Period, Comma, Escape, Backspace, Space, Plus, Minus, Asterisk, Slash, Percent, Home, End, Delete, Tab, LShift, RShift, LCtrl, RCtrl, LAlt, RAlt, Left, Right, Up, Down, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Hash, Unknown, }; pub const KeyEvent = struct { event: Event, key: KeyCode, down: bool, repeat: bool, modifiers: u4, pub fn isModifierPressed(self: KeyEvent, modifier: Modifier) bool { const flag = @as(@TypeOf(self.modifiers), 1) << @enumToInt(modifier); return (self.modifiers & flag) != 0; } pub fn isSingleModifierPressed(self: KeyEvent, modifier: Modifier) bool { const flag = @as(@TypeOf(self.modifiers), 1) << @enumToInt(modifier); return (self.modifiers & flag) == flag; } }; pub const TextInputEvent = struct { event: Event = Event{ .type = .TextInput }, text: []const u8, }; pub const FocusSource = enum { programmatic, keyboard, mouse, }; pub const FocusPolicy = struct { mouse: bool = false, keyboard: bool = false, pub fn none() FocusPolicy { return .{ .mouse = false, .keyboard = false, }; } pub fn accepts(self: FocusPolicy, source: FocusSource) bool { return switch (source) { .programmatic => self.keyboard or self.mouse, .keyboard => self.keyboard, .mouse => self.mouse, }; } }; pub const FocusEvent = struct { event: Event, source: FocusSource, };
src/gui/event.zig
pub const CCH_RM_SESSION_KEY = @as(u32, 32); pub const CCH_RM_MAX_APP_NAME = @as(u32, 255); pub const CCH_RM_MAX_SVC_NAME = @as(u32, 63); pub const RM_INVALID_TS_SESSION = @as(i32, -1); pub const RM_INVALID_PROCESS = @as(i32, -1); //-------------------------------------------------------------------------------- // Section: Types (10) //-------------------------------------------------------------------------------- pub const RM_APP_TYPE = enum(i32) { UnknownApp = 0, MainWindow = 1, OtherWindow = 2, Service = 3, Explorer = 4, Console = 5, Critical = 1000, }; pub const RmUnknownApp = RM_APP_TYPE.UnknownApp; pub const RmMainWindow = RM_APP_TYPE.MainWindow; pub const RmOtherWindow = RM_APP_TYPE.OtherWindow; pub const RmService = RM_APP_TYPE.Service; pub const RmExplorer = RM_APP_TYPE.Explorer; pub const RmConsole = RM_APP_TYPE.Console; pub const RmCritical = RM_APP_TYPE.Critical; pub const RM_SHUTDOWN_TYPE = enum(i32) { ForceShutdown = 1, ShutdownOnlyRegistered = 16, }; pub const RmForceShutdown = RM_SHUTDOWN_TYPE.ForceShutdown; pub const RmShutdownOnlyRegistered = RM_SHUTDOWN_TYPE.ShutdownOnlyRegistered; pub const RM_APP_STATUS = enum(i32) { Unknown = 0, Running = 1, Stopped = 2, StoppedOther = 4, Restarted = 8, ErrorOnStop = 16, ErrorOnRestart = 32, ShutdownMasked = 64, RestartMasked = 128, }; pub const RmStatusUnknown = RM_APP_STATUS.Unknown; pub const RmStatusRunning = RM_APP_STATUS.Running; pub const RmStatusStopped = RM_APP_STATUS.Stopped; pub const RmStatusStoppedOther = RM_APP_STATUS.StoppedOther; pub const RmStatusRestarted = RM_APP_STATUS.Restarted; pub const RmStatusErrorOnStop = RM_APP_STATUS.ErrorOnStop; pub const RmStatusErrorOnRestart = RM_APP_STATUS.ErrorOnRestart; pub const RmStatusShutdownMasked = RM_APP_STATUS.ShutdownMasked; pub const RmStatusRestartMasked = RM_APP_STATUS.RestartMasked; pub const RM_REBOOT_REASON = enum(i32) { None = 0, PermissionDenied = 1, SessionMismatch = 2, CriticalProcess = 4, CriticalService = 8, DetectedSelf = 16, }; pub const RmRebootReasonNone = RM_REBOOT_REASON.None; pub const RmRebootReasonPermissionDenied = RM_REBOOT_REASON.PermissionDenied; pub const RmRebootReasonSessionMismatch = RM_REBOOT_REASON.SessionMismatch; pub const RmRebootReasonCriticalProcess = RM_REBOOT_REASON.CriticalProcess; pub const RmRebootReasonCriticalService = RM_REBOOT_REASON.CriticalService; pub const RmRebootReasonDetectedSelf = RM_REBOOT_REASON.DetectedSelf; pub const RM_UNIQUE_PROCESS = extern struct { dwProcessId: u32, ProcessStartTime: FILETIME, }; pub const RM_PROCESS_INFO = extern struct { Process: RM_UNIQUE_PROCESS, strAppName: [256]u16, strServiceShortName: [64]u16, ApplicationType: RM_APP_TYPE, AppStatus: u32, TSSessionId: u32, bRestartable: BOOL, }; pub const RM_FILTER_TRIGGER = enum(i32) { Invalid = 0, File = 1, Process = 2, Service = 3, }; pub const RmFilterTriggerInvalid = RM_FILTER_TRIGGER.Invalid; pub const RmFilterTriggerFile = RM_FILTER_TRIGGER.File; pub const RmFilterTriggerProcess = RM_FILTER_TRIGGER.Process; pub const RmFilterTriggerService = RM_FILTER_TRIGGER.Service; pub const RM_FILTER_ACTION = enum(i32) { InvalidFilterAction = 0, NoRestart = 1, NoShutdown = 2, }; pub const RmInvalidFilterAction = RM_FILTER_ACTION.InvalidFilterAction; pub const RmNoRestart = RM_FILTER_ACTION.NoRestart; pub const RmNoShutdown = RM_FILTER_ACTION.NoShutdown; pub const RM_FILTER_INFO = extern struct { FilterAction: RM_FILTER_ACTION, FilterTrigger: RM_FILTER_TRIGGER, cbNextOffset: u32, Anonymous: extern union { strFilename: ?PWSTR, Process: RM_UNIQUE_PROCESS, strServiceShortName: ?PWSTR, }, }; pub const RM_WRITE_STATUS_CALLBACK = fn( nPercentComplete: u32, ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // Section: Functions (11) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "rstrtmgr" fn RmStartSession( pSessionHandle: ?*u32, dwSessionFlags: u32, strSessionKey: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "RstrtMgr" fn RmJoinSession( pSessionHandle: ?*u32, strSessionKey: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "rstrtmgr" fn RmEndSession( dwSessionHandle: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "rstrtmgr" fn RmRegisterResources( dwSessionHandle: u32, nFiles: u32, rgsFileNames: ?[*]?PWSTR, nApplications: u32, rgApplications: ?[*]RM_UNIQUE_PROCESS, nServices: u32, rgsServiceNames: ?[*]?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "rstrtmgr" fn RmGetList( dwSessionHandle: u32, pnProcInfoNeeded: ?*u32, pnProcInfo: ?*u32, rgAffectedApps: ?[*]RM_PROCESS_INFO, lpdwRebootReasons: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "rstrtmgr" fn RmShutdown( dwSessionHandle: u32, lActionFlags: u32, fnStatus: ?RM_WRITE_STATUS_CALLBACK, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "rstrtmgr" fn RmRestart( dwSessionHandle: u32, dwRestartFlags: u32, fnStatus: ?RM_WRITE_STATUS_CALLBACK, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "RstrtMgr" fn RmCancelCurrentTask( dwSessionHandle: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "RstrtMgr" fn RmAddFilter( dwSessionHandle: u32, strModuleName: ?[*:0]const u16, pProcess: ?*RM_UNIQUE_PROCESS, strServiceShortName: ?[*:0]const u16, FilterAction: RM_FILTER_ACTION, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "RstrtMgr" fn RmRemoveFilter( dwSessionHandle: u32, strModuleName: ?[*:0]const u16, pProcess: ?*RM_UNIQUE_PROCESS, strServiceShortName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "RstrtMgr" fn RmGetFilterList( dwSessionHandle: u32, // TODO: what to do with BytesParamIndex 2? pbFilterBuf: ?*u8, cbFilterBuf: u32, cbFilterBufNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // 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 (3) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; const FILETIME = @import("../foundation.zig").FILETIME; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "RM_WRITE_STATUS_CALLBACK")) { _ = RM_WRITE_STATUS_CALLBACK; } @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/system/restart_manager.zig
const std = @import("std"); const alka = @import("alka"); const game = @import("game.zig"); usingnamespace alka.math; usingnamespace alka.log; const mlog = std.log.scoped(.app); const gui = alka.gui; const ecs = @import("ecs.zig"); const ButtonTextTag = enum { score, dash_counter, menu, play, exit, }; const normalButtonColour = alka.Colour.rgba(40, 100, 200, 255); const hoverButtonColour = alka.Colour.rgba(40, 120, 240, 255); var scoreButtonTransform: Transform2D = undefined; var dashButtonTransform: Transform2D = undefined; var buttonText: std.AutoHashMap(ButtonTextTag, []const u8) = undefined; pub fn init() !void { try gui.init(alka.getAllocator()); buttonText = std.AutoHashMap(ButtonTextTag, []const u8).init(alka.getAllocator()); try buttonText.put(.score, "Score:"); try buttonText.put(.dash_counter, "Dash:"); try buttonText.put(.menu, "Menu"); try buttonText.put(.play, "Play"); try buttonText.put(.exit, "Exit"); var w = alka.getWindow(); var canvas = try gui.createCanvas( 0, Transform2D{ .position = Vec2f{ .x = @intToFloat(f32, w.size.width) / 2, .y = @intToFloat(f32, w.size.height) / 2, }, .origin = Vec2f{ .x = 1000 / 2, .y = 700 / 2 }, .size = Vec2f{ .x = 1000, .y = 700 }, }, alka.Colour.rgba(200, 0, 0, 0), ); const sx: f32 = 225; const sxinc: f32 = 90; _ = try canvas.createElement( @enumToInt(ButtonTextTag.score), Transform2D{ .position = Vec2f{ .x = canvas.transform.size.x / 2, .y = sx - sxinc * 1, }, .origin = Vec2f{ .x = 250 / 2, .y = 50 / 2 }, .size = Vec2f{ .x = 250, .y = 50 }, }, alka.Colour.rgba(60, 200, 120, 255), gui.Events{ .draw = drawButtonScore, .update = updateButtonScore, }, ); _ = try canvas.createElement( @enumToInt(ButtonTextTag.dash_counter), Transform2D{ .position = Vec2f{ .x = canvas.transform.size.x / 2, .y = sx, }, .origin = Vec2f{ .x = 200 / 2, .y = 25 / 2 }, .size = Vec2f{ .x = 200, .y = 25 }, }, alka.Colour.rgba(60, 200, 120, 255), gui.Events{ .draw = drawButtonDash, .update = updateButtonDash, }, ); _ = try canvas.createElement( @enumToInt(ButtonTextTag.menu), Transform2D{ .position = Vec2f{ .x = canvas.transform.size.x - 75 * 1.5, .y = canvas.transform.size.y - 30 * 1.5, }, .origin = Vec2f{ .x = 75 / 2, .y = 30 / 2 }, .size = Vec2f{ .x = 75, .y = 30 }, }, normalButtonColour, gui.Events{ .draw = drawButton, .onEnter = onEnterButton, .onExit = onExitButton, .onHover = onHoverButton, .onPressed = onPressedButton, }, ); _ = try canvas.createElement( @enumToInt(ButtonTextTag.play), Transform2D{ .position = Vec2f{ .x = canvas.transform.size.x / 2, .y = sx + sxinc * 1, }, .origin = Vec2f{ .x = 75 / 2, .y = 30 / 2 }, .size = Vec2f{ .x = 75, .y = 30 }, }, normalButtonColour, gui.Events{ .draw = drawButton, .onEnter = onEnterButton, .onExit = onExitButton, .onHover = onHoverButton, .onPressed = onPressedButton, }, ); _ = try canvas.createElement( @enumToInt(ButtonTextTag.exit), Transform2D{ .position = Vec2f{ .x = canvas.transform.size.x / 2, .y = sx + sxinc * 2, }, .origin = Vec2f{ .x = 75 / 2, .y = 30 / 2 }, .size = Vec2f{ .x = 75, .y = 30 }, }, normalButtonColour, gui.Events{ .draw = drawButton, .onEnter = onEnterButton, .onExit = onExitButton, .onHover = onHoverButton, .onPressed = onPressedButton, }, ); scoreButtonTransform = try canvas.getTransform(@enumToInt(ButtonTextTag.score)); dashButtonTransform = try canvas.getTransform(@enumToInt(ButtonTextTag.dash_counter)); } pub fn deinit() !void { buttonText.deinit(); try gui.deinit(); } fn updateButtonScore(self: *gui.Element, dt: f32) !void { if (game.state == .play) { var canvas = try gui.getCanvasPtr(0); var tr = try canvas.getTransformPtr(@enumToInt(ButtonTextTag.score)); tr.size = scoreButtonTransform.size.divValues(1.2, 1); tr.origin = scoreButtonTransform.origin.divValues(1.2, 1); tr.position.x = tr.origin.x + tr.size.x / 4; tr.position.y = tr.origin.y; } else if (game.state == .menu) { var canvas = try gui.getCanvasPtr(0); var tr = try canvas.getTransformPtr(@enumToInt(ButtonTextTag.score)); tr.* = scoreButtonTransform; } } fn updateButtonDash(self: *gui.Element, dt: f32) !void { if (game.state == .play) { var canvas = try gui.getCanvasPtr(0); var tr = try canvas.getTransformPtr(@enumToInt(ButtonTextTag.dash_counter)); tr.position.x = canvas.transform.size.x - tr.origin.x * 1.5; tr.position.y = tr.origin.y; } else if (game.state == .menu) { var canvas = try gui.getCanvasPtr(0); var tr = try canvas.getTransformPtr(@enumToInt(ButtonTextTag.dash_counter)); tr.* = dashButtonTransform; } } fn drawButtonScore(self: *gui.Element) !void { var alloc = alka.getAllocator(); const text = buttonText.get(@intToEnum(ButtonTextTag, @intCast(u2, self.id.?))).?; var buffer = blk: { if (game.score >= 0) { break :blk try std.fmt.allocPrint(alloc, "{s}{d:0.2}\nHigh{s}{d:0.2}", .{ text, game.score, text, game.highscore }); } else { break :blk try std.fmt.allocPrint(alloc, "You died.\nHigh{s}{d:0.2}", .{ text, game.highscore }); } }; defer alloc.free(buffer); const f = try alka.getAssetManager().getFont(0); const size: f32 = 18; const opos = self.transform.getOriginated(); const position = Vec2f{ .x = opos.x + (self.transform.origin.x / (size / @intToFloat(f32, buffer.len))), .y = opos.y + (self.transform.size.y / size), }; const colour = alka.Colour.rgba(0, 0, 0, 255); try alka.drawRectangleAdv( self.transform.getRectangleNoOrigin(), self.transform.origin, deg2radf(self.transform.rotation), self.colour, ); try alka.drawText(0, buffer, position, size, colour); } fn drawButtonDash(self: *gui.Element) !void { var alloc = alka.getAllocator(); const text = buttonText.get(@intToEnum(ButtonTextTag, @intCast(u3, self.id.?))).?; const dash: f32 = blk: { const pl = ecs.world.getRegister(@enumToInt(ecs.SpecialEntities.player)) catch { break :blk 0.0; }; const c = try pl.get("Player Controller", ecs.PlayerController); break :blk abs(c.dash_counter); }; var buffer = try std.fmt.allocPrint(alloc, "{s}{d:0.2}", .{ text, dash }); defer alloc.free(buffer); const f = try alka.getAssetManager().getFont(0); const size = 18; const opos = self.transform.getOriginated(); const position = Vec2f{ .x = opos.x + (self.transform.origin.x / (size / @intToFloat(f32, buffer.len))), .y = opos.y + (self.transform.size.y / size), }; const colour = alka.Colour.rgba(0, 0, 0, 255); try alka.drawRectangleAdv( self.transform.getRectangleNoOrigin(), self.transform.origin, deg2radf(self.transform.rotation), self.colour, ); try alka.drawText(0, buffer, position, size, colour); } fn drawButton(self: *gui.Element) !void { if (self.id.? == @enumToInt(ButtonTextTag.menu) and game.state == .menu) { return; } else if (self.id.? != @enumToInt(ButtonTextTag.menu) and game.state == .play) return; const text = buttonText.get(@intToEnum(ButtonTextTag, @intCast(u3, self.id.?))).?; const f = try alka.getAssetManager().getFont(0); const size = 18; const opos = self.transform.getOriginated(); const position = Vec2f{ .x = opos.x + (self.transform.origin.x / (size / @intToFloat(f32, text.len))), .y = opos.y + (self.transform.size.y / size), }; const colour = alka.Colour.rgba(0, 0, 0, 255); try alka.drawRectangleAdv( self.transform.getRectangleNoOrigin(), self.transform.origin, deg2radf(self.transform.rotation), self.colour, ); try alka.drawText(0, text, position, size, colour); } fn onEnterButton(self: *gui.Element, position: Vec2f, relativepos: Vec2f) !void { self.colour = hoverButtonColour; } fn onExitButton(self: *gui.Element, position: Vec2f, relativepos: Vec2f) !void { self.colour = normalButtonColour; } fn onHoverButton(self: *gui.Element, position: Vec2f, relativepos: Vec2f) !void { self.colour = hoverButtonColour; } fn onPressedButton(self: *gui.Element, position: Vec2f, relativepos: Vec2f, button: alka.input.Mouse) !void { if (game.state == .play and self.id.? != @enumToInt(ButtonTextTag.menu)) return; const state = @intToEnum(ButtonTextTag, @intCast(u3, self.id.?)); switch (state) { .score => {}, .dash_counter => {}, .menu => { game.state = .menu; try game.eclose(); }, .play => { game.state = .play; try game.estart(); }, .exit => { try alka.close(); }, } }
examples/example_shooter_game/src/gui.zig
const std = @import("std"); const stdx = @import("stdx"); const ds = stdx.ds; const log = stdx.log.scoped(.work_queue); const builtin = @import("builtin"); const uv = @import("uv"); const CsError = @import("runtime.zig").CsError; pub const WorkQueue = struct { const Self = @This(); alloc: std.mem.Allocator, tasks_mutex: std.Thread.Mutex, tasks: ds.CompactUnorderedList(TaskId, TaskInfo), // Allocate the worker on the heap for now so the worker thread doesn't have to query for it. workers: std.ArrayList(*Worker), // Tasks in the ready queue can be picked up for work; their parent tasks have already completed. ready: std.atomic.Queue(TaskId), // Done queue holds tasks that have completed but haven't taken post steps (invoking callbacks and resolving deps) // This let's the main thread process them all without needing thread locks. done: std.atomic.Queue(TaskResultInfo), // When workers have processed a task and added to done, wakeup event is set. // Must refer to the same memory address. done_notify: *std.Thread.ResetEvent, /// A task isn't finished until it's been taken from the ready queue, processed by a worker, moved to done, /// and post-processed by the main thread again. num_unfinished_tasks: u32, // uv loop is used to set timers. uv_loop: *uv.uv_loop_t, pub fn init(alloc: std.mem.Allocator, uv_loop: *uv.uv_loop_t, done_notify: *std.Thread.ResetEvent) Self { var new = Self{ .alloc = alloc, .tasks_mutex = std.Thread.Mutex{}, .tasks = ds.CompactUnorderedList(TaskId, TaskInfo).init(alloc), .ready = std.atomic.Queue(TaskId).init(), .done = std.atomic.Queue(TaskResultInfo).init(), .workers = std.ArrayList(*Worker).init(alloc), .done_notify = done_notify, .uv_loop = uv_loop, .num_unfinished_tasks = 0, }; return new; } pub fn deinit(self: *Self) void { // Consume the tasks. while (self.done.get()) |n| { self.alloc.destroy(n); } while (self.ready.get()) |n| { self.alloc.destroy(n); } { self.tasks_mutex.lock(); defer self.tasks_mutex.unlock(); var iter = self.tasks.iterator(); while (iter.next()) |task| { task.deinit(self.alloc); } self.tasks.deinit(); } for (self.workers.items) |worker| { worker.deinit(); self.alloc.destroy(worker); } self.workers.deinit(); } /// Should only be called by the main thread. pub fn hasUnfinishedTasks(self: *Self) bool { return self.num_unfinished_tasks > 0; } fn getTaskInfo(self: *Self, id: TaskId) TaskInfo { self.tasks_mutex.lock(); defer self.tasks_mutex.unlock(); return self.tasks.getNoCheck(id); } pub fn createAndRunWorker(self: *Self) void { const worker = self.alloc.create(Worker) catch unreachable; worker.init(self); self.workers.append(worker) catch unreachable; const thread = std.Thread.spawn(.{}, Worker.loop, .{worker}) catch unreachable; worker.thread = thread; } pub fn addTaskWithCb(self: *Self, task: anytype, ctx: anytype, comptime success_cb: fn (@TypeOf(ctx), TaskOutput(@TypeOf(task))) void, comptime failure_cb: fn (@TypeOf(ctx), anyerror) void, ) void { self.num_unfinished_tasks += 1; const Task = @TypeOf(task); const task_dupe = self.alloc.create(Task) catch unreachable; task_dupe.* = task; const ctx_dupe = self.alloc.create(@TypeOf(ctx)) catch unreachable; ctx_dupe.* = ctx; const task_info = TaskInfo.initWithCb(Task, task_dupe, ctx_dupe, success_cb, failure_cb); var task_id: TaskId = undefined; { self.tasks_mutex.lock(); defer self.tasks_mutex.unlock(); task_id = self.tasks.add(task_info) catch unreachable; } self.addReadyTaskAndNotify(task_id); } fn addReadyTaskAndNotify(self: *Self, task_id: TaskId) void { const task_node = self.alloc.create(std.atomic.Queue(TaskId).Node) catch unreachable; task_node.data = task_id; self.ready.put(task_node); for (self.workers.items) |worker| { worker.wakeup.set(); } } /// Workers submit their results through this method. fn addTaskResult(self: *Self, res: TaskResultInfo) void { // log.debug("task done processing", .{}); // TODO: Ensure allocator is thread safe or use our own array list with lock. const res_node = self.alloc.create(std.atomic.Queue(TaskResultInfo).Node) catch unreachable; res_node.data = res; self.done.put(res_node); // Notify that we have done tasks. self.done_notify.set(); } /// Should be called by the main thread to process done and dispatch subsequent tasks. pub fn processDone(self: *Self) void { while (self.done.get()) |n| { // log.debug("processed done task", .{}); const task_id = n.data.task_id; // We don't need to acquire the tasks lock here since only the main thread (same thread) can modify it. const task_info = self.tasks.getNoCheck(task_id); switch (n.data.result) { .Success => { if (task_info.has_cb) { task_info.invokeSuccessCallback(); } task_info.deinit(self.alloc); }, .Failure => |res| { if (task_info.has_cb) { task_info.invokeFailureCallback(res); } task_info.deinit(self.alloc); }, .Requeue => |res| { // TODO: Allocate into dense array. const handle = self.alloc.create(TaskTimer) catch unreachable; handle.super.data = self; _ = uv.uv_timer_init(self.uv_loop, &handle.super); _ = uv.uv_timer_start(&handle.super, onTaskTimer, res.delay_ms, 0); }, } self.alloc.destroy(n); self.tasks_mutex.lock(); defer self.tasks_mutex.unlock(); self.tasks.remove(task_id); self.num_unfinished_tasks -= 1; } } fn onTaskTimer(ptr: [*c]uv.uv_timer_t) callconv(.C) void { const timer = @ptrCast(*TaskTimer, ptr); const self = stdx.mem.ptrCastAlign(*Self, timer.super.data); self.addReadyTaskAndNotify(timer.task_id); uv.uv_close(@ptrCast(*uv.uv_handle_t, ptr), onCloseTaskTimer); } fn onCloseTaskTimer(ptr: [*c]uv.uv_handle_t) callconv(.C) void { const timer = @ptrCast(*TaskTimer, ptr); const self = stdx.mem.ptrCastAlign(*Self, timer.super.data); self.alloc.destroy(timer); } }; const TaskTimer = struct { super: uv.uv_timer_t, task_id: TaskId, }; pub fn TaskOutput(comptime Task: type) type { const Result = comptime stdx.meta.FieldType(Task, .res); if (@typeInfo(Result) == .ErrorUnion) { return @typeInfo(Result).ErrorUnion.payload; } else { return Result; } } // A thread is tied to a worker which simply requests the next task to work on. const Worker = struct { const Self = @This(); thread: std.Thread, queue: *WorkQueue, wakeup: std.Thread.ResetEvent, close_flag: std.atomic.Atomic(bool), fn init(self: *Self, queue: *WorkQueue) void { self.* = .{ .thread = undefined, .queue = queue, .wakeup = undefined, .close_flag = std.atomic.Atomic(bool).init(false), }; self.wakeup.reset(); } fn deinit(self: *Self) void { self.thread.detach(); } fn loop(self: *Self) void { while (true) { if (self.close_flag.load(.Acquire)) { break; } while (self.queue.ready.get()) |n| { // log.debug("Worker on thread: {} received work", .{std.Thread.getCurrentId()}); const task_id = n.data; self.queue.alloc.destroy(n); const task_info = self.queue.getTaskInfo(task_id); if (task_info.task.process()) |res| { self.queue.addTaskResult(.{ .task_id = task_id, .result = res, }); } else |err| { self.queue.addTaskResult(.{ .task_id = task_id, .result = .{ .Failure = err }, }); } } // Wait until the next task is added. self.wakeup.wait(); self.wakeup.reset(); } // Reuse flag to indicate the thread is done. self.close_flag.store(false, .Release); } }; const TaskId = u32; const TaskInfo = struct { const Self = @This(); task: TaskIface, cb_ctx_ptr: *anyopaque, success_cb: fn(ctx_ptr: *anyopaque, ptr: *anyopaque) void, failure_cb: fn(ctx_ptr: *anyopaque, err: anyerror) void, deinit_fn: fn(self: Self, alloc: std.mem.Allocator) void, has_cb: bool, fn initWithCb(comptime TaskImpl: type, task_ptr: *TaskImpl, ctx_ptr: anytype, comptime success_cb: fn (std.meta.Child(@TypeOf(ctx_ptr)), TaskOutput(TaskImpl)) void, comptime failure_cb: fn (std.meta.Child(@TypeOf(ctx_ptr)), anyerror) void, ) Self { const Context = std.meta.Child(@TypeOf(ctx_ptr)); const gen = struct { fn success_cb(_ctx_ptr: *anyopaque, ptr: *anyopaque) void { const ctx = stdx.mem.ptrCastAlign(*Context, _ctx_ptr); const orig_ptr = stdx.mem.ptrCastAlign(*TaskImpl, ptr); const ResultType = comptime stdx.meta.FieldType(TaskImpl, .res); if (@typeInfo(ResultType) == .ErrorUnion) { return @call(.{ .modifier = .always_inline }, success_cb, .{ ctx.*, orig_ptr.res catch unreachable }); } else { return @call(.{ .modifier = .always_inline }, success_cb, .{ ctx.*, orig_ptr.res }); } } fn failure_cb(_ctx_ptr: *anyopaque, err: anyerror) void { const ctx = stdx.mem.ptrCastAlign(*Context, _ctx_ptr); return @call(.{ .modifier = .always_inline }, failure_cb, .{ ctx.*, err }); } fn deinit(self: Self, alloc: std.mem.Allocator) void { self.task.deinit(); const orig_ptr = stdx.mem.ptrCastAlign(*TaskImpl, self.task.ptr); alloc.destroy(orig_ptr); const orig_ctx_ptr = stdx.mem.ptrCastAlign(*Context, self.cb_ctx_ptr); alloc.destroy(orig_ctx_ptr); } }; return .{ .task = TaskIface.init(task_ptr), .cb_ctx_ptr = ctx_ptr, .success_cb = gen.success_cb, .failure_cb = gen.failure_cb, .deinit_fn = gen.deinit, .has_cb = true, }; } fn deinit(self: Self, alloc: std.mem.Allocator) void { self.deinit_fn(self, alloc); } fn invokeSuccessCallback(self: Self) void { self.success_cb(self.cb_ctx_ptr, self.task.ptr); } fn invokeFailureCallback(self: Self, err: anyerror) void { self.failure_cb(self.cb_ctx_ptr, err); } }; const TaskIface = struct { const Self = @This(); const VTable = struct { process: fn (ptr: *anyopaque) anyerror!TaskResult, deinit: fn (ptr: *anyopaque) void, }; ptr: *anyopaque, vtable: *const VTable, pub fn init(impl_ptr: anytype) Self { const ImplPtr = @TypeOf(impl_ptr); const Impl = std.meta.Child(ImplPtr); const gen = struct { const vtable = VTable{ .process = _process, .deinit = _deinit, }; fn _process(ptr: *anyopaque) anyerror!TaskResult { const self = stdx.mem.ptrCastAlign(ImplPtr, ptr); return @call(.{ .modifier = .always_inline }, Impl.process, .{ self }); } fn _deinit(ptr: *anyopaque) void { const self = stdx.mem.ptrCastAlign(ImplPtr, ptr); return @call(.{ .modifier = .always_inline }, Impl.deinit, .{ self }); } }; return .{ .ptr = impl_ptr, .vtable = &gen.vtable, }; } fn process(self: Self) !TaskResult { return self.vtable.process(self.ptr); } fn deinit(self: Self) void { self.vtable.deinit(self.ptr); } }; const TaskResultInfo = struct { task_id: TaskId, result: TaskResult, }; pub const TaskResult = union(enum) { // Success, success callback should be invoked at processDone. Success: void, // Failure, failure callback should be invoked at processDone. Failure: anyerror, // Requeue, set a timeout to requeue the task at processDone. // TODO: Although this is implemented, it remains untested since the use case ended up using a different method. Requeue: struct { delay_ms: u32 }, };
runtime/work_queue.zig
const std = @import("std"); const stdx = @import("stdx"); const t = stdx.testing; const log = stdx.log.scoped(.parser_manual_test); const _parser = @import("parser.zig"); const Parser = _parser.Parser; const DebugInfo = _parser.DebugInfo; const ParseConfig = _parser.ParseConfig; const _grammar = @import("grammar.zig"); const Grammar = _grammar.Grammar; const builder = @import("builder.zig"); const grammars = @import("grammars.zig"); // zig repo should be at "ProjectRoot/lib/zig" test "Parse zig big" { const path = "./lib/zig/src/Sema.zig"; const file = std.fs.cwd().openFile(path, .{}) catch unreachable; defer file.close(); const src = file.readToEndAlloc(t.alloc, 1024 * 1024 * 10) catch unreachable; defer t.alloc.free(src); var grammar: Grammar = undefined; try builder.initGrammar(&grammar, t.alloc, grammars.ZigGrammar); defer grammar.deinit(); var parser = Parser.init(t.alloc, &grammar); defer parser.deinit(); var debug: DebugInfo = undefined; debug.init(t.alloc); defer debug.deinit(); var str_buf = std.ArrayList(u8).init(t.alloc); defer str_buf.deinit(); // stdx.debug.flag = true; const Config: ParseConfig = .{ .is_incremental = false }; var res = parser.parseDebug(Config, src, &debug); defer res.deinit(); if (!res.success) { str_buf.clearRetainingCapacity(); res.ast.formatContextAtToken(str_buf.writer(), res.err_token_id); log.warn("{s}", .{str_buf.items}); // buf.clearRetainingCapacity(); // zig_parser.tokenizer.formatTokens(buf.writer()); // log.warn("{s}", .{buf.items}); // buf.clearRetainingCapacity(); // ast.formatTree(buf.writer()); // log.warn("{s}", .{buf.items}); } try t.eq(debug.stats.parse_match_ops, 3621886); try t.eq(debug.stats.parse_rule_ops_no_cache, 1039435); const stmts = res.ast.getChildNodeList(res.ast.mb_root.?, 0); try t.eq(stmts.len, 415); } test "Parse zig std" { const trace = stdx.debug.trace(); defer trace.endPrint("parsed zig std"); var grammar: Grammar = undefined; try builder.initGrammar(&grammar, t.alloc, grammars.ZigGrammar); defer grammar.deinit(); var parser = Parser.init(t.alloc, &grammar); defer parser.deinit(); const Config: ParseConfig = .{ .is_incremental = false }; var str_buf = std.ArrayList(u8).init(t.alloc); defer str_buf.deinit(); const path = "./lib/zig/lib/std"; var dir = try std.fs.cwd().openDir(path, .{ .iterate = true }); defer dir.close(); // var debug: DebugInfo = undefined; // debug.init(t.alloc); // defer debug.deinit(); var walker = try dir.walk(t.alloc); defer walker.deinit(); while (try walker.next()) |it| { if (it.kind == .File) { if (!stdx.string.endsWith(it.path, ".zig")) { continue; } if (stdx.string.endsWith(it.path, "_test.zig")) { continue; } log.warn("Parsing: {s}", .{it.path}); const file = dir.openFile(it.path, .{}) catch unreachable; defer file.close(); const src = file.readToEndAlloc(t.alloc, 1024 * 1024 * 10) catch unreachable; defer t.alloc.free(src); var res = parser.parse(Config, src); // var res = parser.parseDebug(Config, src, &debug); defer res.deinit(); if (!res.success) { str_buf.clearRetainingCapacity(); res.ast.formatContextAtToken(str_buf.writer(), res.err_token_id); log.warn("{s}", .{str_buf.items}); // str_buf.clearRetainingCapacity(); // debug.formatMaxCallStack(Config, &res.ast, str_buf.writer()); // log.warn("{s}", .{str_buf.items}); // str_buf.clearRetainingCapacity(); // res.ast.formatTokens(str_buf.writer()); // log.warn("{s}", .{str_buf.items}); try t.fail(); } const stmts = res.ast.getChildNodeList(res.ast.mb_root.?, 0); log.warn("{} statements", .{stmts.len}); } } }
parser/parser_manual.test.zig
const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const expect = std.testing.expect; const expectEqualStrings = std.testing.expectEqualStrings; test "call result of if else expression" { try expect(mem.eql(u8, f2(true), "a")); try expect(mem.eql(u8, f2(false), "b")); } fn f2(x: bool) []const u8 { return (if (x) fA else fB)(); } fn fA() []const u8 { return "a"; } fn fB() []const u8 { return "b"; } test "memcpy and memset intrinsics" { try testMemcpyMemset(); // TODO add comptime test coverage //comptime try testMemcpyMemset(); } fn testMemcpyMemset() !void { var foo: [20]u8 = undefined; var bar: [20]u8 = undefined; @memset(&foo, 'A', foo.len); @memcpy(&bar, &foo, bar.len); try expect(bar[0] == 'A'); try expect(bar[11] == 'A'); try expect(bar[19] == 'A'); } const OpaqueA = opaque {}; const OpaqueB = opaque {}; test "variable is allowed to be a pointer to an opaque type" { var x: i32 = 1234; _ = hereIsAnOpaqueType(@ptrCast(*OpaqueA, &x)); } fn hereIsAnOpaqueType(ptr: *OpaqueA) *OpaqueA { var a = ptr; return a; } test "take address of parameter" { try testTakeAddressOfParameter(12.34); } fn testTakeAddressOfParameter(f: f32) !void { const f_ptr = &f; try expect(f_ptr.* == 12.34); } test "pointer to void return type" { try testPointerToVoidReturnType(); } fn testPointerToVoidReturnType() anyerror!void { const a = testPointerToVoidReturnType2(); return a.*; } const test_pointer_to_void_return_type_x = void{}; fn testPointerToVoidReturnType2() *const void { return &test_pointer_to_void_return_type_x; } test "array 2D const double ptr" { const rect_2d_vertexes = [_][1]f32{ [_]f32{1.0}, [_]f32{2.0}, }; try testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]); } fn testArray2DConstDoublePtr(ptr: *const f32) !void { const ptr2 = @ptrCast([*]const f32, ptr); try expect(ptr2[0] == 1.0); try expect(ptr2[1] == 2.0); } test "double implicit cast in same expression" { var x = @as(i32, @as(u16, nine())); try expect(x == 9); } fn nine() u8 { return 9; } test "struct inside function" { try testStructInFn(); comptime try testStructInFn(); } fn testStructInFn() !void { const BlockKind = u32; const Block = struct { kind: BlockKind, }; var block = Block{ .kind = 1234 }; block.kind += 1; try expect(block.kind == 1235); } test "fn call returning scalar optional in equality expression" { try expect(getNull() == null); } fn getNull() ?*i32 { return null; } var global_foo: *i32 = undefined; test "global variable assignment with optional unwrapping with var initialized to undefined" { const S = struct { var data: i32 = 1234; fn foo() ?*i32 { return &data; } }; global_foo = S.foo() orelse { @panic("bad"); }; try expect(global_foo.* == 1234); } test "peer result location with typed parent, runtime condition, comptime prongs" { const S = struct { fn doTheTest(arg: i32) i32 { const st = Structy{ .bleh = if (arg == 1) 1 else 1, }; if (st.bleh == 1) return 1234; return 0; } const Structy = struct { bleh: i32, }; }; try expect(S.doTheTest(0) == 1234); try expect(S.doTheTest(1) == 1234); } fn ZA() type { return struct { b: B(), const Self = @This(); fn B() type { return struct { const Self = @This(); }; } }; } test "non-ambiguous reference of shadowed decls" { try expect(ZA().B().Self != ZA().Self); } test "use of declaration with same name as primitive" { const S = struct { const @"u8" = u16; const alias = @"u8"; }; const a: S.u8 = 300; try expect(a == 300); const b: S.alias = 300; try expect(b == 300); const @"u8" = u16; const c: @"u8" = 300; try expect(c == 300); } fn emptyFn() void {} test "constant equal function pointers" { const alias = emptyFn; try expect(comptime x: { break :x emptyFn == alias; }); } test "multiline string literal is null terminated" { const s1 = \\one \\two) \\three ; const s2 = "one\ntwo)\nthree"; try expect(std.cstr.cmp(s1, s2) == 0); } test "self reference through fn ptr field" { const S = struct { const A = struct { f: fn (A) u8, }; fn foo(a: A) u8 { _ = a; return 12; } }; var a: S.A = undefined; a.f = S.foo; try expect(a.f(a) == 12); } test "global variable initialized to global variable array element" { try expect(global_ptr == &gdt[0]); } const GDTEntry = struct { field: i32, }; var gdt = [_]GDTEntry{ GDTEntry{ .field = 1 }, GDTEntry{ .field = 2 }, }; var global_ptr = &gdt[0]; test "global constant is loaded with a runtime-known index" { const S = struct { fn doTheTest() !void { var index: usize = 1; const ptr = &pieces[index].field; try expect(ptr.* == 2); } const Piece = struct { field: i32, }; const pieces = [_]Piece{ Piece{ .field = 1 }, Piece{ .field = 2 }, Piece{ .field = 3 } }; }; try S.doTheTest(); }
test/behavior/basic_llvm.zig
const std = @import("std"); const debug = std.debug; const mem = std.mem; const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; pub fn build(b: *Builder) !void { const fontconfig_cflags = try b.exec([][]const u8{ "pkg-config", "--cflags", "fontconfig" }); const freetype2_cflags = try b.exec([][]const u8{ "pkg-config", "--cflags", "freetype2" }); const cflags = try concat(b.allocator, []const u8, [][]const []const u8{ [][]const u8{ "-std=gnu99", "-DVERSION=\"0.8.1\"", "-D_XOPEN_SOURCE=600", }, try split(b.allocator, fontconfig_cflags, " \t\r\n"), try split(b.allocator, freetype2_cflags, " \t\r\n"), }); const exe = b.addCExecutable("zt"); exe.addCompileFlags(cflags); linkLibs(exe, [][]const u8{ "m", "rt", "X11", "util", "Xft", }); try linkPackageConfigLibs(b, exe, "fontconfig"); try linkPackageConfigLibs(b, exe, "freetype2"); inline for ([][]const u8{ "st", "x", }) |obj_name| { const obj = b.addCObject(obj_name, obj_name ++ ".c"); obj.addCompileFlags(cflags); exe.addObject(obj); } inline for ([][]const u8{"st"}) |obj_name| { const obj = b.addObject(obj_name ++ "-zig", "src/" ++ obj_name ++ ".zig"); exe.addObject(obj); } const run_step = b.step("run", "Run the zt"); const run_cmd = b.addCommand(".", b.env_map, [][]const u8{exe.getOutputPath()}); run_step.dependOn(&run_cmd.step); run_cmd.step.dependOn(&exe.step); b.default_step.dependOn(&exe.step); } fn linkLibs(exe: *LibExeObjStep, libs: []const []const u8) void { for (libs) |lib| exe.linkSystemLibrary(lib); } fn linkPackageConfigLibs(b: *Builder, exe: *LibExeObjStep, package: []const u8) !void { const libs = try b.exec([][]const u8{ "pkg-config", "--libs", package }); var lib_iter = mem.tokenize(libs, " \t\r\n"); while (lib_iter.next()) |lib| { if (!mem.startsWith(u8, lib, "-l")) return error.Unexpected; exe.linkSystemLibrary(lib[2..]); } } fn concat(allocator: *mem.Allocator, comptime T: type, items: []const []const T) ![]T { var res = std.ArrayList(T).init(allocator); defer res.deinit(); for (items) |sub_items| { for (sub_items) |item| try res.append(item); } return res.toOwnedSlice(); } fn split(allocator: *mem.Allocator, buffer: []const u8, split_bytes: []const u8) ![][]const u8 { var res = std.ArrayList([]const u8).init(allocator); defer res.deinit(); var iter = mem.tokenize(buffer, split_bytes); while (iter.next()) |s| try res.append(s); return res.toOwnedSlice(); }
build.zig
const std = @import("std"); const kernel = @import("../../kernel.zig"); const Spinlock = kernel.arch.Spinlock; // the UART control registers. // some have different meanings for // read vs write. // http://byterunner.com/16550.html const RHR = 0; // receive holding register (for input bytes) const THR = 0; // transmit holding register (for output bytes) const IER = 1; // interrupt enable register const FCR = 2; // FIFO control register const ISR = 2; // interrupt status register const LCR = 3; // line control register const LSR = 5; // line status register /// UART Driver /// seems not thread-safe, use with caution when in SMP mode pub fn UART(comptime base_address: u64) type { return struct { const ptr = @intToPtr([*c]volatile u8, base_address); /// Return an uninitialized Uart instance /// init set baud rate and enable UART /// We need this comptime parameter to avoid locking, which causes to enable interrupts pub fn init(self: *@This(), comptime lock: bool) void { if (lock) self.lock.acquire(); defer if (lock) self.lock.release(); // Volatile needed // using C-type ptr // Disable interrupt ptr[IER] = 0x00; // Enter setting mode ptr[LCR] = 0x80; // Set baud rate to 38.4K, other value may be valid // but here just copy xv6 behaviour ptr[0] = 0x03; ptr[1] = 0x00; // Leave setting mode ptr[LCR] = 0x03; // Reset and enable FIFO ptr[FCR] = 0x07; // Re-enable interrupt ptr[IER] = 0x01; } pub inline fn raw_read() ?u8 { if (ptr[5] & 1 == 0) return null else return ptr[0]; } pub inline fn raw_write(byte: u8) void { // Wait until previous data is flushed while (ptr[5] & (1 << 5) == 0) {} // Write our data ptr[0] = byte; } /// Get a char from UART /// Return a optional u8, must check pub fn get(self: *@This()) ?u8 { self.lock.acquire(); defer self.lock.release(); const result = raw_read(); return result; } pub fn write_bytes(self: *@This(), bytes: []const u8, comptime lock: bool) void { if (lock) self.lock.acquire(); defer if (lock) self.lock.release(); for (bytes) |byte| { raw_write(byte); } } pub fn handle_interrupt(self: *@This()) void { if (self.get()) |byte| { switch (byte) { 8 => { kernel.arch.writer.print("{} {}", .{ byte, byte }) catch unreachable; }, else => kernel.arch.writer.print("{c}", .{byte}), } } } }; }
src/kernel/arch/riscv64/uart.zig
const builtin = @import("builtin"); const std = @import("std"); const math = std.math; const assert = std.debug.assert; const testing = std.testing; pub fn powci(comptime x: comptime_int, y: comptime_int) comptime_int { return if (y == 0) 1 else switch (x) { 0 => 0, 1 => 1, else => blk: { if (x == -1) { return if (y % 2 == 0) 1 else -1; } comptime var base = x; comptime var exp = y; comptime var acc = 1; while (exp > 1) { if (exp & 1 == 1) { acc = acc * base; } exp >>= 1; base = base * base; } if (exp == 1) { acc = acc * base; } break :blk acc; }, }; } // tests from zig std powi test "math.powci" { testing.expect(powci(-5, 3) == -125); testing.expect(powci(-16, 3) == -4096); testing.expect(powci(-91, 3) == -753571); testing.expect(powci(-36, 6) == 2176782336); testing.expect(powci(-2, 15) == -32768); testing.expect(powci(-5, 7) == -78125); testing.expect(powci(6, 2) == 36); testing.expect(powci(5, 4) == 625); testing.expect(powci(12, 6) == 2985984); testing.expect(powci(34, 2) == 1156); testing.expect(powci(16, 3) == 4096); testing.expect(powci(34, 6) == 1544804416); } test "math.powci.special" { testing.expect(powci(-1, 3) == -1); testing.expect(powci(-1, 2) == 1); testing.expect(powci(-1, 16) == 1); testing.expect(powci(-1, 6) == 1); testing.expect(powci(-1, 15) == -1); testing.expect(powci(-1, 7) == -1); testing.expect(powci(1, 2) == 1); testing.expect(powci(1, 4) == 1); testing.expect(powci(1, 6) == 1); testing.expect(powci(1, 2) == 1); testing.expect(powci(1, 3) == 1); testing.expect(powci(1, 6) == 1); testing.expect(powci(6, 0) == 1); testing.expect(powci(5, 0) == 1); testing.expect(powci(12, 0) == 1); testing.expect(powci(34, 0) == 1); testing.expect(powci(16, 0) == 1); testing.expect(powci(34, 0) == 1); }
src/powci.zig
const std = @import("std"); const ArrayList = std.ArrayList; const Builder = @import("std").build.Builder; pub fn build(b: *Builder) !void { const exe = b.addExecutable("BootX64", "src/kernel/main.zig"); exe.addAssemblyFile("src/kernel/arch/x86/platform.s"); exe.addAssemblyFile("src/kernel/arch/x86/vmem.s"); exe.addAssemblyFile("src/kernel/arch/x86/gdt.s"); exe.addAssemblyFile("src/kernel/arch/x86/isr.s"); exe.setBuildMode(b.standardReleaseOptions()); exe.setTarget(.{ .cpu_arch = .x86_64, .os_tag = .uefi, }); exe.setOutputDir("build/EFI/BOOT"); b.default_step.dependOn(&exe.step); const extractDebugInfo = b.addSystemCommand(&[_][]const u8{ "objcopy", "-j", ".text", "-j", ".debug_info", "-j", ".debug_abbrev", "-j", ".debug_loc", "-j", ".debug_ranges", "-j", ".debug_pubnames", "-j", ".debug_pubtypes", "-j", ".debug_line", "-j", ".debug_macinfo", "-j", ".debug_str", "--target=efi-app-x86_64", "build/EFI/BOOT/BootX64.efi", "build/EFI/BOOT/BootX64.debug", }); extractDebugInfo.step.dependOn(&exe.step); b.default_step.dependOn(&extractDebugInfo.step); const uefiStartupScript = b.addWriteFile("startup.nsh", "\\EFI\\BOOT\\BootX64.efi"); const uefi_fw_path = std.os.getenv("OVMF_FW_CODE_PATH") orelse "ovmf_code_x64.bin"; var uefi_flag_buffer: [200]u8 = undefined; const uefi_code = std.fmt.bufPrint(uefi_flag_buffer[0..], "if=pflash,format=raw,readonly,file={s}", .{uefi_fw_path}) catch unreachable; var qemu_args_al = ArrayList([]const u8).init(b.allocator); defer qemu_args_al.deinit(); const use_local_qemu = b.option(bool, "use-local-qemu", "Run the kernel using the QEMU binary in vendor/qemu/build.") orelse false; const disable_display = b.option(bool, "disable-display", "Disable the QEMU display.") orelse false; const disable_debugger = b.option(bool, "disable-debugger", "Disable the QEMU gdbserver.") orelse false; const disable_reboot = b.option(bool, "disable-reboot", "Disable the autoreboot mechanism, useful for triple faults debugging.") orelse true; const disable_shutdown = b.option(bool, "disable-shutdown", "Disable the shutdown mechanism, useful for triple faults debugging.") orelse false; const wait_debugger_on_startup = b.option(bool, "wait-debugger-on-startup", "Wait for debugger at startup.") orelse false; const debug_events = b.option([]const u8, "debug-events", "List separated by comma of QEMU debug events to use") orelse "cpu_reset"; const guest_memory_size = b.option([]const u8, "guest-memory-size", "Amount of memory allocated to the guest VM with the <integer><size> format, e.g. 128M, 1G, etc.") orelse "128M"; if (use_local_qemu) { try qemu_args_al.append("vendor/qemu/build/qemu-system-x86_64"); } else { try qemu_args_al.append("qemu-system-x86_64"); } try qemu_args_al.append("-nodefaults"); try qemu_args_al.append("-serial"); try qemu_args_al.append("stdio"); try qemu_args_al.append("-vga"); try qemu_args_al.append("std"); if (disable_display) { try qemu_args_al.append("-display"); try qemu_args_al.append("none"); } if (!disable_debugger) { try qemu_args_al.append("-s"); } if (wait_debugger_on_startup) { try qemu_args_al.append("-S"); } try qemu_args_al.append("-m"); try qemu_args_al.append(guest_memory_size); try qemu_args_al.append("-boot"); try qemu_args_al.append("d"); try qemu_args_al.append("-drive"); try qemu_args_al.append(uefi_code); try qemu_args_al.append("-drive"); try qemu_args_al.append("format=raw,file=fat:rw:build"); try qemu_args_al.append("-monitor"); try qemu_args_al.append("unix:qemu-monitor-socket,server,nowait"); try qemu_args_al.append("-debugcon"); try qemu_args_al.append("file:build/debug.log"); try qemu_args_al.append("-global"); try qemu_args_al.append("isa-debugcon.iobase=0x402"); try qemu_args_al.append("-d"); try qemu_args_al.append(debug_events); if (disable_reboot) { try qemu_args_al.append("-no-reboot"); } if (disable_shutdown) { try qemu_args_al.append("-no-shutdown"); } var qemu_args = qemu_args_al.toOwnedSlice(); const run_cmd = b.addSystemCommand(qemu_args); run_cmd.step.dependOn(b.getInstallStep()); run_cmd.step.dependOn(&uefiStartupScript.step); const run = b.step("run", "run with qemu"); run.dependOn(&run_cmd.step); }
build.zig
const std = @import("std"); const warn = std.debug.print; const Allocator = std.mem.Allocator; const config = @import("./config.zig"); const toot_lib = @import("./toot.zig"); const thread = @import("./thread.zig"); const guilib = @import("./gui/gtk.zig"); const GUIError = error{Init}; const Column = guilib.Column; var columns: std.ArrayList(*Column) = undefined; var allocator: *Allocator = undefined; var settings: *config.Settings = undefined; pub fn init(alloca: *Allocator, set: *config.Settings) !void { warn("gui init allocator {*} {}\n", .{ alloca, alloca }); settings = set; allocator = alloca; columns = std.ArrayList(*Column).init(allocator); try guilib.init(alloca, set); } var myActor: *thread.Actor = undefined; var stop = false; pub fn go(data: ?*anyopaque) callconv(.C) ?*anyopaque { warn("gui {} thread start &actor_data: {*} data: {}\n", .{ guilib.libname(), data, data }); var data8 = @alignCast(@alignOf(thread.Actor), data); myActor = @ptrCast(*thread.Actor, data8); warn("gui {} thread start &actor: {*} actor:{}\n", .{ guilib.libname(), myActor, myActor }); if (guilib.gui_setup(myActor)) { // mainloop while (!stop) { stop = guilib.mainloop(); } warn("last mainloop {}\n", .{guilib.mainloop()}); guilib.gui_end(); } else |err| { warn("gui error {}\n", .{err}); } return null; } pub fn schedule(func: ?fn (?*anyopaque) callconv(.C) c_int, param: ?*anyopaque) void { guilib.schedule(func, param); } pub fn show_main_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.show_main_schedule(in); } pub fn add_column_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.add_column_schedule(in); } pub fn column_remove_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.column_remove_schedule(in); } pub fn column_config_oauth_url_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.column_config_oauth_url_schedule(in); } pub fn update_column_config_oauth_finalize_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.update_column_config_oauth_finalize_schedule(in); } pub fn update_column_ui_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.update_column_ui_schedule(in); } pub fn update_column_netstatus_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.update_column_netstatus_schedule(in); } pub fn update_column_toots_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.update_column_toots_schedule(in); } pub fn update_author_photo_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.update_author_photo_schedule(in); } pub const TootPic = guilib.TootPic; pub fn toot_media_schedule(in: ?*anyopaque) callconv(.C) c_int { return guilib.toot_media_schedule(in); }
src/gui.zig
const builtin = @import("builtin"); const std = @import("std"); const Allocator = std.mem.Allocator; const mustache = @import("mustache"); const TIMES = if (builtin.mode == .Debug) 10_000 else 1_000_000; // Run tests on full featured mustache specs, or minimum settings for the use case const full = true; const features: mustache.options.Features = if (full) .{} else .{ .preseve_line_breaks_and_indentation = false, .lambdas = .Disabled, }; const Mode = enum { Buffer, Alloc, Writer, }; pub fn main() anyerror!void { var tmp_dir = std.testing.tmpDir(.{}); defer tmp_dir.cleanup(); var file = try tmp_dir.dir.createFile("test.mustache", .{ .truncate = true }); defer file.close(); var file_writer = std.io.bufferedWriter(file.writer()); var buffer: [1024]u8 = undefined; if (builtin.mode == .Debug) { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); try simpleTemplate(allocator, &buffer, .Buffer, std.io.null_writer); try simpleTemplate(allocator, &buffer, .Alloc, std.io.null_writer); try simpleTemplate(allocator, &buffer, .Writer, file_writer); try file_writer.flush(); try partialTemplates(allocator, &buffer, .Buffer, std.io.null_writer); try partialTemplates(allocator, &buffer, .Alloc, std.io.null_writer); try parseTemplates(allocator); } else { const allocator = std.heap.raw_c_allocator; try simpleTemplate(allocator, &buffer, .Buffer, std.io.null_writer); try simpleTemplate(allocator, &buffer, .Alloc, std.io.null_writer); try simpleTemplate(allocator, &buffer, .Writer, file_writer); try file_writer.flush(); try partialTemplates(allocator, &buffer, .Buffer, std.io.null_writer); try partialTemplates(allocator, &buffer, .Alloc, std.io.null_writer); try parseTemplates(allocator); } } pub fn simpleTemplate(allocator: Allocator, buffer: []u8, comptime mode: Mode, writer: anytype) !void { const template_text = "<title>{{title}}</title><h1>{{ title }}</h1><div>{{{body}}}</div>"; const fmt_template = "<title>{[title]s}</title><h1>{[title]s}</h1><div>{[body]s}</div>"; const Data = struct { title: []const u8, body: []const u8 }; var data: Data = .{ .title = "Hello, Mustache!", .body = "This is a really simple test of the rendering!", }; var template = (try mustache.parseText(allocator, template_text, .{}, .{ .copy_strings = false, .features = features })).success; defer template.deinit(allocator); std.debug.print("Mode {s}\n", .{@tagName(mode)}); std.debug.print("----------------------------------\n", .{}); const reference = try repeat("Reference: Zig fmt", zigFmt, .{ allocator, buffer, mode, fmt_template, data, writer, }, null); _ = try repeat("Mustache pre-parsed", preParsed, .{ allocator, buffer, mode, template, data, writer }, reference); if (mode != .Buffer) _ = try repeat("Mustache not parsed", notParsed, .{ allocator, buffer, mode, template_text, data, writer }, reference); std.debug.print("\n\n", .{}); } pub fn partialTemplates(allocator: Allocator, buffer: []u8, comptime mode: Mode, writer: anytype) !void { const template_text = \\{{>head.html}} \\<body> \\ <div>{{body}}</div> \\ {{>footer.html}} \\</body> ; const head_partial_text = \\<head> \\ <title>{{title}}</title> \\</head> ; const footer_partial_text = "<footer>Sup?</footer>"; var template = (try mustache.parseText(allocator, template_text, .{}, .{ .copy_strings = false, .features = features })).success; defer template.deinit(allocator); var head_template = (try mustache.parseText(allocator, head_partial_text, .{}, .{ .copy_strings = false, .features = features })).success; defer head_template.deinit(allocator); var footer_template = (try mustache.parseText(allocator, footer_partial_text, .{}, .{ .copy_strings = false, .features = features })).success; defer footer_template.deinit(allocator); var partial_templates = std.StringHashMap(mustache.Template).init(allocator); defer partial_templates.deinit(); try partial_templates.put("head.html", head_template); try partial_templates.put("footer.html", footer_template); const partial_templates_text = .{ .{ "head.html", head_partial_text }, .{ "footer.html", footer_partial_text }, }; const Data = struct { title: []const u8, body: []const u8 }; var data: Data = .{ .title = "Hello, Mustache!", .body = "This is a really simple test of the rendering!", }; std.debug.print("Mode {s}\n", .{@tagName(mode)}); std.debug.print("----------------------------------\n", .{}); _ = try repeat("Mustache pre-parsed partials", preParsedPartials, .{ allocator, buffer, mode, template, partial_templates, data, writer }, null); if (mode != .Buffer) _ = try repeat("Mustache not parsed partials", notParsedPartials, .{ allocator, buffer, mode, template_text, partial_templates_text, data, writer }, null); std.debug.print("\n\n", .{}); } pub fn parseTemplates(allocator: Allocator) !void { std.debug.print("----------------------------------\n", .{}); _ = try repeat("Parse", parse, .{allocator}, null); std.debug.print("\n\n", .{}); } fn repeat(comptime caption: []const u8, comptime func: anytype, args: anytype, reference: ?i128) !i128 { var index: usize = 0; var total_bytes: usize = 0; const start = std.time.nanoTimestamp(); while (index < TIMES) : (index += 1) { total_bytes += try @call(.{}, func, args); } const ellapsed = std.time.nanoTimestamp() - start; printSummary(caption, ellapsed, total_bytes, reference); return ellapsed; } fn printSummary(caption: []const u8, ellapsed: i128, total_bytes: usize, reference: ?i128) void { std.debug.print("{s}\n", .{caption}); std.debug.print("Total time {d:.3}s\n", .{@intToFloat(f64, ellapsed) / std.time.ns_per_s}); if (reference) |reference_time| { const perf = if (reference_time > 0) @intToFloat(f64, ellapsed) / @intToFloat(f64, reference_time) else 0; std.debug.print("Comparation {d:.3}x {s}\n", .{ perf, (if (perf > 0) "slower" else "faster") }); } std.debug.print("{d:.0} ops/s\n", .{TIMES / (@intToFloat(f64, ellapsed) / std.time.ns_per_s)}); std.debug.print("{d:.0} ns/iter\n", .{@intToFloat(f64, ellapsed) / TIMES}); std.debug.print("{d:.0} MB/s\n", .{(@intToFloat(f64, total_bytes) / 1024 / 1024) / (@intToFloat(f64, ellapsed) / std.time.ns_per_s)}); std.debug.print("\n", .{}); } fn zigFmt(allocator: Allocator, buffer: []u8, mode: Mode, comptime fmt_template: []const u8, data: anytype, writer: anytype) !usize { switch (mode) { .Buffer => { const ret = try std.fmt.bufPrint(buffer, fmt_template, data); return ret.len; }, .Writer => { var counter = std.io.countingWriter(writer); try std.fmt.format(counter.writer(), fmt_template, data); return counter.bytes_written; }, .Alloc => { const ret = try std.fmt.allocPrint(allocator, fmt_template, data); defer allocator.free(ret); return ret.len; }, } } fn preParsed(allocator: Allocator, buffer: []u8, mode: Mode, template: mustache.Template, data: anytype, writer: anytype) !usize { switch (mode) { .Buffer => { const ret = try mustache.bufRender(buffer, template, data); return ret.len; }, .Writer => { var counter = std.io.countingWriter(writer); try mustache.render(template, data, counter.writer()); return counter.bytes_written; }, .Alloc => { const ret = try mustache.allocRender(allocator, template, data); defer allocator.free(ret); return ret.len; }, } } fn preParsedPartials(allocator: Allocator, buffer: []u8, mode: Mode, template: mustache.Template, partial_templates: anytype, data: anytype, writer: anytype) !usize { switch (mode) { .Buffer => { var ret = try mustache.bufRenderPartials(buffer, template, partial_templates, data); return ret.len; }, .Writer => { var counter = std.io.countingWriter(writer); try mustache.renderPartials(template, partial_templates, data, counter.writer()); return counter.bytes_written; }, .Alloc => { const ret = try mustache.allocRenderPartials(allocator, template, partial_templates, data); defer allocator.free(ret); return ret.len; }, } } fn notParsed(allocator: Allocator, buffer: []u8, mode: Mode, template_text: []const u8, data: anytype, writer: anytype) !usize { switch (mode) { .Buffer => { _ = buffer; return 0; }, .Writer => { var counter = std.io.countingWriter(writer); try mustache.renderTextPartialsWithOptions(allocator, template_text, {}, data, counter.writer(), .{ .features = features }); return counter.bytes_written; }, .Alloc => { const ret = try mustache.allocRenderTextPartialsWithOptions(allocator, template_text, {}, data, .{ .features = features }); defer allocator.free(ret); return ret.len; }, } } fn notParsedPartials(allocator: Allocator, buffer: []u8, mode: Mode, template_text: []const u8, partial_templates: anytype, data: anytype, writer: anytype) !usize { switch (mode) { .Buffer => { _ = buffer; return 0; }, .Writer => { var counter = std.io.countingWriter(writer); try mustache.renderTextPartialsWithOptions(allocator, template_text, partial_templates, data, counter.writer(), .{ .features = features }); return counter.bytes_written; }, .Alloc => { const ret = try mustache.allocRenderTextPartialsWithOptions(allocator, template_text, partial_templates, data, .{ .features = features }); defer allocator.free(ret); return ret.len; }, } } fn parse(allocator: Allocator) !usize { const template_text = \\<html>\ \\ <head>\ \\ <title>{{title}}</title>\ \\ </head> \\ <body>\ \\ {{#posts}}\ \\ <h1>{{title}}</h1>\ \\ <em>{{date}}</em>\ \\ <article>\ \\ {{{body}}}\ \\ </article>\ \\ {{/posts}}\ \\ </body>\ \\</html>\ ; var template = switch (try mustache.parseText(allocator, template_text, .{}, .{ .copy_strings = false, .features = features })) { .success => |template| template, else => unreachable, }; template.deinit(allocator); return template_text.len; }
benchmark/src/ramhorns_bench.zig
const std = @import("std"); const stdx = @import("stdx"); const graphics = @import("graphics"); const Color = graphics.Color; const log = stdx.log.scoped(.flex); const ui = @import("../ui.zig"); const module = @import("../module.zig"); /// Lays out children vertically. pub const Column = struct { props: struct { bg_color: ?Color = null, valign: ui.VAlign = .Top, stretch_width: bool = false, spacing: f32 = 0, /// Whether the columns's height will shrink to the total height of it's children or expand to the parent container's height. /// Expands to the parent container's height by default. /// flex and flex_fit are only used when expand is true. expand: bool = true, flex: u32 = 1, flex_fit: ui.FlexFit = .Exact, children: ui.FrameListPtr = ui.FrameListPtr.init(0, 0), }, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = self; return c.fragment(self.props.children); } pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { _ = self; const cstr = c.getSizeConstraint(); var vacant_size = cstr; var cur_y: f32 = 0; var max_child_width: f32 = 0; const total_spacing = if (c.node.children.items.len > 0) self.props.spacing * @intToFloat(f32, c.node.children.items.len-1) else 0; vacant_size.height -= total_spacing; // First pass computes non expanding children. var has_expanding_children = false; var flex_sum: u32 = 0; for (c.node.children.items) |it| { // Only Flex and Column make sense to do flex for a parent Column. if (it.vtable == module.GenWidgetVTable(Flex)) { const flex = it.getWidget(Flex); has_expanding_children = true; flex_sum += flex.props.flex; continue; } else if (it.vtable == module.GenWidgetVTable(Column)) { const col = it.getWidget(Column); if (col.props.expand) { has_expanding_children = true; flex_sum += col.props.flex; continue; } } var child_size = c.computeLayoutStretch(it, vacant_size, self.props.stretch_width, false); child_size.cropTo(vacant_size); c.setLayout(it, ui.Layout.init(0, cur_y, child_size.width, child_size.height)); cur_y += child_size.height + self.props.spacing; vacant_size.height -= child_size.height; if (child_size.width > max_child_width) { max_child_width = child_size.width; } } if (has_expanding_children) { cur_y = 0; const flex_unit_size = vacant_size.height / @intToFloat(f32, flex_sum); var max_child_size = ui.LayoutSize.init(vacant_size.width, 0); var carry_over_height: f32 = 0; for (c.node.children.items) |it| { var flex: u32 = std.math.maxInt(u32); var flex_fit: ui.FlexFit = undefined; if (it.vtable == module.GenWidgetVTable(Flex)) { const w = it.getWidget(Flex); flex = w.props.flex; flex_fit = w.props.flex_fit; } else if (it.vtable == module.GenWidgetVTable(Column)) { const col = it.getWidget(Column); if (col.props.expand) { flex = col.props.flex; flex_fit = col.props.flex_fit; } } if (flex == std.math.maxInt(u32)) { // Update the layout pos of sized children since this pass will include expanded children. c.setLayoutPos(it, 0, cur_y); cur_y += c.getLayout(it).height; continue; } max_child_size.height = flex_unit_size * @intToFloat(f32, flex) + carry_over_height; if (carry_over_height > 0) { carry_over_height = 0; } var child_size: ui.LayoutSize = undefined; switch (flex_fit) { .ShrinkAndGive => { child_size = c.computeLayoutStretch(it, max_child_size, self.props.stretch_width, false); child_size.cropTo(max_child_size); c.setLayout(it, ui.Layout.init(0, cur_y, child_size.width, child_size.height)); cur_y += child_size.height + self.props.spacing; if (child_size.height < max_child_size.height) { carry_over_height = max_child_size.height - child_size.height; } }, else => { child_size = c.computeLayoutStretch(it, max_child_size, self.props.stretch_width, true); child_size.cropTo(max_child_size); c.setLayout(it, ui.Layout.init(0, cur_y, child_size.width, child_size.height)); cur_y += child_size.height + self.props.spacing; if (child_size.width > max_child_width) { max_child_width = child_size.width; } } } if (child_size.width > max_child_width) { max_child_width = child_size.width; } } } else { // No expanding children. Check to realign vertically. if (self.props.expand and self.props.valign == .Bottom) { const inner_height = cur_y - self.props.spacing; var scratch_y = cstr.height - inner_height; for (c.node.children.items) |it| { c.setLayoutPos(it, 0, scratch_y); scratch_y += it.layout.height + self.props.spacing; } } } if (self.props.expand) { return ui.LayoutSize.init(max_child_width, cstr.height); } else { if (c.node.children.items.len > 0) { return ui.LayoutSize.init(max_child_width, cur_y - self.props.spacing); } else { return ui.LayoutSize.init(max_child_width, cur_y); } } } pub fn render(self: *Self, ctx: *ui.RenderContext) void { _ = self; _ = ctx; // const g = c.g; // const n = c.node; const props = self.props; if (props.bg_color != null) { // g.setFillColor(props.bg_color.?); // g.fillRect(n.layout.x, n.layout.y, n.layout.width, n.layout.height); } // TODO: draw border } }; pub const Row = struct { props: struct { bg_color: ?Color = null, flex: u32 = 1, valign: ui.VAlign = .Top, halign: ui.HAlign = .Left, spacing: f32 = 0, /// Whether the row's width will shrink to the total width of it's children or expand to the parent container's width. /// Expands to the parent container's width by default. expand: bool = true, children: ui.FrameListPtr = ui.FrameListPtr.init(0, 0), }, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = self; return c.fragment(self.props.children); } pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { _ = self; const cstr = c.getSizeConstraint(); var vacant_size = cstr; var cur_x: f32 = 0; var max_child_height: f32 = 0; const total_spacing = if (c.node.children.items.len > 0) self.props.spacing * @intToFloat(f32, c.node.children.items.len-1) else 0; vacant_size.width -= total_spacing; // First pass computes non expanding children. var has_expanding_children = false; var flex_sum: u32 = 0; for (c.node.children.items) |it| { // Only Flex and Row make sense to do flex for a parent Row. if (it.vtable == module.GenWidgetVTable(Flex)) { const flex = it.getWidget(Flex); has_expanding_children = true; flex_sum += flex.props.flex; continue; } else if (it.vtable == module.GenWidgetVTable(Row)) { const row = it.getWidget(Row); if (row.props.expand) { has_expanding_children = true; flex_sum += row.props.flex; continue; } } var child_size = c.computeLayout(it, vacant_size); child_size.cropTo(vacant_size); c.setLayout(it, ui.Layout.init(cur_x, 0, child_size.width, child_size.height)); cur_x += child_size.width + self.props.spacing; vacant_size.width -= child_size.width; if (child_size.height > max_child_height) { max_child_height = child_size.height; } } if (has_expanding_children) { cur_x = 0; const flex_unit_size = vacant_size.width / @intToFloat(f32, flex_sum); var max_child_size = ui.LayoutSize.init(0, vacant_size.height); for (c.node.children.items) |it| { var flex: u32 = std.math.maxInt(u32); if (it.vtable == module.GenWidgetVTable(Flex)) { const w = it.getWidget(Flex); flex = w.props.flex; } else if (it.vtable == module.GenWidgetVTable(Row)) { const row = it.getWidget(Row); flex = row.props.flex; } if (flex == std.math.maxInt(u32)) { // Update the layout pos of sized children since this pass will include expanded children. c.setLayoutPos(it, cur_x, 0); cur_x += c.getLayout(it).width; continue; } max_child_size.width = flex_unit_size * @intToFloat(f32, flex); var child_size = c.computeLayoutStretch(it, max_child_size, true, false); child_size.cropTo(max_child_size); c.setLayout(it, ui.Layout.init(cur_x, 0, child_size.width, child_size.height)); cur_x += child_size.width + self.props.spacing; if (child_size.height > max_child_height) { max_child_height = child_size.height; } } } else { // No expanding children. Check to realign in x dim. if (self.props.expand and self.props.halign == .Right) { const inner_width = cur_x - self.props.spacing; var scratch_x = cstr.width - inner_width; for (c.node.children.items) |it| { c.setLayoutPos(it, scratch_x, 0); scratch_x += it.layout.width + self.props.spacing; } } } if (self.props.valign != .Top) { switch (self.props.valign) { .Center => { for (c.node.children.items) |child| { c.setLayoutPos(child, child.layout.x, (max_child_height - child.layout.height) * 0.5); } }, else => {}, } } if (self.props.expand) { return ui.LayoutSize.init(cstr.width, max_child_height); } else { if (c.node.children.items.len > 0) { return ui.LayoutSize.init(cur_x - self.props.spacing, max_child_height); } else { return ui.LayoutSize.init(cur_x, max_child_height); } } } pub fn render(self: *Self, c: *ui.RenderContext) void { _ = self; const g = c.g; const alo = c.getAbsLayout(); const props = self.props; if (props.bg_color != null) { g.setFillColor(props.bg_color.?); g.fillRect(alo.x, alo.y, alo.width, alo.height); } // TODO: draw border } }; /// Interpreted by Column or Row as a flexible widget. The flex property is used determine how it fits in the parent container. pub const Flex = struct { props: struct { child: ui.FrameId = ui.NullFrameId, flex: u32 = 1, flex_fit: ui.FlexFit = .Exact, /// When false, stretching is inherited by the parent. stretch_width: bool = false, }, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = c; return self.props.child; } /// Computes the child layout preferring to stretch it and returns the current constraint. pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { _ = self; const cstr = c.getSizeConstraint(); const node = c.getNode(); if (node.children.items.len == 0) { var res = ui.LayoutSize.init(0, 0); if (c.prefer_exact_width) { res.width = cstr.width; } if (c.prefer_exact_height) { res.height = cstr.height; } return res; } const child = node.children.items[0]; const stretch_width = if (self.props.stretch_width) true else c.prefer_exact_width; const child_size = c.computeLayoutStretch(child, cstr, stretch_width, c.prefer_exact_height); var res = child_size; if (c.prefer_exact_width) { res.width = cstr.width; } if (c.prefer_exact_height) { res.height = cstr.height; } c.setLayout(child, ui.Layout.init(0, 0, child_size.width, child_size.height)); return res; } };
ui/src/widgets/flex.zig
const std = @import("std"); const mem = std.mem; const meta = std.meta; const c = std.c; usingnamespace @import("c_api.zig"); const log = std.log.scoped(.zamqp); pub const boolean_t = c_int; pub const flags_t = u32; pub const channel_t = u16; pub const bytes_t = extern struct { len: usize, bytes: ?[*]const u8, pub fn init(buf: []const u8) bytes_t { if (buf.len == 0) return empty(); return .{ .len = buf.len, .bytes = buf.ptr }; } pub fn slice(self: bytes_t) ?[]const u8 { return (self.bytes orelse return null)[0..self.len]; } pub const initZ = amqp_cstring_bytes; pub fn empty() bytes_t { return .{ .len = 0, .bytes = null }; } }; pub const array_t = extern struct { num_entries: c_int, entries: ?*opaque {}, pub fn empty() array_t { return .{ .num_entries = 0, .entries = null }; } }; pub const table_t = extern struct { num_entries: c_int, entries: ?*opaque {}, pub fn empty() table_t { return .{ .num_entries = 0, .entries = null }; } }; pub const method_t = extern struct { id: method_number_t, decoded: ?*c_void, }; pub const DEFAULT_FRAME_SIZE: c_int = 131072; pub const DEFAULT_MAX_CHANNELS: c_int = 2047; // pub const DEFAULT_HEARTBEAT: c_int = 0; // pub const DEFAULT_VHOST = "/"; pub const version_number = amqp_version_number; pub const version = amqp_version; pub const ConnectionInfo = extern struct { user: [*:0]u8, password: [*:0]u8, host: [*:0]u8, vhost: [*:0]u8, port: c_int, ssl: boolean_t, }; pub fn parse_url(url: [*:0]u8) error{ BadUrl, Unexpected }!ConnectionInfo { var result: ConnectionInfo = undefined; return switch (amqp_parse_url(url, &result)) { .OK => result, .BAD_URL => error.BadUrl, else => |code| unexpected(code), }; } pub const Connection = struct { handle: *connection_state_t, pub fn new() error{OutOfMemory}!Connection { return Connection{ .handle = amqp_new_connection() orelse return error.OutOfMemory }; } pub fn close(self: Connection, code: ReplyCode) !void { return amqp_connection_close(self.handle, @enumToInt(code)).ok(); } pub fn destroy(self: *Connection) !void { const status = amqp_destroy_connection(self.handle); self.handle = undefined; return status.ok(); } pub fn maybe_release_buffers(self: Connection) void { amqp_maybe_release_buffers(self.handle); } /// Not every function updates this. See docs of `amqp_get_rpc_reply`. pub fn last_rpc_reply(self: Connection) RpcReply { return amqp_get_rpc_reply(self.handle); } pub fn login( self: Connection, vhost: [*:0]const u8, sasl_auth: SaslAuth, extra: struct { heartbeat: c_int, channel_max: c_int = DEFAULT_MAX_CHANNELS, frame_max: c_int = DEFAULT_FRAME_SIZE, }, ) !void { return switch (sasl_auth) { .plain => |plain| amqp_login(self.handle, vhost, extra.channel_max, extra.frame_max, extra.heartbeat, .PLAIN, plain.username, plain.password), .external => |external| amqp_login(self.handle, vhost, extra.channel_max, extra.frame_max, extra.heartbeat, .EXTERNAL, external.identity), }.ok(); } pub fn simple_wait_frame(self: Connection, timeout: ?*c.timeval) !Frame { var f: Frame = undefined; try amqp_simple_wait_frame_noblock(self.handle, &f, timeout).ok(); return f; } pub fn consume_message(self: Connection, timeout: ?*c.timeval, flags: c_int) !Envelope { var e: Envelope = undefined; try amqp_consume_message(self.handle, &e, timeout, flags).ok(); return e; } pub fn channel(self: Connection, number: channel_t) Channel { return .{ .connection = self, .number = number }; } pub const SaslAuth = union(enum) { plain: struct { username: [*:0]const u8, password: [*:0]const u8, }, external: struct { identity: [*:0]const u8, }, }; }; pub const Channel = struct { connection: Connection, number: channel_t, pub fn open(self: Channel) !*channel_open_ok_t { return amqp_channel_open(self.connection.handle, self.number) orelse self.connection.last_rpc_reply().err(); } pub fn close(self: Channel, code: ReplyCode) !void { return amqp_channel_close(self.connection.handle, self.number, @enumToInt(code)).ok(); } pub fn exchange_declare( self: Channel, exchange: bytes_t, type_: bytes_t, extra: struct { passive: bool = false, durable: bool = false, auto_delete: bool = false, internal: bool = false, arguments: table_t = table_t.empty(), }, ) !void { _ = amqp_exchange_declare( self.connection.handle, self.number, exchange, type_, @boolToInt(extra.passive), @boolToInt(extra.durable), @boolToInt(extra.auto_delete), @boolToInt(extra.internal), extra.arguments, ) orelse return self.connection.last_rpc_reply().err(); } pub fn queue_declare( self: Channel, queue: bytes_t, extra: struct { passive: bool = false, durable: bool = false, exclusive: bool = false, auto_delete: bool = false, arguments: table_t = table_t.empty(), }, ) !*queue_declare_ok_t { return amqp_queue_declare( self.connection.handle, self.number, queue, @boolToInt(extra.passive), @boolToInt(extra.durable), @boolToInt(extra.exclusive), @boolToInt(extra.auto_delete), extra.arguments, ) orelse self.connection.last_rpc_reply().err(); } pub fn queue_bind(self: Channel, queue: bytes_t, exchange: bytes_t, routing_key: bytes_t, arguments: table_t) !void { _ = amqp_queue_bind(self.connection.handle, self.number, queue, exchange, routing_key, arguments) orelse return self.connection.last_rpc_reply().err(); } pub fn basic_publish( self: Channel, exchange: bytes_t, routing_key: bytes_t, body: bytes_t, properties: BasicProperties, extra: struct { mandatory: bool = false, immediate: bool = false, }, ) !void { return amqp_basic_publish( self.connection.handle, self.number, exchange, routing_key, @boolToInt(extra.mandatory), @boolToInt(extra.immediate), &properties, body, ).ok(); } pub fn basic_consume( self: Channel, queue: bytes_t, extra: struct { consumer_tag: bytes_t = bytes_t.empty(), no_local: bool = false, no_ack: bool = false, exclusive: bool = false, arguments: table_t = table_t.empty(), }, ) !*basic_consume_ok_t { return amqp_basic_consume( self.connection.handle, self.number, queue, extra.consumer_tag, @boolToInt(extra.no_local), @boolToInt(extra.no_ack), @boolToInt(extra.exclusive), extra.arguments, ) orelse self.connection.last_rpc_reply().err(); } pub fn basic_ack(self: Channel, delivery_tag: u64, multiple: bool) !void { return amqp_basic_ack(self.connection.handle, self.number, delivery_tag, @boolToInt(multiple)).ok(); } pub fn basic_reject(self: Channel, delivery_tag: u64, requeue: bool) !void { return amqp_basic_reject(self.connection.handle, self.number, delivery_tag, @boolToInt(requeue)).ok(); } pub fn basic_qos(self: Channel, prefetch_size: u32, prefetch_count: u16, global: bool) !void { _ = amqp_basic_qos( self.connection.handle, self.number, prefetch_size, prefetch_count, @boolToInt(global), ) orelse return self.connection.last_rpc_reply().err(); } pub fn read_message(self: Channel, flags: c_int) !Message { var msg: Message = undefined; try amqp_read_message(self.connection.handle, self.number, &msg, flags).ok(); return msg; } pub fn maybe_release_buffers(self: Channel) void { amqp_maybe_release_buffers_on_channel(self.connection.handle, self.number); } }; pub const TcpSocket = struct { handle: *socket_t, pub fn new(connection: Connection) error{OutOfMemory}!TcpSocket { return TcpSocket{ .handle = amqp_tcp_socket_new(connection.handle) orelse return error.OutOfMemory }; } pub fn set_sockfd(self: TcpSocket, sockfd: c_int) void { amqp_tcp_socket_set_sockfd(self.handle, sockfd); } pub fn open(self: TcpSocket, host: [*:0]const u8, port: c_int, timeout: ?*c.timeval) !void { return amqp_socket_open_noblock(self.handle, host, port, timeout).ok(); } }; pub const SslSocket = struct { handle: *socket_t, pub fn new(connection: Connection) error{OutOfMemory}!SslSocket { return SslSocket{ .handle = amqp_ssl_socket_new(connection.handle) orelse return error.OutOfMemory }; } pub fn open(self: SslSocket, host: [*:0]const u8, port: c_int, timeout: ?*c.timeval) !void { return amqp_socket_open_noblock(self.handle, host, port, timeout).ok(); } pub fn set_cacert(self: SslSocket, cacert_path: [*:0]const u8) !void { return amqp_ssl_socket_set_cacert(self.handle, cacert_path).ok(); } pub fn set_key(self: SslSocket, cert_path: [*:0]const u8, key_path: [*:0]const u8) !void { return amqp_ssl_socket_set_key(self.handle, cert_path, key_path).ok(); } pub fn set_key_buffer(self: SslSocket, cert_path: [*:0]const u8, key: []const u8) !void { return amqp_ssl_socket_set_key_buffer(self.handle, cert_path, key.ptr, key.len).ok(); } pub fn set_verify_peer(self: SslSocket, verify: bool) void { amqp_ssl_socket_set_verify_peer(self.handle, @boolToInt(verify)); } pub fn set_verify_hostname(self: SslSocket, verify: bool) void { amqp_ssl_socket_set_verify_hostname(self.handle, @boolToInt(verify)); } pub fn set_ssl_versions(self: SslSocket, min: TlsVersion, max: TlsVersion) error{ Unsupported, InvalidParameter, Unexpected }!void { return switch (amqp_ssl_socket_set_ssl_versions(self.handle, min, max)) { .OK => {}, .UNSUPPORTED => error.Unsupported, .INVALID_PARAMETER => error.InvalidParameter, else => |code| unexpected(code), }; } const TlsVersion = extern enum(c_int) { v1 = 1, v1_1 = 2, v1_2 = 3, vLATEST = 65535, _, }; }; pub const RpcReply = extern struct { reply_type: response_type_t, reply: method_t, library_error: status_t, pub fn ok(self: RpcReply) Error!void { return switch (self.reply_type) { .NORMAL => {}, .NONE => error.SocketError, .LIBRARY_EXCEPTION => self.library_error.ok(), .SERVER_EXCEPTION => switch (self.reply.id) { .CONNECTION_CLOSE => error.ConnectionClosed, .CHANNEL_CLOSE => error.ChannelClosed, else => error.UnexpectedReply, }, _ => { log.crit("unexpected librabbitmq response type, value {}", .{self.reply_type}); return error.Unexpected; }, }; } pub fn err(self: RpcReply) Error { if (self.ok()) |_| { log.crit("expected librabbitmq error, got success instead", .{}); return error.Unexpected; } else |e| return e; } pub const response_type_t = extern enum(c_int) { NONE = 0, NORMAL = 1, LIBRARY_EXCEPTION = 2, SERVER_EXCEPTION = 3, _, }; }; /// Do not use fields directly to avoid bugs. pub const BasicProperties = extern struct { _flags: flags_t, _content_type: bytes_t, _content_encoding: bytes_t, _headers: table_t, _delivery_mode: u8, _priority: u8, _correlation_id: bytes_t, _reply_to: bytes_t, _expiration: bytes_t, _message_id: bytes_t, _timestamp: u64, _type_: bytes_t, _user_id: bytes_t, _app_id: bytes_t, _cluster_id: bytes_t, pub fn init(fields: anytype) BasicProperties { var props: BasicProperties = undefined; props._flags = 0; inline for (meta.fields(@TypeOf(fields))) |f| { @field(props, "_" ++ f.name) = @field(fields, f.name); props._flags |= @enumToInt(@field(Flag, f.name)); } return props; } pub fn get(self: BasicProperties, comptime flag: Flag) ?flag.Type() { if (self._flags & @enumToInt(flag) == 0) return null; return @field(self, "_" ++ @tagName(flag)); } pub fn set(self: *BasicProperties, comptime flag: Flag, value: ?flag.Type()) void { if (value) |val| { self._flags |= @enumToInt(flag); @field(self, "_" ++ @tagName(flag)) = val; } else { self._flags &= ~@enumToInt(flag); @field(self, "_" ++ @tagName(flag)) = undefined; } } pub const Flag = extern enum(flags_t) { content_type = 1 << 15, content_encoding = 1 << 14, headers = 1 << 13, delivery_mode = 1 << 12, priority = 1 << 11, correlation_id = 1 << 10, reply_to = 1 << 9, expiration = 1 << 8, message_id = 1 << 7, timestamp = 1 << 6, type_ = 1 << 5, user_id = 1 << 4, app_id = 1 << 3, cluster_id = 1 << 2, _, pub fn Type(flag: Flag) type { const needle = "_" ++ @tagName(flag); inline for (comptime meta.fields(BasicProperties)) |field| { if (comptime mem.eql(u8, field.name, needle)) return field.field_type; } unreachable; } }; }; pub const pool_blocklist_t = extern struct { num_blocks: c_int, blocklist: [*]?*c_void, }; pub const pool_t = extern struct { pagesize: usize, pages: pool_blocklist_t, large_blocks: pool_blocklist_t, next_page: c_int, alloc_block: [*]u8, alloc_used: usize, }; pub const Message = extern struct { properties: BasicProperties, body: bytes_t, pool: pool_t, pub fn destroy(self: *Message) void { amqp_destroy_message(self); } }; pub const Envelope = extern struct { channel: channel_t, consumer_tag: bytes_t, delivery_tag: u64, redelivered: boolean_t, exchange: bytes_t, routing_key: bytes_t, message: Message, pub fn destroy(self: *Envelope) void { amqp_destroy_envelope(self); } }; pub const Frame = extern struct { frame_type: Type, channel: channel_t, payload: extern union { /// frame_type == .METHOD method: method_t, /// frame_type == .HEADER properties: extern struct { class_id: u16, body_size: u64, decoded: ?*c_void, raw: bytes_t, }, /// frame_type == BODY body_fragment: bytes_t, /// used during initial handshake protocol_header: extern struct { transport_high: u8, transport_low: u8, protocol_version_major: u8, protocol_version_minor: u8, }, }, pub const Type = extern enum(u8) { METHOD = 1, HEADER = 2, BODY = 3, HEARTBEAT = 8, _, }; }; pub const Error = LibraryError || ServerError; pub const ServerError = error{ ConnectionClosed, ChannelClosed, UnexpectedReply, }; pub const LibraryError = error{ OutOfMemory, BadAmqpData, UnknownClass, UnknownMethod, HostnameResolutionFailed, IncompatibleAmqpVersion, ConnectionClosed, BadUrl, SocketError, InvalidParameter, TableTooBig, WrongMethod, Timeout, TimerFailure, HeartbeatTimeout, UnexpectedState, SocketClosed, SocketInUse, BrokerUnsupportedSaslMethod, Unsupported, TcpError, TcpSocketlibInitError, SslError, SslHostnameVerifyFailed, SslPeerVerifyFailed, SslConnectionFailed, Unexpected, }; fn unexpected(status: status_t) error{Unexpected} { log.crit("unexpected librabbitmq error, code {}, message {s}", .{ status, status.string() }); return error.Unexpected; } pub const status_t = extern enum(c_int) { OK = 0, NO_MEMORY = -1, BAD_AMQP_DATA = -2, UNKNOWN_CLASS = -3, UNKNOWN_METHOD = -4, HOSTNAME_RESOLUTION_FAILED = -5, INCOMPATIBLE_AMQP_VERSION = -6, CONNECTION_CLOSED = -7, BAD_URL = -8, SOCKET_ERROR = -9, INVALID_PARAMETER = -10, TABLE_TOO_BIG = -11, WRONG_METHOD = -12, TIMEOUT = -13, TIMER_FAILURE = -14, HEARTBEAT_TIMEOUT = -15, UNEXPECTED_STATE = -16, SOCKET_CLOSED = -17, SOCKET_INUSE = -18, BROKER_UNSUPPORTED_SASL_METHOD = -19, UNSUPPORTED = -20, TCP_ERROR = -256, TCP_SOCKETLIB_INIT_ERROR = -257, SSL_ERROR = -512, SSL_HOSTNAME_VERIFY_FAILED = -513, SSL_PEER_VERIFY_FAILED = -514, SSL_CONNECTION_FAILED = -515, _, pub fn ok(status: status_t) LibraryError!void { return switch (status) { .OK => {}, .NO_MEMORY => error.OutOfMemory, .BAD_AMQP_DATA => error.BadAmqpData, .UNKNOWN_CLASS => error.UnknownClass, .UNKNOWN_METHOD => error.UnknownMethod, .HOSTNAME_RESOLUTION_FAILED => error.HostnameResolutionFailed, .INCOMPATIBLE_AMQP_VERSION => error.IncompatibleAmqpVersion, .CONNECTION_CLOSED => error.ConnectionClosed, .BAD_URL => error.BadUrl, .SOCKET_ERROR => error.SocketError, .INVALID_PARAMETER => error.InvalidParameter, .TABLE_TOO_BIG => error.TableTooBig, .WRONG_METHOD => error.WrongMethod, .TIMEOUT => error.Timeout, .TIMER_FAILURE => error.TimerFailure, .HEARTBEAT_TIMEOUT => error.HeartbeatTimeout, .UNEXPECTED_STATE => error.UnexpectedState, .SOCKET_CLOSED => error.SocketClosed, .SOCKET_INUSE => error.SocketInUse, .BROKER_UNSUPPORTED_SASL_METHOD => error.BrokerUnsupportedSaslMethod, .UNSUPPORTED => error.Unsupported, .TCP_ERROR => error.TcpError, .TCP_SOCKETLIB_INIT_ERROR => error.TcpSocketlibInitError, .SSL_ERROR => error.SslError, .SSL_HOSTNAME_VERIFY_FAILED => error.SslHostnameVerifyFailed, .SSL_PEER_VERIFY_FAILED => error.SslPeerVerifyFailed, .SSL_CONNECTION_FAILED => error.SslConnectionFailed, _ => unexpected(status), }; } pub const string = amqp_error_string2; }; pub const ReplyCode = extern enum(u16) { REPLY_SUCCESS = 200, CONTENT_TOO_LARGE = 311, NO_ROUTE = 312, NO_CONSUMERS = 313, ACCESS_REFUSED = 403, NOT_FOUND = 404, RESOURCE_LOCKED = 405, PRECONDITION_FAILED = 406, CONNECTION_FORCED = 320, INVALID_PATH = 402, FRAME_ERROR = 501, SYNTAX_ERROR = 502, COMMAND_INVALID = 503, CHANNEL_ERROR = 504, UNEXPECTED_FRAME = 505, RESOURCE_ERROR = 506, NOT_ALLOWED = 530, NOT_IMPLEMENTED = 540, INTERNAL_ERROR = 541, }; pub const method_number_t = extern enum(u32) { CONNECTION_START = 0x000A000A, CONNECTION_START_OK = 0x000A000B, CONNECTION_SECURE = 0x000A0014, CONNECTION_SECURE_OK = 0x000A0015, CONNECTION_TUNE = 0x000A001E, CONNECTION_TUNE_OK = 0x000A001F, CONNECTION_OPEN = 0x000A0028, CONNECTION_OPEN_OK = 0x000A0029, CONNECTION_CLOSE = 0x000A0032, CONNECTION_CLOSE_OK = 0x000A0033, CONNECTION_BLOCKED = 0x000A003C, CONNECTION_UNBLOCKED = 0x000A003D, CHANNEL_OPEN = 0x0014000A, CHANNEL_OPEN_OK = 0x0014000B, CHANNEL_FLOW = 0x00140014, CHANNEL_FLOW_OK = 0x00140015, CHANNEL_CLOSE = 0x00140028, CHANNEL_CLOSE_OK = 0x00140029, ACCESS_REQUEST = 0x001E000A, ACCESS_REQUEST_OK = 0x001E000B, EXCHANGE_DECLARE = 0x0028000A, EXCHANGE_DECLARE_OK = 0x0028000B, EXCHANGE_DELETE = 0x00280014, EXCHANGE_DELETE_OK = 0x00280015, EXCHANGE_BIND = 0x0028001E, EXCHANGE_BIND_OK = 0x0028001F, EXCHANGE_UNBIND = 0x00280028, EXCHANGE_UNBIND_OK = 0x00280033, QUEUE_DECLARE = 0x0032000A, QUEUE_DECLARE_OK = 0x0032000B, QUEUE_BIND = 0x00320014, QUEUE_BIND_OK = 0x00320015, QUEUE_PURGE = 0x0032001E, QUEUE_PURGE_OK = 0x0032001F, QUEUE_DELETE = 0x00320028, QUEUE_DELETE_OK = 0x00320029, QUEUE_UNBIND = 0x00320032, QUEUE_UNBIND_OK = 0x00320033, BASIC_QOS = 0x003C000A, BASIC_QOS_OK = 0x003C000B, BASIC_CONSUME = 0x003C0014, BASIC_CONSUME_OK = 0x003C0015, BASIC_CANCEL = 0x003C001E, BASIC_CANCEL_OK = 0x003C001F, BASIC_PUBLISH = 0x003C0028, BASIC_RETURN = 0x003C0032, BASIC_DELIVER = 0x003C003C, BASIC_GET = 0x003C0046, BASIC_GET_OK = 0x003C0047, BASIC_GET_EMPTY = 0x003C0048, BASIC_ACK = 0x003C0050, BASIC_REJECT = 0x003C005A, BASIC_RECOVER_ASYNC = 0x003C0064, BASIC_RECOVER = 0x003C006E, BASIC_RECOVER_OK = 0x003C006F, BASIC_NACK = 0x003C0078, TX_SELECT = 0x005A000A, TX_SELECT_OK = 0x005A000B, TX_COMMIT = 0x005A0014, TX_COMMIT_OK = 0x005A0015, TX_ROLLBACK = 0x005A001E, TX_ROLLBACK_OK = 0x005A001F, CONFIRM_SELECT = 0x0055000A, CONFIRM_SELECT_OK = 0x0055000B, _, }; // Messages pub const channel_open_ok_t = extern struct { channel_id: bytes_t, }; pub const queue_declare_ok_t = extern struct { queue: bytes_t, message_count: u32, consumer_count: u32, }; pub const basic_consume_ok_t = extern struct { consumer_tag: bytes_t, }; pub const connection_close_t = extern struct { reply_code: ReplyCode, reply_text: bytes_t, class_id: u16, method_id: u16, }; pub const channel_close_t = extern struct { reply_code: ReplyCode, reply_text: bytes_t, class_id: u16, method_id: u16, };
src/zamqp.zig
const std = @import("std"); const elf = std.elf; pub const ds = @import("./ds.zig"); pub const funcs = @import("./funcs.zig"); const elfErrors = error{ CannotTellIfBinaryIs32or64bit, }; pub const ELF = struct { file: std.fs.File = undefined, is32: bool = undefined, address: usize = 0x400000, ehdr: ds.Ehdr = undefined, shdrs: std.ArrayList(ds.Shdr) = undefined, phdrs: std.ArrayList(ds.Phdr) = undefined, data: []u8, symbols: std.ArrayList(ds.Syms) = undefined, relas: std.ArrayList(ds.Rela) = undefined, const Self = @This(); pub fn init() !ELF { return ELF{}; } pub fn readElf(file: std.fs.File, alloc: std.mem.Allocator) !ELF { var e: ELF = undefined; e.file = file; e.ehdr = try funcs.ehdrParse(e); e.is32 = try is32(e); e.data = try e.file.reader().readAllAlloc(alloc, std.math.maxInt(u64)); e.phdrs = try funcs.phdrParse(e, alloc); e.shdrs = try funcs.shdrParse(e, alloc); e.symbols = try funcs.getSyms(e, alloc); return e; } fn is32(parse_source: ELF) !bool { var ident: [std.elf.EI_NIDENT]u8 = undefined; try parse_source.file.seekableStream().seekTo(0); _ = try parse_source.file.read(ident[0..]); if (ident[0x04] == 1) { return true; } else if (ident[0x04] == 2) { return false; } else { return elfErrors.CannotTellIfBinaryIs32or64bit; } } // have a deinit and update function pub fn deinit(self: Self) void { self.file.close(); self.relas.deinit(); self.shdrs.deinit(); self.phdrs.deinit(); } pub fn writeElf(self: Self, alloc: std.mem.Allocator) !void { try funcs.writeEhdr(self); try funcs.writePhdrList(self, alloc); { try self.file.seekTo((self.ehdr.phnum * self.ehdr.phentsize) + self.ehdr.phoff); //try self.file.writeAll(self.data); if ((self.ehdr.phnum * self.ehdr.phentsize) + self.ehdr.phoff > self.ehdr.shoff - 1) { @panic("the offset of the end of phdrs should be smaller than the offset of the start of shdrs, but that is not the case, idk whats up"); } else { //try self.file.writer().writeAll(self.data[((self.ehdr.phnum * self.ehdr.phentsize) + self.ehdr.phoff) .. self.ehdr.shoff - 1]); try self.file.writer().writeAll(self.data[((self.ehdr.phnum * self.ehdr.phentsize) + self.ehdr.phoff)..]); } } try funcs.writeShdrList(self, alloc); } };
src/elf.zig
pub const GUID_DEVINTERFACE_DISPLAY_ADAPTER = Guid.initString("5b45201d-f2f2-4f3b-85bb-30ff1f953599"); pub const GUID_DEVINTERFACE_MONITOR = Guid.initString("e6f07b5f-ee97-4a90-b076-33f57bf4eaa7"); pub const GUID_DISPLAY_DEVICE_ARRIVAL = Guid.initString("1ca05180-a699-450a-9a0c-de4fbe3ddd89"); pub const GUID_DEVINTERFACE_VIDEO_OUTPUT_ARRIVAL = Guid.initString("1ad9e4f0-f88d-4360-bab9-4c2d55e564cd"); pub const DEVPKEY_IndirectDisplay = PROPERTYKEY { .fmtid = Guid.initString("c50a3f10-aa5c-4247-b830-d6a6f8eaa310"), .pid = 1 }; pub const DEVPKEY_Device_TerminalLuid = PROPERTYKEY { .fmtid = Guid.initString("c50a3f10-aa5c-4247-b830-d6a6f8eaa310"), .pid = 2 }; pub const DEVPKEY_Device_AdapterLuid = PROPERTYKEY { .fmtid = Guid.initString("c50a3f10-aa5c-4247-b830-d6a6f8eaa310"), .pid = 3 }; pub const DEVPKEY_Device_ActivityId = PROPERTYKEY { .fmtid = Guid.initString("c50a3f10-aa5c-4247-b830-d6a6f8eaa310"), .pid = 4 }; pub const INDIRECT_DISPLAY_INFO_FLAGS_CREATED_IDDCX_ADAPTER = @as(u32, 1); pub const IOCTL_VIDEO_DISABLE_VDM = @as(u32, 2293764); pub const IOCTL_VIDEO_REGISTER_VDM = @as(u32, 2293768); pub const IOCTL_VIDEO_SET_OUTPUT_DEVICE_POWER_STATE = @as(u32, 2293772); pub const IOCTL_VIDEO_GET_OUTPUT_DEVICE_POWER_STATE = @as(u32, 2293776); pub const IOCTL_VIDEO_MONITOR_DEVICE = @as(u32, 2293780); pub const IOCTL_VIDEO_ENUM_MONITOR_PDO = @as(u32, 2293784); pub const IOCTL_VIDEO_INIT_WIN32K_CALLBACKS = @as(u32, 2293788); pub const IOCTL_VIDEO_IS_VGA_DEVICE = @as(u32, 2293796); pub const IOCTL_VIDEO_USE_DEVICE_IN_SESSION = @as(u32, 2293800); pub const IOCTL_VIDEO_PREPARE_FOR_EARECOVERY = @as(u32, 2293804); pub const IOCTL_VIDEO_ENABLE_VDM = @as(u32, 2293760); pub const IOCTL_VIDEO_SAVE_HARDWARE_STATE = @as(u32, 2294272); pub const IOCTL_VIDEO_RESTORE_HARDWARE_STATE = @as(u32, 2294276); pub const IOCTL_VIDEO_HANDLE_VIDEOPARAMETERS = @as(u32, 2293792); pub const IOCTL_VIDEO_QUERY_AVAIL_MODES = @as(u32, 2294784); pub const IOCTL_VIDEO_QUERY_NUM_AVAIL_MODES = @as(u32, 2294788); pub const IOCTL_VIDEO_QUERY_CURRENT_MODE = @as(u32, 2294792); pub const IOCTL_VIDEO_SET_CURRENT_MODE = @as(u32, 2294796); pub const IOCTL_VIDEO_RESET_DEVICE = @as(u32, 2294800); pub const IOCTL_VIDEO_LOAD_AND_SET_FONT = @as(u32, 2294804); pub const IOCTL_VIDEO_SET_PALETTE_REGISTERS = @as(u32, 2294808); pub const IOCTL_VIDEO_SET_COLOR_REGISTERS = @as(u32, 2294812); pub const IOCTL_VIDEO_ENABLE_CURSOR = @as(u32, 2294816); pub const IOCTL_VIDEO_DISABLE_CURSOR = @as(u32, 2294820); pub const IOCTL_VIDEO_SET_CURSOR_ATTR = @as(u32, 2294824); pub const IOCTL_VIDEO_QUERY_CURSOR_ATTR = @as(u32, 2294828); pub const IOCTL_VIDEO_SET_CURSOR_POSITION = @as(u32, 2294832); pub const IOCTL_VIDEO_QUERY_CURSOR_POSITION = @as(u32, 2294836); pub const IOCTL_VIDEO_ENABLE_POINTER = @as(u32, 2294840); pub const IOCTL_VIDEO_DISABLE_POINTER = @as(u32, 2294844); pub const IOCTL_VIDEO_SET_POINTER_ATTR = @as(u32, 2294848); pub const IOCTL_VIDEO_QUERY_POINTER_ATTR = @as(u32, 2294852); pub const IOCTL_VIDEO_SET_POINTER_POSITION = @as(u32, 2294856); pub const IOCTL_VIDEO_QUERY_POINTER_POSITION = @as(u32, 2294860); pub const IOCTL_VIDEO_QUERY_POINTER_CAPABILITIES = @as(u32, 2294864); pub const IOCTL_VIDEO_GET_BANK_SELECT_CODE = @as(u32, 2294868); pub const IOCTL_VIDEO_MAP_VIDEO_MEMORY = @as(u32, 2294872); pub const IOCTL_VIDEO_UNMAP_VIDEO_MEMORY = @as(u32, 2294876); pub const IOCTL_VIDEO_QUERY_PUBLIC_ACCESS_RANGES = @as(u32, 2294880); pub const IOCTL_VIDEO_FREE_PUBLIC_ACCESS_RANGES = @as(u32, 2294884); pub const IOCTL_VIDEO_QUERY_COLOR_CAPABILITIES = @as(u32, 2294888); pub const IOCTL_VIDEO_SET_POWER_MANAGEMENT = @as(u32, 2294892); pub const IOCTL_VIDEO_GET_POWER_MANAGEMENT = @as(u32, 2294896); pub const IOCTL_VIDEO_SHARE_VIDEO_MEMORY = @as(u32, 2294900); pub const IOCTL_VIDEO_UNSHARE_VIDEO_MEMORY = @as(u32, 2294904); pub const IOCTL_VIDEO_SET_COLOR_LUT_DATA = @as(u32, 2294908); pub const IOCTL_VIDEO_GET_CHILD_STATE = @as(u32, 2294912); pub const IOCTL_VIDEO_VALIDATE_CHILD_STATE_CONFIGURATION = @as(u32, 2294916); pub const IOCTL_VIDEO_SET_CHILD_STATE_CONFIGURATION = @as(u32, 2294920); pub const IOCTL_VIDEO_SWITCH_DUALVIEW = @as(u32, 2294924); pub const IOCTL_VIDEO_SET_BANK_POSITION = @as(u32, 2294928); pub const IOCTL_VIDEO_QUERY_SUPPORTED_BRIGHTNESS = @as(u32, 2294932); pub const IOCTL_VIDEO_QUERY_DISPLAY_BRIGHTNESS = @as(u32, 2294936); pub const IOCTL_VIDEO_SET_DISPLAY_BRIGHTNESS = @as(u32, 2294940); pub const IOCTL_FSVIDEO_COPY_FRAME_BUFFER = @as(u32, 3409920); pub const IOCTL_FSVIDEO_WRITE_TO_FRAME_BUFFER = @as(u32, 3409924); pub const IOCTL_FSVIDEO_REVERSE_MOUSE_POINTER = @as(u32, 3409928); pub const IOCTL_FSVIDEO_SET_CURRENT_MODE = @as(u32, 3409932); pub const IOCTL_FSVIDEO_SET_SCREEN_INFORMATION = @as(u32, 3409936); pub const IOCTL_FSVIDEO_SET_CURSOR_POSITION = @as(u32, 3409940); pub const IOCTL_PANEL_QUERY_BRIGHTNESS_CAPS = @as(u32, 2296832); pub const IOCTL_PANEL_QUERY_BRIGHTNESS_RANGES = @as(u32, 2296836); pub const IOCTL_PANEL_GET_BRIGHTNESS = @as(u32, 2296840); pub const IOCTL_PANEL_SET_BRIGHTNESS = @as(u32, 2296844); pub const IOCTL_PANEL_SET_BRIGHTNESS_STATE = @as(u32, 2296848); pub const IOCTL_PANEL_SET_BACKLIGHT_OPTIMIZATION = @as(u32, 2296852); pub const IOCTL_PANEL_GET_BACKLIGHT_REDUCTION = @as(u32, 2296856); pub const IOCTL_COLORSPACE_TRANSFORM_QUERY_TARGET_CAPS = @as(u32, 2297856); pub const IOCTL_COLORSPACE_TRANSFORM_SET = @as(u32, 2297860); pub const IOCTL_SET_ACTIVE_COLOR_PROFILE_NAME = @as(u32, 2297864); pub const IOCTL_MIPI_DSI_QUERY_CAPS = @as(u32, 2298880); pub const IOCTL_MIPI_DSI_TRANSMISSION = @as(u32, 2298884); pub const IOCTL_MIPI_DSI_RESET = @as(u32, 2298888); pub const DXGK_WIN32K_PARAM_FLAG_UPDATEREGISTRY = @as(u32, 1); pub const DXGK_WIN32K_PARAM_FLAG_MODESWITCH = @as(u32, 2); pub const DXGK_WIN32K_PARAM_FLAG_DISABLEVIEW = @as(u32, 4); pub const VIDEO_DUALVIEW_REMOVABLE = @as(u32, 1); pub const VIDEO_DUALVIEW_PRIMARY = @as(u32, 2147483648); pub const VIDEO_DUALVIEW_SECONDARY = @as(u32, 1073741824); pub const VIDEO_DUALVIEW_WDDM_VGA = @as(u32, 536870912); pub const VIDEO_STATE_NON_STANDARD_VGA = @as(u32, 1); pub const VIDEO_STATE_UNEMULATED_VGA_STATE = @as(u32, 2); pub const VIDEO_STATE_PACKED_CHAIN4_MODE = @as(u32, 4); pub const VIDEO_MODE_NO_ZERO_MEMORY = @as(u32, 2147483648); pub const VIDEO_MODE_MAP_MEM_LINEAR = @as(u32, 1073741824); pub const VIDEO_MODE_COLOR = @as(u32, 1); pub const VIDEO_MODE_GRAPHICS = @as(u32, 2); pub const VIDEO_MODE_PALETTE_DRIVEN = @as(u32, 4); pub const VIDEO_MODE_MANAGED_PALETTE = @as(u32, 8); pub const VIDEO_MODE_INTERLACED = @as(u32, 16); pub const VIDEO_MODE_NO_OFF_SCREEN = @as(u32, 32); pub const VIDEO_MODE_NO_64_BIT_ACCESS = @as(u32, 64); pub const VIDEO_MODE_BANKED = @as(u32, 128); pub const VIDEO_MODE_LINEAR = @as(u32, 256); pub const VIDEO_MODE_ASYNC_POINTER = @as(u32, 1); pub const VIDEO_MODE_MONO_POINTER = @as(u32, 2); pub const VIDEO_MODE_COLOR_POINTER = @as(u32, 4); pub const VIDEO_MODE_ANIMATE_START = @as(u32, 8); pub const VIDEO_MODE_ANIMATE_UPDATE = @as(u32, 16); pub const PLANAR_HC = @as(u32, 1); pub const VIDEO_DEVICE_COLOR = @as(u32, 1); pub const VIDEO_OPTIONAL_GAMMET_TABLE = @as(u32, 2); pub const VIDEO_COLOR_LUT_DATA_FORMAT_RGB256WORDS = @as(u32, 1); pub const VIDEO_COLOR_LUT_DATA_FORMAT_PRIVATEFORMAT = @as(u32, 2147483648); pub const DISPLAYPOLICY_AC = @as(u32, 1); pub const DISPLAYPOLICY_DC = @as(u32, 2); pub const CHAR_TYPE_SBCS = @as(u32, 0); pub const CHAR_TYPE_LEADING = @as(u32, 2); pub const CHAR_TYPE_TRAILING = @as(u32, 3); pub const BITMAP_BITS_BYTE_ALIGN = @as(u32, 8); pub const BITMAP_BITS_WORD_ALIGN = @as(u32, 16); pub const BITMAP_ARRAY_BYTE = @as(u32, 3); pub const BITMAP_PLANES = @as(u32, 1); pub const BITMAP_BITS_PIXEL = @as(u32, 1); pub const VIDEO_REASON_NONE = @as(u32, 0); pub const VIDEO_REASON_POLICY1 = @as(u32, 1); pub const VIDEO_REASON_POLICY2 = @as(u32, 2); pub const VIDEO_REASON_POLICY3 = @as(u32, 3); pub const VIDEO_REASON_POLICY4 = @as(u32, 4); pub const VIDEO_REASON_LOCK = @as(u32, 5); pub const VIDEO_REASON_FAILED_ROTATION = @as(u32, 5); pub const VIDEO_REASON_ALLOCATION = @as(u32, 6); pub const VIDEO_REASON_SCRATCH = @as(u32, 8); pub const VIDEO_REASON_CONFIGURATION = @as(u32, 9); pub const VIDEO_MAX_REASON = @as(u32, 9); pub const BRIGHTNESS_MAX_LEVEL_COUNT = @as(u32, 103); pub const BRIGHTNESS_MAX_NIT_RANGE_COUNT = @as(u32, 16); pub const DSI_PACKET_EMBEDDED_PAYLOAD_SIZE = @as(u32, 8); pub const MAX_PACKET_COUNT = @as(u32, 128); pub const DSI_INVALID_PACKET_INDEX = @as(u32, 255); pub const DSI_SOT_ERROR = @as(u32, 1); pub const DSI_SOT_SYNC_ERROR = @as(u32, 2); pub const DSI_EOT_SYNC_ERROR = @as(u32, 4); pub const DSI_ESCAPE_MODE_ENTRY_COMMAND_ERROR = @as(u32, 8); pub const DSI_LOW_POWER_TRANSMIT_SYNC_ERROR = @as(u32, 16); pub const DSI_PERIPHERAL_TIMEOUT_ERROR = @as(u32, 32); pub const DSI_FALSE_CONTROL_ERROR = @as(u32, 64); pub const DSI_CONTENTION_DETECTED = @as(u32, 128); pub const DSI_CHECKSUM_ERROR_CORRECTED = @as(u32, 256); pub const DSI_CHECKSUM_ERROR_NOT_CORRECTED = @as(u32, 512); pub const DSI_LONG_PACKET_PAYLOAD_CHECKSUM_ERROR = @as(u32, 1024); pub const DSI_DSI_DATA_TYPE_NOT_RECOGNIZED = @as(u32, 2048); pub const DSI_DSI_VC_ID_INVALID = @as(u32, 4096); pub const DSI_INVALID_TRANSMISSION_LENGTH = @as(u32, 8192); pub const DSI_DSI_PROTOCOL_VIOLATION = @as(u32, 32768); pub const HOST_DSI_DEVICE_NOT_READY = @as(u32, 1); pub const HOST_DSI_INTERFACE_RESET = @as(u32, 2); pub const HOST_DSI_DEVICE_RESET = @as(u32, 4); pub const HOST_DSI_TRANSMISSION_CANCELLED = @as(u32, 16); pub const HOST_DSI_TRANSMISSION_DROPPED = @as(u32, 32); pub const HOST_DSI_TRANSMISSION_TIMEOUT = @as(u32, 64); pub const HOST_DSI_INVALID_TRANSMISSION = @as(u32, 256); pub const HOST_DSI_OS_REJECTED_PACKET = @as(u32, 512); pub const HOST_DSI_DRIVER_REJECTED_PACKET = @as(u32, 1024); pub const HOST_DSI_BAD_TRANSMISSION_MODE = @as(u32, 4096); pub const GUID_MONITOR_OVERRIDE_PSEUDO_SPECIALIZED = Guid.initString("f196c02f-f86f-4f9a-aa15-e9cebdfe3b96"); pub const FD_ERROR = @as(u32, 4294967295); pub const DDI_ERROR = @as(u32, 4294967295); pub const FDM_TYPE_BM_SIDE_CONST = @as(u32, 1); pub const FDM_TYPE_MAXEXT_EQUAL_BM_SIDE = @as(u32, 2); pub const FDM_TYPE_CHAR_INC_EQUAL_BM_BASE = @as(u32, 4); pub const FDM_TYPE_ZERO_BEARINGS = @as(u32, 8); pub const FDM_TYPE_CONST_BEARINGS = @as(u32, 16); pub const GS_UNICODE_HANDLES = @as(u32, 1); pub const GS_8BIT_HANDLES = @as(u32, 2); pub const GS_16BIT_HANDLES = @as(u32, 4); pub const FM_VERSION_NUMBER = @as(u32, 0); pub const FM_TYPE_LICENSED = @as(u32, 2); pub const FM_READONLY_EMBED = @as(u32, 4); pub const FM_EDITABLE_EMBED = @as(u32, 8); pub const FM_NO_EMBEDDING = @as(u32, 2); pub const FM_INFO_TECH_TRUETYPE = @as(u32, 1); pub const FM_INFO_TECH_BITMAP = @as(u32, 2); pub const FM_INFO_TECH_STROKE = @as(u32, 4); pub const FM_INFO_TECH_OUTLINE_NOT_TRUETYPE = @as(u32, 8); pub const FM_INFO_ARB_XFORMS = @as(u32, 16); pub const FM_INFO_1BPP = @as(u32, 32); pub const FM_INFO_4BPP = @as(u32, 64); pub const FM_INFO_8BPP = @as(u32, 128); pub const FM_INFO_16BPP = @as(u32, 256); pub const FM_INFO_24BPP = @as(u32, 512); pub const FM_INFO_32BPP = @as(u32, 1024); pub const FM_INFO_INTEGER_WIDTH = @as(u32, 2048); pub const FM_INFO_CONSTANT_WIDTH = @as(u32, 4096); pub const FM_INFO_NOT_CONTIGUOUS = @as(u32, 8192); pub const FM_INFO_TECH_MM = @as(u32, 16384); pub const FM_INFO_RETURNS_OUTLINES = @as(u32, 32768); pub const FM_INFO_RETURNS_STROKES = @as(u32, 65536); pub const FM_INFO_RETURNS_BITMAPS = @as(u32, 131072); pub const FM_INFO_DSIG = @as(u32, 262144); pub const FM_INFO_RIGHT_HANDED = @as(u32, 524288); pub const FM_INFO_INTEGRAL_SCALING = @as(u32, 1048576); pub const FM_INFO_90DEGREE_ROTATIONS = @as(u32, 2097152); pub const FM_INFO_OPTICALLY_FIXED_PITCH = @as(u32, 4194304); pub const FM_INFO_DO_NOT_ENUMERATE = @as(u32, 8388608); pub const FM_INFO_ISOTROPIC_SCALING_ONLY = @as(u32, 16777216); pub const FM_INFO_ANISOTROPIC_SCALING_ONLY = @as(u32, 33554432); pub const FM_INFO_TECH_CFF = @as(u32, 67108864); pub const FM_INFO_FAMILY_EQUIV = @as(u32, 134217728); pub const FM_INFO_DBCS_FIXED_PITCH = @as(u32, 268435456); pub const FM_INFO_NONNEGATIVE_AC = @as(u32, 536870912); pub const FM_INFO_IGNORE_TC_RA_ABLE = @as(u32, 1073741824); pub const FM_INFO_TECH_TYPE1 = @as(u32, 2147483648); pub const MAXCHARSETS = @as(u32, 16); pub const FM_PANOSE_CULTURE_LATIN = @as(u32, 0); pub const FM_SEL_ITALIC = @as(u32, 1); pub const FM_SEL_UNDERSCORE = @as(u32, 2); pub const FM_SEL_NEGATIVE = @as(u32, 4); pub const FM_SEL_OUTLINED = @as(u32, 8); pub const FM_SEL_STRIKEOUT = @as(u32, 16); pub const FM_SEL_BOLD = @as(u32, 32); pub const FM_SEL_REGULAR = @as(u32, 64); pub const OPENGL_CMD = @as(u32, 4352); pub const OPENGL_GETINFO = @as(u32, 4353); pub const WNDOBJ_SETUP = @as(u32, 4354); pub const DDI_DRIVER_VERSION_NT4 = @as(u32, 131072); pub const DDI_DRIVER_VERSION_SP3 = @as(u32, 131075); pub const DDI_DRIVER_VERSION_NT5 = @as(u32, 196608); pub const DDI_DRIVER_VERSION_NT5_01 = @as(u32, 196864); pub const DDI_DRIVER_VERSION_NT5_01_SP1 = @as(u32, 196865); pub const GDI_DRIVER_VERSION = @as(u32, 16384); pub const INDEX_DrvEnablePDEV = @as(i32, 0); pub const INDEX_DrvCompletePDEV = @as(i32, 1); pub const INDEX_DrvDisablePDEV = @as(i32, 2); pub const INDEX_DrvEnableSurface = @as(i32, 3); pub const INDEX_DrvDisableSurface = @as(i32, 4); pub const INDEX_DrvAssertMode = @as(i32, 5); pub const INDEX_DrvOffset = @as(i32, 6); pub const INDEX_DrvResetPDEV = @as(i32, 7); pub const INDEX_DrvDisableDriver = @as(i32, 8); pub const INDEX_DrvCreateDeviceBitmap = @as(i32, 10); pub const INDEX_DrvDeleteDeviceBitmap = @as(i32, 11); pub const INDEX_DrvRealizeBrush = @as(i32, 12); pub const INDEX_DrvDitherColor = @as(i32, 13); pub const INDEX_DrvStrokePath = @as(i32, 14); pub const INDEX_DrvFillPath = @as(i32, 15); pub const INDEX_DrvStrokeAndFillPath = @as(i32, 16); pub const INDEX_DrvPaint = @as(i32, 17); pub const INDEX_DrvBitBlt = @as(i32, 18); pub const INDEX_DrvCopyBits = @as(i32, 19); pub const INDEX_DrvStretchBlt = @as(i32, 20); pub const INDEX_DrvSetPalette = @as(i32, 22); pub const INDEX_DrvTextOut = @as(i32, 23); pub const INDEX_DrvEscape = @as(i32, 24); pub const INDEX_DrvDrawEscape = @as(i32, 25); pub const INDEX_DrvQueryFont = @as(i32, 26); pub const INDEX_DrvQueryFontTree = @as(i32, 27); pub const INDEX_DrvQueryFontData = @as(i32, 28); pub const INDEX_DrvSetPointerShape = @as(i32, 29); pub const INDEX_DrvMovePointer = @as(i32, 30); pub const INDEX_DrvLineTo = @as(i32, 31); pub const INDEX_DrvSendPage = @as(i32, 32); pub const INDEX_DrvStartPage = @as(i32, 33); pub const INDEX_DrvEndDoc = @as(i32, 34); pub const INDEX_DrvStartDoc = @as(i32, 35); pub const INDEX_DrvGetGlyphMode = @as(i32, 37); pub const INDEX_DrvSynchronize = @as(i32, 38); pub const INDEX_DrvSaveScreenBits = @as(i32, 40); pub const INDEX_DrvGetModes = @as(i32, 41); pub const INDEX_DrvFree = @as(i32, 42); pub const INDEX_DrvDestroyFont = @as(i32, 43); pub const INDEX_DrvQueryFontCaps = @as(i32, 44); pub const INDEX_DrvLoadFontFile = @as(i32, 45); pub const INDEX_DrvUnloadFontFile = @as(i32, 46); pub const INDEX_DrvFontManagement = @as(i32, 47); pub const INDEX_DrvQueryTrueTypeTable = @as(i32, 48); pub const INDEX_DrvQueryTrueTypeOutline = @as(i32, 49); pub const INDEX_DrvGetTrueTypeFile = @as(i32, 50); pub const INDEX_DrvQueryFontFile = @as(i32, 51); pub const INDEX_DrvMovePanning = @as(i32, 52); pub const INDEX_DrvQueryAdvanceWidths = @as(i32, 53); pub const INDEX_DrvSetPixelFormat = @as(i32, 54); pub const INDEX_DrvDescribePixelFormat = @as(i32, 55); pub const INDEX_DrvSwapBuffers = @as(i32, 56); pub const INDEX_DrvStartBanding = @as(i32, 57); pub const INDEX_DrvNextBand = @as(i32, 58); pub const INDEX_DrvGetDirectDrawInfo = @as(i32, 59); pub const INDEX_DrvEnableDirectDraw = @as(i32, 60); pub const INDEX_DrvDisableDirectDraw = @as(i32, 61); pub const INDEX_DrvQuerySpoolType = @as(i32, 62); pub const INDEX_DrvIcmCreateColorTransform = @as(i32, 64); pub const INDEX_DrvIcmDeleteColorTransform = @as(i32, 65); pub const INDEX_DrvIcmCheckBitmapBits = @as(i32, 66); pub const INDEX_DrvIcmSetDeviceGammaRamp = @as(i32, 67); pub const INDEX_DrvGradientFill = @as(i32, 68); pub const INDEX_DrvStretchBltROP = @as(i32, 69); pub const INDEX_DrvPlgBlt = @as(i32, 70); pub const INDEX_DrvAlphaBlend = @as(i32, 71); pub const INDEX_DrvSynthesizeFont = @as(i32, 72); pub const INDEX_DrvGetSynthesizedFontFiles = @as(i32, 73); pub const INDEX_DrvTransparentBlt = @as(i32, 74); pub const INDEX_DrvQueryPerBandInfo = @as(i32, 75); pub const INDEX_DrvQueryDeviceSupport = @as(i32, 76); pub const INDEX_DrvReserved1 = @as(i32, 77); pub const INDEX_DrvReserved2 = @as(i32, 78); pub const INDEX_DrvReserved3 = @as(i32, 79); pub const INDEX_DrvReserved4 = @as(i32, 80); pub const INDEX_DrvReserved5 = @as(i32, 81); pub const INDEX_DrvReserved6 = @as(i32, 82); pub const INDEX_DrvReserved7 = @as(i32, 83); pub const INDEX_DrvReserved8 = @as(i32, 84); pub const INDEX_DrvDeriveSurface = @as(i32, 85); pub const INDEX_DrvQueryGlyphAttrs = @as(i32, 86); pub const INDEX_DrvNotify = @as(i32, 87); pub const INDEX_DrvSynchronizeSurface = @as(i32, 88); pub const INDEX_DrvResetDevice = @as(i32, 89); pub const INDEX_DrvReserved9 = @as(i32, 90); pub const INDEX_DrvReserved10 = @as(i32, 91); pub const INDEX_DrvReserved11 = @as(i32, 92); pub const INDEX_DrvRenderHint = @as(i32, 93); pub const INDEX_DrvCreateDeviceBitmapEx = @as(i32, 94); pub const INDEX_DrvDeleteDeviceBitmapEx = @as(i32, 95); pub const INDEX_DrvAssociateSharedSurface = @as(i32, 96); pub const INDEX_DrvSynchronizeRedirectionBitmaps = @as(i32, 97); pub const INDEX_DrvAccumulateD3DDirtyRect = @as(i32, 98); pub const INDEX_DrvStartDxInterop = @as(i32, 99); pub const INDEX_DrvEndDxInterop = @as(i32, 100); pub const INDEX_DrvLockDisplayArea = @as(i32, 101); pub const INDEX_DrvUnlockDisplayArea = @as(i32, 102); pub const INDEX_DrvSurfaceComplete = @as(i32, 103); pub const INDEX_LAST = @as(i32, 89); pub const GCAPS_BEZIERS = @as(u32, 1); pub const GCAPS_GEOMETRICWIDE = @as(u32, 2); pub const GCAPS_ALTERNATEFILL = @as(u32, 4); pub const GCAPS_WINDINGFILL = @as(u32, 8); pub const GCAPS_HALFTONE = @as(u32, 16); pub const GCAPS_COLOR_DITHER = @as(u32, 32); pub const GCAPS_HORIZSTRIKE = @as(u32, 64); pub const GCAPS_VERTSTRIKE = @as(u32, 128); pub const GCAPS_OPAQUERECT = @as(u32, 256); pub const GCAPS_VECTORFONT = @as(u32, 512); pub const GCAPS_MONO_DITHER = @as(u32, 1024); pub const GCAPS_ASYNCCHANGE = @as(u32, 2048); pub const GCAPS_ASYNCMOVE = @as(u32, 4096); pub const GCAPS_DONTJOURNAL = @as(u32, 8192); pub const GCAPS_DIRECTDRAW = @as(u32, 16384); pub const GCAPS_ARBRUSHOPAQUE = @as(u32, 32768); pub const GCAPS_PANNING = @as(u32, 65536); pub const GCAPS_HIGHRESTEXT = @as(u32, 262144); pub const GCAPS_PALMANAGED = @as(u32, 524288); pub const GCAPS_DITHERONREALIZE = @as(u32, 2097152); pub const GCAPS_NO64BITMEMACCESS = @as(u32, 4194304); pub const GCAPS_FORCEDITHER = @as(u32, 8388608); pub const GCAPS_GRAY16 = @as(u32, 16777216); pub const GCAPS_ICM = @as(u32, 33554432); pub const GCAPS_CMYKCOLOR = @as(u32, 67108864); pub const GCAPS_LAYERED = @as(u32, 134217728); pub const GCAPS_ARBRUSHTEXT = @as(u32, 268435456); pub const GCAPS_SCREENPRECISION = @as(u32, 536870912); pub const GCAPS_FONT_RASTERIZER = @as(u32, 1073741824); pub const GCAPS_NUP = @as(u32, 2147483648); pub const GCAPS2_JPEGSRC = @as(u32, 1); pub const GCAPS2_xxxx = @as(u32, 2); pub const GCAPS2_PNGSRC = @as(u32, 8); pub const GCAPS2_CHANGEGAMMARAMP = @as(u32, 16); pub const GCAPS2_ALPHACURSOR = @as(u32, 32); pub const GCAPS2_SYNCFLUSH = @as(u32, 64); pub const GCAPS2_SYNCTIMER = @as(u32, 128); pub const GCAPS2_ICD_MULTIMON = @as(u32, 256); pub const GCAPS2_MOUSETRAILS = @as(u32, 512); pub const GCAPS2_RESERVED1 = @as(u32, 1024); pub const GCAPS2_REMOTEDRIVER = @as(u32, 1024); pub const GCAPS2_EXCLUDELAYERED = @as(u32, 2048); pub const GCAPS2_INCLUDEAPIBITMAPS = @as(u32, 4096); pub const GCAPS2_SHOWHIDDENPOINTER = @as(u32, 8192); pub const GCAPS2_CLEARTYPE = @as(u32, 16384); pub const GCAPS2_ACC_DRIVER = @as(u32, 32768); pub const GCAPS2_BITMAPEXREUSE = @as(u32, 65536); pub const LA_GEOMETRIC = @as(u32, 1); pub const LA_ALTERNATE = @as(u32, 2); pub const LA_STARTGAP = @as(u32, 4); pub const LA_STYLED = @as(u32, 8); pub const JOIN_ROUND = @as(i32, 0); pub const JOIN_BEVEL = @as(i32, 1); pub const JOIN_MITER = @as(i32, 2); pub const ENDCAP_ROUND = @as(i32, 0); pub const ENDCAP_SQUARE = @as(i32, 1); pub const ENDCAP_BUTT = @as(i32, 2); pub const PRIMARY_ORDER_ABC = @as(u32, 0); pub const PRIMARY_ORDER_ACB = @as(u32, 1); pub const PRIMARY_ORDER_BAC = @as(u32, 2); pub const PRIMARY_ORDER_BCA = @as(u32, 3); pub const PRIMARY_ORDER_CBA = @as(u32, 4); pub const PRIMARY_ORDER_CAB = @as(u32, 5); pub const HT_PATSIZE_2x2 = @as(u32, 0); pub const HT_PATSIZE_2x2_M = @as(u32, 1); pub const HT_PATSIZE_4x4 = @as(u32, 2); pub const HT_PATSIZE_4x4_M = @as(u32, 3); pub const HT_PATSIZE_6x6 = @as(u32, 4); pub const HT_PATSIZE_6x6_M = @as(u32, 5); pub const HT_PATSIZE_8x8 = @as(u32, 6); pub const HT_PATSIZE_8x8_M = @as(u32, 7); pub const HT_PATSIZE_10x10 = @as(u32, 8); pub const HT_PATSIZE_10x10_M = @as(u32, 9); pub const HT_PATSIZE_12x12 = @as(u32, 10); pub const HT_PATSIZE_12x12_M = @as(u32, 11); pub const HT_PATSIZE_14x14 = @as(u32, 12); pub const HT_PATSIZE_14x14_M = @as(u32, 13); pub const HT_PATSIZE_16x16 = @as(u32, 14); pub const HT_PATSIZE_16x16_M = @as(u32, 15); pub const HT_PATSIZE_SUPERCELL = @as(u32, 16); pub const HT_PATSIZE_SUPERCELL_M = @as(u32, 17); pub const HT_PATSIZE_USER = @as(u32, 18); pub const HT_PATSIZE_MAX_INDEX = @as(u32, 18); pub const HT_PATSIZE_DEFAULT = @as(u32, 17); pub const HT_USERPAT_CX_MIN = @as(u32, 4); pub const HT_USERPAT_CX_MAX = @as(u32, 256); pub const HT_USERPAT_CY_MIN = @as(u32, 4); pub const HT_USERPAT_CY_MAX = @as(u32, 256); pub const HT_FORMAT_1BPP = @as(u32, 0); pub const HT_FORMAT_4BPP = @as(u32, 2); pub const HT_FORMAT_4BPP_IRGB = @as(u32, 3); pub const HT_FORMAT_8BPP = @as(u32, 4); pub const HT_FORMAT_16BPP = @as(u32, 5); pub const HT_FORMAT_24BPP = @as(u32, 6); pub const HT_FORMAT_32BPP = @as(u32, 7); pub const WINDDI_MAX_BROADCAST_CONTEXT = @as(u32, 64); pub const HT_FLAG_SQUARE_DEVICE_PEL = @as(u32, 1); pub const HT_FLAG_HAS_BLACK_DYE = @as(u32, 2); pub const HT_FLAG_ADDITIVE_PRIMS = @as(u32, 4); pub const HT_FLAG_USE_8BPP_BITMASK = @as(u32, 8); pub const HT_FLAG_INK_HIGH_ABSORPTION = @as(u32, 16); pub const HT_FLAG_INK_ABSORPTION_INDICES = @as(u32, 96); pub const HT_FLAG_DO_DEVCLR_XFORM = @as(u32, 128); pub const HT_FLAG_OUTPUT_CMY = @as(u32, 256); pub const HT_FLAG_PRINT_DRAFT_MODE = @as(u32, 512); pub const HT_FLAG_INVERT_8BPP_BITMASK_IDX = @as(u32, 1024); pub const HT_FLAG_8BPP_CMY332_MASK = @as(u32, 4278190080); pub const HT_FLAG_INK_ABSORPTION_IDX0 = @as(u32, 0); pub const HT_FLAG_INK_ABSORPTION_IDX1 = @as(u32, 32); pub const HT_FLAG_INK_ABSORPTION_IDX2 = @as(u32, 64); pub const HT_FLAG_INK_ABSORPTION_IDX3 = @as(u32, 96); pub const HT_FLAG_NORMAL_INK_ABSORPTION = @as(u32, 0); pub const HT_FLAG_LOW_INK_ABSORPTION = @as(u32, 32); pub const HT_FLAG_LOWER_INK_ABSORPTION = @as(u32, 64); pub const HT_FLAG_LOWEST_INK_ABSORPTION = @as(u32, 96); pub const PPC_DEFAULT = @as(u32, 0); pub const PPC_UNDEFINED = @as(u32, 1); pub const PPC_RGB_ORDER_VERTICAL_STRIPES = @as(u32, 2); pub const PPC_BGR_ORDER_VERTICAL_STRIPES = @as(u32, 3); pub const PPC_RGB_ORDER_HORIZONTAL_STRIPES = @as(u32, 4); pub const PPC_BGR_ORDER_HORIZONTAL_STRIPES = @as(u32, 5); pub const PPG_DEFAULT = @as(u32, 0); pub const PPG_SRGB = @as(u32, 1); pub const BR_DEVICE_ICM = @as(u32, 1); pub const BR_HOST_ICM = @as(u32, 2); pub const BR_CMYKCOLOR = @as(u32, 4); pub const BR_ORIGCOLOR = @as(u32, 8); pub const FO_SIM_BOLD = @as(u32, 8192); pub const FO_SIM_ITALIC = @as(u32, 16384); pub const FO_EM_HEIGHT = @as(u32, 32768); pub const FO_GRAY16 = @as(u32, 65536); pub const FO_NOGRAY16 = @as(u32, 131072); pub const FO_NOHINTS = @as(u32, 262144); pub const FO_NO_CHOICE = @as(u32, 524288); pub const FO_CFF = @as(u32, 1048576); pub const FO_POSTSCRIPT = @as(u32, 2097152); pub const FO_MULTIPLEMASTER = @as(u32, 4194304); pub const FO_VERT_FACE = @as(u32, 8388608); pub const FO_DBCS_FONT = @as(u32, 16777216); pub const FO_NOCLEARTYPE = @as(u32, 33554432); pub const FO_CLEARTYPE_X = @as(u32, 268435456); pub const FO_CLEARTYPE_Y = @as(u32, 536870912); pub const FO_CLEARTYPENATURAL_X = @as(u32, 1073741824); pub const DC_TRIVIAL = @as(u32, 0); pub const DC_RECT = @as(u32, 1); pub const DC_COMPLEX = @as(u32, 3); pub const FC_RECT = @as(u32, 1); pub const FC_RECT4 = @as(u32, 2); pub const FC_COMPLEX = @as(u32, 3); pub const TC_RECTANGLES = @as(u32, 0); pub const TC_PATHOBJ = @as(u32, 2); pub const OC_BANK_CLIP = @as(u32, 1); pub const CT_RECTANGLES = @as(i32, 0); pub const CD_RIGHTDOWN = @as(i32, 0); pub const CD_LEFTDOWN = @as(i32, 1); pub const CD_RIGHTUP = @as(i32, 2); pub const CD_LEFTUP = @as(i32, 3); pub const CD_ANY = @as(i32, 4); pub const CD_LEFTWARDS = @as(i32, 1); pub const CD_UPWARDS = @as(i32, 2); pub const FO_HGLYPHS = @as(i32, 0); pub const FO_GLYPHBITS = @as(i32, 1); pub const FO_PATHOBJ = @as(i32, 2); pub const FD_NEGATIVE_FONT = @as(i32, 1); pub const FO_DEVICE_FONT = @as(i32, 1); pub const FO_OUTLINE_CAPABLE = @as(i32, 2); pub const SO_FLAG_DEFAULT_PLACEMENT = @as(u32, 1); pub const SO_HORIZONTAL = @as(u32, 2); pub const SO_VERTICAL = @as(u32, 4); pub const SO_REVERSED = @as(u32, 8); pub const SO_ZERO_BEARINGS = @as(u32, 16); pub const SO_CHAR_INC_EQUAL_BM_BASE = @as(u32, 32); pub const SO_MAXEXT_EQUAL_BM_SIDE = @as(u32, 64); pub const SO_DO_NOT_SUBSTITUTE_DEVICE_FONT = @as(u32, 128); pub const SO_GLYPHINDEX_TEXTOUT = @as(u32, 256); pub const SO_ESC_NOT_ORIENT = @as(u32, 512); pub const SO_DXDY = @as(u32, 1024); pub const SO_CHARACTER_EXTRA = @as(u32, 2048); pub const SO_BREAK_EXTRA = @as(u32, 4096); pub const FO_ATTR_MODE_ROTATE = @as(u32, 1); pub const PAL_INDEXED = @as(u32, 1); pub const PAL_BITFIELDS = @as(u32, 2); pub const PAL_RGB = @as(u32, 4); pub const PAL_BGR = @as(u32, 8); pub const PAL_CMYK = @as(u32, 16); pub const PO_BEZIERS = @as(u32, 1); pub const PO_ELLIPSE = @as(u32, 2); pub const PO_ALL_INTEGERS = @as(u32, 4); pub const PO_ENUM_AS_INTEGERS = @as(u32, 8); pub const PO_WIDENED = @as(u32, 16); pub const PD_BEGINSUBPATH = @as(u32, 1); pub const PD_ENDSUBPATH = @as(u32, 2); pub const PD_RESETSTYLE = @as(u32, 4); pub const PD_CLOSEFIGURE = @as(u32, 8); pub const PD_BEZIERS = @as(u32, 16); pub const SGI_EXTRASPACE = @as(u32, 0); pub const STYPE_BITMAP = @as(i32, 0); pub const STYPE_DEVBITMAP = @as(i32, 3); pub const BMF_1BPP = @as(i32, 1); pub const BMF_4BPP = @as(i32, 2); pub const BMF_8BPP = @as(i32, 3); pub const BMF_16BPP = @as(i32, 4); pub const BMF_24BPP = @as(i32, 5); pub const BMF_32BPP = @as(i32, 6); pub const BMF_4RLE = @as(i32, 7); pub const BMF_8RLE = @as(i32, 8); pub const BMF_JPEG = @as(i32, 9); pub const BMF_PNG = @as(i32, 10); pub const BMF_TOPDOWN = @as(u32, 1); pub const BMF_NOZEROINIT = @as(u32, 2); pub const BMF_DONTCACHE = @as(u32, 4); pub const BMF_USERMEM = @as(u32, 8); pub const BMF_KMSECTION = @as(u32, 16); pub const BMF_NOTSYSMEM = @as(u32, 32); pub const BMF_WINDOW_BLT = @as(u32, 64); pub const BMF_UMPDMEM = @as(u32, 128); pub const BMF_TEMP_ALPHA = @as(u32, 256); pub const BMF_ACC_NOTIFY = @as(u32, 32768); pub const BMF_RMT_ENTER = @as(u32, 16384); pub const BMF_RESERVED = @as(u32, 15872); pub const GX_IDENTITY = @as(i32, 0); pub const GX_OFFSET = @as(i32, 1); pub const GX_SCALE = @as(i32, 2); pub const GX_GENERAL = @as(i32, 3); pub const XF_LTOL = @as(i32, 0); pub const XF_INV_LTOL = @as(i32, 1); pub const XF_LTOFX = @as(i32, 2); pub const XF_INV_FXTOL = @as(i32, 3); pub const XO_TRIVIAL = @as(u32, 1); pub const XO_TABLE = @as(u32, 2); pub const XO_TO_MONO = @as(u32, 4); pub const XO_FROM_CMYK = @as(u32, 8); pub const XO_DEVICE_ICM = @as(u32, 16); pub const XO_HOST_ICM = @as(u32, 32); pub const XO_SRCPALETTE = @as(u32, 1); pub const XO_DESTPALETTE = @as(u32, 2); pub const XO_DESTDCPALETTE = @as(u32, 3); pub const XO_SRCBITFIELDS = @as(u32, 4); pub const XO_DESTBITFIELDS = @as(u32, 5); pub const HOOK_BITBLT = @as(u32, 1); pub const HOOK_STRETCHBLT = @as(u32, 2); pub const HOOK_PLGBLT = @as(u32, 4); pub const HOOK_TEXTOUT = @as(u32, 8); pub const HOOK_PAINT = @as(u32, 16); pub const HOOK_STROKEPATH = @as(u32, 32); pub const HOOK_FILLPATH = @as(u32, 64); pub const HOOK_STROKEANDFILLPATH = @as(u32, 128); pub const HOOK_LINETO = @as(u32, 256); pub const HOOK_COPYBITS = @as(u32, 1024); pub const HOOK_MOVEPANNING = @as(u32, 2048); pub const HOOK_SYNCHRONIZE = @as(u32, 4096); pub const HOOK_STRETCHBLTROP = @as(u32, 8192); pub const HOOK_SYNCHRONIZEACCESS = @as(u32, 16384); pub const HOOK_TRANSPARENTBLT = @as(u32, 32768); pub const HOOK_ALPHABLEND = @as(u32, 65536); pub const HOOK_GRADIENTFILL = @as(u32, 131072); pub const HOOK_FLAGS = @as(u32, 243199); pub const MS_NOTSYSTEMMEMORY = @as(u32, 1); pub const MS_SHAREDACCESS = @as(u32, 2); pub const MS_CDDDEVICEBITMAP = @as(u32, 4); pub const MS_REUSEDDEVICEBITMAP = @as(u32, 8); pub const DRVQUERY_USERMODE = @as(u32, 1); pub const HS_DDI_MAX = @as(u32, 6); pub const DRD_SUCCESS = @as(u32, 0); pub const DRD_ERROR = @as(u32, 1); pub const SS_SAVE = @as(u32, 0); pub const SS_RESTORE = @as(u32, 1); pub const SS_FREE = @as(u32, 2); pub const CDBEX_REDIRECTION = @as(u32, 1); pub const CDBEX_DXINTEROP = @as(u32, 2); pub const CDBEX_NTSHAREDSURFACEHANDLE = @as(u32, 4); pub const CDBEX_CROSSADAPTER = @as(u32, 8); pub const CDBEX_REUSE = @as(u32, 16); pub const WINDDI_MAXSETPALETTECOLORS = @as(u32, 256); pub const WINDDI_MAXSETPALETTECOLORINDEX = @as(u32, 255); pub const DM_DEFAULT = @as(u32, 1); pub const DM_MONOCHROME = @as(u32, 2); pub const DCR_SOLID = @as(u32, 0); pub const DCR_DRIVER = @as(u32, 1); pub const DCR_HALFTONE = @as(u32, 2); pub const RB_DITHERCOLOR = @as(i32, -2147483648); pub const QFT_LIGATURES = @as(i32, 1); pub const QFT_KERNPAIRS = @as(i32, 2); pub const QFT_GLYPHSET = @as(i32, 3); pub const QFD_GLYPHANDBITMAP = @as(i32, 1); pub const QFD_GLYPHANDOUTLINE = @as(i32, 2); pub const QFD_MAXEXTENTS = @as(i32, 3); pub const QFD_TT_GLYPHANDBITMAP = @as(i32, 4); pub const QFD_TT_GRAY1_BITMAP = @as(i32, 5); pub const QFD_TT_GRAY2_BITMAP = @as(i32, 6); pub const QFD_TT_GRAY4_BITMAP = @as(i32, 8); pub const QFD_TT_GRAY8_BITMAP = @as(i32, 9); pub const QFD_TT_MONO_BITMAP = @as(i32, 5); pub const QC_OUTLINES = @as(u32, 1); pub const QC_1BIT = @as(u32, 2); pub const QC_4BIT = @as(u32, 4); pub const FF_SIGNATURE_VERIFIED = @as(u32, 1); pub const FF_IGNORED_SIGNATURE = @as(u32, 2); pub const QAW_GETWIDTHS = @as(u32, 0); pub const QAW_GETEASYWIDTHS = @as(u32, 1); pub const TTO_METRICS_ONLY = @as(u32, 1); pub const TTO_QUBICS = @as(u32, 2); pub const TTO_UNHINTED = @as(u32, 4); pub const QFF_DESCRIPTION = @as(i32, 1); pub const QFF_NUMFACES = @as(i32, 2); pub const FP_ALTERNATEMODE = @as(i32, 1); pub const FP_WINDINGMODE = @as(i32, 2); pub const SPS_ERROR = @as(u32, 0); pub const SPS_DECLINE = @as(u32, 1); pub const SPS_ACCEPT_NOEXCLUDE = @as(u32, 2); pub const SPS_ACCEPT_EXCLUDE = @as(u32, 3); pub const SPS_ACCEPT_SYNCHRONOUS = @as(u32, 4); pub const SPS_CHANGE = @as(i32, 1); pub const SPS_ASYNCCHANGE = @as(i32, 2); pub const SPS_ANIMATESTART = @as(i32, 4); pub const SPS_ANIMATEUPDATE = @as(i32, 8); pub const SPS_ALPHA = @as(i32, 16); pub const SPS_RESERVED = @as(i32, 32); pub const SPS_RESERVED1 = @as(i32, 64); pub const SPS_FLAGSMASK = @as(i32, 255); pub const SPS_LENGTHMASK = @as(i32, 3840); pub const SPS_FREQMASK = @as(i32, 1044480); pub const ED_ABORTDOC = @as(u32, 1); pub const IGRF_RGB_256BYTES = @as(u32, 0); pub const IGRF_RGB_256WORDS = @as(u32, 1); pub const QDS_CHECKJPEGFORMAT = @as(u32, 0); pub const QDS_CHECKPNGFORMAT = @as(u32, 1); pub const DSS_TIMER_EVENT = @as(u32, 1); pub const DSS_FLUSH_EVENT = @as(u32, 2); pub const DSS_RESERVED = @as(u32, 4); pub const DSS_RESERVED1 = @as(u32, 8); pub const DSS_RESERVED2 = @as(u32, 16); pub const DN_ACCELERATION_LEVEL = @as(u32, 1); pub const DN_DEVICE_ORIGIN = @as(u32, 2); pub const DN_SLEEP_MODE = @as(u32, 3); pub const DN_DRAWING_BEGIN = @as(u32, 4); pub const DN_ASSOCIATE_WINDOW = @as(u32, 5); pub const DN_COMPOSITION_CHANGED = @as(u32, 6); pub const DN_DRAWING_BEGIN_APIBITMAP = @as(u32, 7); pub const DN_SURFOBJ_DESTRUCTION = @as(u32, 8); pub const WOC_RGN_CLIENT_DELTA = @as(u32, 1); pub const WOC_RGN_CLIENT = @as(u32, 2); pub const WOC_RGN_SURFACE_DELTA = @as(u32, 4); pub const WOC_RGN_SURFACE = @as(u32, 8); pub const WOC_CHANGED = @as(u32, 16); pub const WOC_DELETE = @as(u32, 32); pub const WOC_DRAWN = @as(u32, 64); pub const WOC_SPRITE_OVERLAP = @as(u32, 128); pub const WOC_SPRITE_NO_OVERLAP = @as(u32, 256); pub const WOC_RGN_SPRITE = @as(u32, 512); pub const WO_RGN_CLIENT_DELTA = @as(u32, 1); pub const WO_RGN_CLIENT = @as(u32, 2); pub const WO_RGN_SURFACE_DELTA = @as(u32, 4); pub const WO_RGN_SURFACE = @as(u32, 8); pub const WO_RGN_UPDATE_ALL = @as(u32, 16); pub const WO_RGN_WINDOW = @as(u32, 32); pub const WO_DRAW_NOTIFY = @as(u32, 64); pub const WO_SPRITE_NOTIFY = @as(u32, 128); pub const WO_RGN_DESKTOP_COORD = @as(u32, 256); pub const WO_RGN_SPRITE = @as(u32, 512); pub const EHN_RESTORED = @as(u32, 0); pub const EHN_ERROR = @as(u32, 1); pub const ECS_TEARDOWN = @as(u32, 1); pub const ECS_REDRAW = @as(u32, 2); pub const DEVHTADJF_COLOR_DEVICE = @as(u32, 1); pub const DEVHTADJF_ADDITIVE_DEVICE = @as(u32, 2); pub const FL_ZERO_MEMORY = @as(u32, 1); pub const FL_NONPAGED_MEMORY = @as(u32, 2); pub const FL_NON_SESSION = @as(u32, 4); pub const QSA_MMX = @as(u32, 256); pub const QSA_SSE = @as(u32, 8192); pub const QSA_3DNOW = @as(u32, 16384); pub const QSA_SSE1 = @as(u32, 8192); pub const QSA_SSE2 = @as(u32, 65536); pub const QSA_SSE3 = @as(u32, 524288); pub const ENG_FNT_CACHE_READ_FAULT = @as(u32, 1); pub const ENG_FNT_CACHE_WRITE_FAULT = @as(u32, 2); pub const DRH_APIBITMAP = @as(u32, 1); pub const MC_CAPS_NONE = @as(u32, 0); pub const MC_CAPS_MONITOR_TECHNOLOGY_TYPE = @as(u32, 1); pub const MC_CAPS_BRIGHTNESS = @as(u32, 2); pub const MC_CAPS_CONTRAST = @as(u32, 4); pub const MC_CAPS_COLOR_TEMPERATURE = @as(u32, 8); pub const MC_CAPS_RED_GREEN_BLUE_GAIN = @as(u32, 16); pub const MC_CAPS_RED_GREEN_BLUE_DRIVE = @as(u32, 32); pub const MC_CAPS_DEGAUSS = @as(u32, 64); pub const MC_CAPS_DISPLAY_AREA_POSITION = @as(u32, 128); pub const MC_CAPS_DISPLAY_AREA_SIZE = @as(u32, 256); pub const MC_CAPS_RESTORE_FACTORY_DEFAULTS = @as(u32, 1024); pub const MC_CAPS_RESTORE_FACTORY_COLOR_DEFAULTS = @as(u32, 2048); pub const MC_RESTORE_FACTORY_DEFAULTS_ENABLES_MONITOR_SETTINGS = @as(u32, 4096); pub const MC_SUPPORTED_COLOR_TEMPERATURE_NONE = @as(u32, 0); pub const MC_SUPPORTED_COLOR_TEMPERATURE_4000K = @as(u32, 1); pub const MC_SUPPORTED_COLOR_TEMPERATURE_5000K = @as(u32, 2); pub const MC_SUPPORTED_COLOR_TEMPERATURE_6500K = @as(u32, 4); pub const MC_SUPPORTED_COLOR_TEMPERATURE_7500K = @as(u32, 8); pub const MC_SUPPORTED_COLOR_TEMPERATURE_8200K = @as(u32, 16); pub const MC_SUPPORTED_COLOR_TEMPERATURE_9300K = @as(u32, 32); pub const MC_SUPPORTED_COLOR_TEMPERATURE_10000K = @as(u32, 64); pub const MC_SUPPORTED_COLOR_TEMPERATURE_11500K = @as(u32, 128); pub const PHYSICAL_MONITOR_DESCRIPTION_SIZE = @as(u32, 128); pub const GETCONNECTEDIDS_TARGET = @as(u32, 0); pub const GETCONNECTEDIDS_SOURCE = @as(u32, 1); pub const S_INIT = @as(u32, 2); pub const SETCONFIGURATION_STATUS_APPLIED = @as(u32, 0); pub const SETCONFIGURATION_STATUS_ADDITIONAL = @as(u32, 1); pub const SETCONFIGURATION_STATUS_OVERRIDDEN = @as(u32, 2); //-------------------------------------------------------------------------------- // Section: Types (316) //-------------------------------------------------------------------------------- // TODO: this type has a FreeFunc 'EngDeleteSemaphore', what can Zig do with this information? pub const HSEMAPHORE = *opaque{}; pub const HSURF = *opaque{}; pub const HFASTMUTEX = *opaque{}; pub const HDRVOBJ = *opaque{}; pub const HDEV = *opaque{}; pub const HBM = *opaque{}; pub const DHSURF = isize; pub const DHPDEV = isize; pub const DISPLAYCONFIG_RATIONAL = extern struct { Numerator: u32, Denominator: u32, }; pub const DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY = enum(i32) { OTHER = -1, HD15 = 0, SVIDEO = 1, COMPOSITE_VIDEO = 2, COMPONENT_VIDEO = 3, DVI = 4, HDMI = 5, LVDS = 6, D_JPN = 8, SDI = 9, DISPLAYPORT_EXTERNAL = 10, DISPLAYPORT_EMBEDDED = 11, UDI_EXTERNAL = 12, UDI_EMBEDDED = 13, SDTVDONGLE = 14, MIRACAST = 15, INDIRECT_WIRED = 16, INDIRECT_VIRTUAL = 17, DISPLAYPORT_USB_TUNNEL = 18, INTERNAL = -2147483648, // FORCE_UINT32 = -1, this enum value conflicts with OTHER }; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.OTHER; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HD15 = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.HD15; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SVIDEO = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.SVIDEO; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_COMPOSITE_VIDEO = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.COMPOSITE_VIDEO; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_COMPONENT_VIDEO = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.COMPONENT_VIDEO; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.DVI; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.HDMI; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_LVDS = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.LVDS; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_D_JPN = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.D_JPN; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SDI = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.SDI; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EXTERNAL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.DISPLAYPORT_EXTERNAL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EMBEDDED = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.DISPLAYPORT_EMBEDDED; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EXTERNAL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.UDI_EXTERNAL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EMBEDDED = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.UDI_EMBEDDED; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SDTVDONGLE = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.SDTVDONGLE; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_MIRACAST = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.MIRACAST; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INDIRECT_WIRED = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.INDIRECT_WIRED; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INDIRECT_VIRTUAL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.INDIRECT_VIRTUAL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_USB_TUNNEL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.DISPLAYPORT_USB_TUNNEL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.INTERNAL; pub const DISPLAYCONFIG_OUTPUT_TECHNOLOGY_FORCE_UINT32 = DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY.OTHER; pub const DISPLAYCONFIG_SCANLINE_ORDERING = enum(i32) { UNSPECIFIED = 0, PROGRESSIVE = 1, INTERLACED = 2, // INTERLACED_UPPERFIELDFIRST = 2, this enum value conflicts with INTERLACED INTERLACED_LOWERFIELDFIRST = 3, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED = DISPLAYCONFIG_SCANLINE_ORDERING.UNSPECIFIED; pub const DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE = DISPLAYCONFIG_SCANLINE_ORDERING.PROGRESSIVE; pub const DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED = DISPLAYCONFIG_SCANLINE_ORDERING.INTERLACED; pub const DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST = DISPLAYCONFIG_SCANLINE_ORDERING.INTERLACED; pub const DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST = DISPLAYCONFIG_SCANLINE_ORDERING.INTERLACED_LOWERFIELDFIRST; pub const DISPLAYCONFIG_SCANLINE_ORDERING_FORCE_UINT32 = DISPLAYCONFIG_SCANLINE_ORDERING.FORCE_UINT32; pub const DISPLAYCONFIG_2DREGION = extern struct { cx: u32, cy: u32, }; pub const DISPLAYCONFIG_VIDEO_SIGNAL_INFO = extern struct { pixelRate: u64, hSyncFreq: DISPLAYCONFIG_RATIONAL, vSyncFreq: DISPLAYCONFIG_RATIONAL, activeSize: DISPLAYCONFIG_2DREGION, totalSize: DISPLAYCONFIG_2DREGION, Anonymous: extern union { AdditionalSignalInfo: extern struct { _bitfield: u32, }, videoStandard: u32, }, scanLineOrdering: DISPLAYCONFIG_SCANLINE_ORDERING, }; pub const DISPLAYCONFIG_SCALING = enum(i32) { IDENTITY = 1, CENTERED = 2, STRETCHED = 3, ASPECTRATIOCENTEREDMAX = 4, CUSTOM = 5, PREFERRED = 128, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_SCALING_IDENTITY = DISPLAYCONFIG_SCALING.IDENTITY; pub const DISPLAYCONFIG_SCALING_CENTERED = DISPLAYCONFIG_SCALING.CENTERED; pub const DISPLAYCONFIG_SCALING_STRETCHED = DISPLAYCONFIG_SCALING.STRETCHED; pub const DISPLAYCONFIG_SCALING_ASPECTRATIOCENTEREDMAX = DISPLAYCONFIG_SCALING.ASPECTRATIOCENTEREDMAX; pub const DISPLAYCONFIG_SCALING_CUSTOM = DISPLAYCONFIG_SCALING.CUSTOM; pub const DISPLAYCONFIG_SCALING_PREFERRED = DISPLAYCONFIG_SCALING.PREFERRED; pub const DISPLAYCONFIG_SCALING_FORCE_UINT32 = DISPLAYCONFIG_SCALING.FORCE_UINT32; pub const DISPLAYCONFIG_ROTATION = enum(i32) { IDENTITY = 1, ROTATE90 = 2, ROTATE180 = 3, ROTATE270 = 4, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_ROTATION_IDENTITY = DISPLAYCONFIG_ROTATION.IDENTITY; pub const DISPLAYCONFIG_ROTATION_ROTATE90 = DISPLAYCONFIG_ROTATION.ROTATE90; pub const DISPLAYCONFIG_ROTATION_ROTATE180 = DISPLAYCONFIG_ROTATION.ROTATE180; pub const DISPLAYCONFIG_ROTATION_ROTATE270 = DISPLAYCONFIG_ROTATION.ROTATE270; pub const DISPLAYCONFIG_ROTATION_FORCE_UINT32 = DISPLAYCONFIG_ROTATION.FORCE_UINT32; pub const DISPLAYCONFIG_MODE_INFO_TYPE = enum(i32) { SOURCE = 1, TARGET = 2, DESKTOP_IMAGE = 3, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_MODE_INFO_TYPE_SOURCE = DISPLAYCONFIG_MODE_INFO_TYPE.SOURCE; pub const DISPLAYCONFIG_MODE_INFO_TYPE_TARGET = DISPLAYCONFIG_MODE_INFO_TYPE.TARGET; pub const DISPLAYCONFIG_MODE_INFO_TYPE_DESKTOP_IMAGE = DISPLAYCONFIG_MODE_INFO_TYPE.DESKTOP_IMAGE; pub const DISPLAYCONFIG_MODE_INFO_TYPE_FORCE_UINT32 = DISPLAYCONFIG_MODE_INFO_TYPE.FORCE_UINT32; pub const DISPLAYCONFIG_PIXELFORMAT = enum(i32) { @"8BPP" = 1, @"16BPP" = 2, @"24BPP" = 3, @"32BPP" = 4, NONGDI = 5, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_PIXELFORMAT_8BPP = DISPLAYCONFIG_PIXELFORMAT.@"8BPP"; pub const DISPLAYCONFIG_PIXELFORMAT_16BPP = DISPLAYCONFIG_PIXELFORMAT.@"16BPP"; pub const DISPLAYCONFIG_PIXELFORMAT_24BPP = DISPLAYCONFIG_PIXELFORMAT.@"24BPP"; pub const DISPLAYCONFIG_PIXELFORMAT_32BPP = DISPLAYCONFIG_PIXELFORMAT.@"32BPP"; pub const DISPLAYCONFIG_PIXELFORMAT_NONGDI = DISPLAYCONFIG_PIXELFORMAT.NONGDI; pub const DISPLAYCONFIG_PIXELFORMAT_FORCE_UINT32 = DISPLAYCONFIG_PIXELFORMAT.FORCE_UINT32; pub const DISPLAYCONFIG_SOURCE_MODE = extern struct { width: u32, height: u32, pixelFormat: DISPLAYCONFIG_PIXELFORMAT, position: POINTL, }; pub const DISPLAYCONFIG_TARGET_MODE = extern struct { targetVideoSignalInfo: DISPLAYCONFIG_VIDEO_SIGNAL_INFO, }; pub const DISPLAYCONFIG_DESKTOP_IMAGE_INFO = extern struct { PathSourceSize: POINTL, DesktopImageRegion: RECTL, DesktopImageClip: RECTL, }; pub const DISPLAYCONFIG_MODE_INFO = extern struct { infoType: DISPLAYCONFIG_MODE_INFO_TYPE, id: u32, adapterId: LUID, Anonymous: extern union { targetMode: DISPLAYCONFIG_TARGET_MODE, sourceMode: DISPLAYCONFIG_SOURCE_MODE, desktopImageInfo: DISPLAYCONFIG_DESKTOP_IMAGE_INFO, }, }; pub const DISPLAYCONFIG_PATH_SOURCE_INFO = extern struct { adapterId: LUID, id: u32, Anonymous: extern union { modeInfoIdx: u32, Anonymous: extern struct { _bitfield: u32, }, }, statusFlags: u32, }; pub const DISPLAYCONFIG_PATH_TARGET_INFO = extern struct { adapterId: LUID, id: u32, Anonymous: extern union { modeInfoIdx: u32, Anonymous: extern struct { _bitfield: u32, }, }, outputTechnology: DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY, rotation: DISPLAYCONFIG_ROTATION, scaling: DISPLAYCONFIG_SCALING, refreshRate: DISPLAYCONFIG_RATIONAL, scanLineOrdering: DISPLAYCONFIG_SCANLINE_ORDERING, targetAvailable: BOOL, statusFlags: u32, }; pub const DISPLAYCONFIG_PATH_INFO = extern struct { sourceInfo: DISPLAYCONFIG_PATH_SOURCE_INFO, targetInfo: DISPLAYCONFIG_PATH_TARGET_INFO, flags: u32, }; pub const DISPLAYCONFIG_TOPOLOGY_ID = enum(i32) { INTERNAL = 1, CLONE = 2, EXTEND = 4, EXTERNAL = 8, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_TOPOLOGY_INTERNAL = DISPLAYCONFIG_TOPOLOGY_ID.INTERNAL; pub const DISPLAYCONFIG_TOPOLOGY_CLONE = DISPLAYCONFIG_TOPOLOGY_ID.CLONE; pub const DISPLAYCONFIG_TOPOLOGY_EXTEND = DISPLAYCONFIG_TOPOLOGY_ID.EXTEND; pub const DISPLAYCONFIG_TOPOLOGY_EXTERNAL = DISPLAYCONFIG_TOPOLOGY_ID.EXTERNAL; pub const DISPLAYCONFIG_TOPOLOGY_FORCE_UINT32 = DISPLAYCONFIG_TOPOLOGY_ID.FORCE_UINT32; pub const DISPLAYCONFIG_DEVICE_INFO_TYPE = enum(i32) { GET_SOURCE_NAME = 1, GET_TARGET_NAME = 2, GET_TARGET_PREFERRED_MODE = 3, GET_ADAPTER_NAME = 4, SET_TARGET_PERSISTENCE = 5, GET_TARGET_BASE_TYPE = 6, GET_SUPPORT_VIRTUAL_RESOLUTION = 7, SET_SUPPORT_VIRTUAL_RESOLUTION = 8, GET_ADVANCED_COLOR_INFO = 9, SET_ADVANCED_COLOR_STATE = 10, GET_SDR_WHITE_LEVEL = 11, GET_MONITOR_SPECIALIZATION = 12, SET_MONITOR_SPECIALIZATION = 13, FORCE_UINT32 = -1, }; pub const DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_SOURCE_NAME; pub const DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_TARGET_NAME; pub const DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_PREFERRED_MODE = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_TARGET_PREFERRED_MODE; pub const DISPLAYCONFIG_DEVICE_INFO_GET_ADAPTER_NAME = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_ADAPTER_NAME; pub const DISPLAYCONFIG_DEVICE_INFO_SET_TARGET_PERSISTENCE = DISPLAYCONFIG_DEVICE_INFO_TYPE.SET_TARGET_PERSISTENCE; pub const DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_BASE_TYPE = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_TARGET_BASE_TYPE; pub const DISPLAYCONFIG_DEVICE_INFO_GET_SUPPORT_VIRTUAL_RESOLUTION = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_SUPPORT_VIRTUAL_RESOLUTION; pub const DISPLAYCONFIG_DEVICE_INFO_SET_SUPPORT_VIRTUAL_RESOLUTION = DISPLAYCONFIG_DEVICE_INFO_TYPE.SET_SUPPORT_VIRTUAL_RESOLUTION; pub const DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_ADVANCED_COLOR_INFO; pub const DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE = DISPLAYCONFIG_DEVICE_INFO_TYPE.SET_ADVANCED_COLOR_STATE; pub const DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_SDR_WHITE_LEVEL; pub const DISPLAYCONFIG_DEVICE_INFO_GET_MONITOR_SPECIALIZATION = DISPLAYCONFIG_DEVICE_INFO_TYPE.GET_MONITOR_SPECIALIZATION; pub const DISPLAYCONFIG_DEVICE_INFO_SET_MONITOR_SPECIALIZATION = DISPLAYCONFIG_DEVICE_INFO_TYPE.SET_MONITOR_SPECIALIZATION; pub const DISPLAYCONFIG_DEVICE_INFO_FORCE_UINT32 = DISPLAYCONFIG_DEVICE_INFO_TYPE.FORCE_UINT32; pub const DISPLAYCONFIG_DEVICE_INFO_HEADER = extern struct { type: DISPLAYCONFIG_DEVICE_INFO_TYPE, size: u32, adapterId: LUID, id: u32, }; pub const DISPLAYCONFIG_SOURCE_DEVICE_NAME = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, viewGdiDeviceName: [32]u16, }; pub const DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS = extern struct { Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, }; pub const DISPLAYCONFIG_TARGET_DEVICE_NAME = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, flags: DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS, outputTechnology: DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY, edidManufactureId: u16, edidProductCodeId: u16, connectorInstance: u32, monitorFriendlyDeviceName: [64]u16, monitorDevicePath: [128]u16, }; pub const DISPLAYCONFIG_TARGET_PREFERRED_MODE = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, width: u32, height: u32, targetMode: DISPLAYCONFIG_TARGET_MODE, }; pub const DISPLAYCONFIG_ADAPTER_NAME = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, adapterDevicePath: [128]u16, }; pub const DISPLAYCONFIG_TARGET_BASE_TYPE = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, baseOutputTechnology: DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY, }; pub const DISPLAYCONFIG_SET_TARGET_PERSISTENCE = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, }; pub const DISPLAYCONFIG_SUPPORT_VIRTUAL_RESOLUTION = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, }; pub const DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, colorEncoding: DISPLAYCONFIG_COLOR_ENCODING, bitsPerColorChannel: u32, }; pub const DISPLAYCONFIG_SET_ADVANCED_COLOR_STATE = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, }; pub const DISPLAYCONFIG_SDR_WHITE_LEVEL = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, SDRWhiteLevel: u32, }; pub const DISPLAYCONFIG_GET_MONITOR_SPECIALIZATION = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, }; pub const DISPLAYCONFIG_SET_MONITOR_SPECIALIZATION = extern struct { header: DISPLAYCONFIG_DEVICE_INFO_HEADER, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, value: u32, }, specializationType: Guid, specializationSubType: Guid, specializationApplicationName: [128]u16, }; pub const PHYSICAL_MONITOR = packed struct { hPhysicalMonitor: ?HANDLE, szPhysicalMonitorDescription: [128]u16, }; pub const MC_TIMING_REPORT = packed struct { dwHorizontalFrequencyInHZ: u32, dwVerticalFrequencyInHZ: u32, bTimingStatusByte: u8, }; pub const MC_VCP_CODE_TYPE = enum(i32) { MOMENTARY = 0, SET_PARAMETER = 1, }; pub const MC_MOMENTARY = MC_VCP_CODE_TYPE.MOMENTARY; pub const MC_SET_PARAMETER = MC_VCP_CODE_TYPE.SET_PARAMETER; pub const MC_DISPLAY_TECHNOLOGY_TYPE = enum(i32) { SHADOW_MASK_CATHODE_RAY_TUBE = 0, APERTURE_GRILL_CATHODE_RAY_TUBE = 1, THIN_FILM_TRANSISTOR = 2, LIQUID_CRYSTAL_ON_SILICON = 3, PLASMA = 4, ORGANIC_LIGHT_EMITTING_DIODE = 5, ELECTROLUMINESCENT = 6, MICROELECTROMECHANICAL = 7, FIELD_EMISSION_DEVICE = 8, }; pub const MC_SHADOW_MASK_CATHODE_RAY_TUBE = MC_DISPLAY_TECHNOLOGY_TYPE.SHADOW_MASK_CATHODE_RAY_TUBE; pub const MC_APERTURE_GRILL_CATHODE_RAY_TUBE = MC_DISPLAY_TECHNOLOGY_TYPE.APERTURE_GRILL_CATHODE_RAY_TUBE; pub const MC_THIN_FILM_TRANSISTOR = MC_DISPLAY_TECHNOLOGY_TYPE.THIN_FILM_TRANSISTOR; pub const MC_LIQUID_CRYSTAL_ON_SILICON = MC_DISPLAY_TECHNOLOGY_TYPE.LIQUID_CRYSTAL_ON_SILICON; pub const MC_PLASMA = MC_DISPLAY_TECHNOLOGY_TYPE.PLASMA; pub const MC_ORGANIC_LIGHT_EMITTING_DIODE = MC_DISPLAY_TECHNOLOGY_TYPE.ORGANIC_LIGHT_EMITTING_DIODE; pub const MC_ELECTROLUMINESCENT = MC_DISPLAY_TECHNOLOGY_TYPE.ELECTROLUMINESCENT; pub const MC_MICROELECTROMECHANICAL = MC_DISPLAY_TECHNOLOGY_TYPE.MICROELECTROMECHANICAL; pub const MC_FIELD_EMISSION_DEVICE = MC_DISPLAY_TECHNOLOGY_TYPE.FIELD_EMISSION_DEVICE; pub const MC_DRIVE_TYPE = enum(i32) { RED_DRIVE = 0, GREEN_DRIVE = 1, BLUE_DRIVE = 2, }; pub const MC_RED_DRIVE = MC_DRIVE_TYPE.RED_DRIVE; pub const MC_GREEN_DRIVE = MC_DRIVE_TYPE.GREEN_DRIVE; pub const MC_BLUE_DRIVE = MC_DRIVE_TYPE.BLUE_DRIVE; pub const MC_GAIN_TYPE = enum(i32) { RED_GAIN = 0, GREEN_GAIN = 1, BLUE_GAIN = 2, }; pub const MC_RED_GAIN = MC_GAIN_TYPE.RED_GAIN; pub const MC_GREEN_GAIN = MC_GAIN_TYPE.GREEN_GAIN; pub const MC_BLUE_GAIN = MC_GAIN_TYPE.BLUE_GAIN; pub const MC_POSITION_TYPE = enum(i32) { HORIZONTAL_POSITION = 0, VERTICAL_POSITION = 1, }; pub const MC_HORIZONTAL_POSITION = MC_POSITION_TYPE.HORIZONTAL_POSITION; pub const MC_VERTICAL_POSITION = MC_POSITION_TYPE.VERTICAL_POSITION; pub const MC_SIZE_TYPE = enum(i32) { WIDTH = 0, HEIGHT = 1, }; pub const MC_WIDTH = MC_SIZE_TYPE.WIDTH; pub const MC_HEIGHT = MC_SIZE_TYPE.HEIGHT; pub const MC_COLOR_TEMPERATURE = enum(i32) { UNKNOWN = 0, @"4000K" = 1, @"5000K" = 2, @"6500K" = 3, @"7500K" = 4, @"8200K" = 5, @"9300K" = 6, @"10000K" = 7, @"11500K" = 8, }; pub const MC_COLOR_TEMPERATURE_UNKNOWN = MC_COLOR_TEMPERATURE.UNKNOWN; pub const MC_COLOR_TEMPERATURE_4000K = MC_COLOR_TEMPERATURE.@"4000K"; pub const MC_COLOR_TEMPERATURE_5000K = MC_COLOR_TEMPERATURE.@"5000K"; pub const MC_COLOR_TEMPERATURE_6500K = MC_COLOR_TEMPERATURE.@"6500K"; pub const MC_COLOR_TEMPERATURE_7500K = MC_COLOR_TEMPERATURE.@"7500K"; pub const MC_COLOR_TEMPERATURE_8200K = MC_COLOR_TEMPERATURE.@"8200K"; pub const MC_COLOR_TEMPERATURE_9300K = MC_COLOR_TEMPERATURE.@"9300K"; pub const MC_COLOR_TEMPERATURE_10000K = MC_COLOR_TEMPERATURE.@"10000K"; pub const MC_COLOR_TEMPERATURE_11500K = MC_COLOR_TEMPERATURE.@"11500K"; pub const Sources = extern struct { sourceId: u32, numTargets: i32, aTargets: [1]u32, }; pub const Adapter = extern struct { AdapterName: [128]u16, numSources: i32, sources: [1]Sources, }; pub const Adapters = extern struct { numAdapters: i32, adapter: [1]Adapter, }; pub const DisplayMode = extern struct { DeviceName: [32]u16, devMode: DEVMODEW, }; pub const DisplayModes = extern struct { numDisplayModes: i32, displayMode: [1]DisplayMode, }; const IID_ICloneViewHelper_Value = Guid.initString("f6a3d4c4-5632-4d83-b0a1-fb88712b1eb7"); pub const IID_ICloneViewHelper = &IID_ICloneViewHelper_Value; pub const ICloneViewHelper = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetConnectedIDs: fn( self: *const ICloneViewHelper, wszAdaptorName: ?[*:0]const u16, pulCount: ?*u32, pulID: ?*u32, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveTopology: fn( self: *const ICloneViewHelper, wszAdaptorName: ?[*:0]const u16, ulSourceID: u32, pulCount: ?*u32, pulTargetID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetActiveTopology: fn( self: *const ICloneViewHelper, wszAdaptorName: ?[*:0]const u16, ulSourceID: u32, ulCount: u32, pulTargetID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Commit: fn( self: *const ICloneViewHelper, fFinalCall: BOOL, ) 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 ICloneViewHelper_GetConnectedIDs(self: *const T, wszAdaptorName: ?[*:0]const u16, pulCount: ?*u32, pulID: ?*u32, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICloneViewHelper.VTable, self.vtable).GetConnectedIDs(@ptrCast(*const ICloneViewHelper, self), wszAdaptorName, pulCount, pulID, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICloneViewHelper_GetActiveTopology(self: *const T, wszAdaptorName: ?[*:0]const u16, ulSourceID: u32, pulCount: ?*u32, pulTargetID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICloneViewHelper.VTable, self.vtable).GetActiveTopology(@ptrCast(*const ICloneViewHelper, self), wszAdaptorName, ulSourceID, pulCount, pulTargetID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICloneViewHelper_SetActiveTopology(self: *const T, wszAdaptorName: ?[*:0]const u16, ulSourceID: u32, ulCount: u32, pulTargetID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ICloneViewHelper.VTable, self.vtable).SetActiveTopology(@ptrCast(*const ICloneViewHelper, self), wszAdaptorName, ulSourceID, ulCount, pulTargetID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ICloneViewHelper_Commit(self: *const T, fFinalCall: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ICloneViewHelper.VTable, self.vtable).Commit(@ptrCast(*const ICloneViewHelper, self), fFinalCall); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IViewHelper_Value = Guid.initString("e85ccef5-aaaa-47f0-b5e3-61f7aecdc4c1"); pub const IID_IViewHelper = &IID_IViewHelper_Value; pub const IViewHelper = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetConnectedIDs: fn( self: *const IViewHelper, wszAdaptorName: ?[*:0]const u16, pulCount: ?*u32, pulID: ?*u32, ulFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveTopology: fn( self: *const IViewHelper, wszAdaptorName: ?[*:0]const u16, ulSourceID: u32, pulCount: ?*u32, pulTargetID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetActiveTopology: fn( self: *const IViewHelper, wszAdaptorName: ?[*:0]const u16, ulSourceID: u32, ulCount: u32, pulTargetID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Commit: fn( self: *const IViewHelper, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetConfiguration: fn( self: *const IViewHelper, pIStream: ?*IStream, pulStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProceedOnNewConfiguration: fn( self: *const IViewHelper, ) 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 IViewHelper_GetConnectedIDs(self: *const T, wszAdaptorName: ?[*:0]const u16, pulCount: ?*u32, pulID: ?*u32, ulFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IViewHelper.VTable, self.vtable).GetConnectedIDs(@ptrCast(*const IViewHelper, self), wszAdaptorName, pulCount, pulID, ulFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IViewHelper_GetActiveTopology(self: *const T, wszAdaptorName: ?[*:0]const u16, ulSourceID: u32, pulCount: ?*u32, pulTargetID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IViewHelper.VTable, self.vtable).GetActiveTopology(@ptrCast(*const IViewHelper, self), wszAdaptorName, ulSourceID, pulCount, pulTargetID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IViewHelper_SetActiveTopology(self: *const T, wszAdaptorName: ?[*:0]const u16, ulSourceID: u32, ulCount: u32, pulTargetID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IViewHelper.VTable, self.vtable).SetActiveTopology(@ptrCast(*const IViewHelper, self), wszAdaptorName, ulSourceID, ulCount, pulTargetID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IViewHelper_Commit(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IViewHelper.VTable, self.vtable).Commit(@ptrCast(*const IViewHelper, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IViewHelper_SetConfiguration(self: *const T, pIStream: ?*IStream, pulStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IViewHelper.VTable, self.vtable).SetConfiguration(@ptrCast(*const IViewHelper, self), pIStream, pulStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IViewHelper_GetProceedOnNewConfiguration(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IViewHelper.VTable, self.vtable).GetProceedOnNewConfiguration(@ptrCast(*const IViewHelper, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const VIDEOPARAMETERS = extern struct { Guid: Guid, dwOffset: u32, dwCommand: u32, dwFlags: u32, dwMode: u32, dwTVStandard: u32, dwAvailableModes: u32, dwAvailableTVStandard: u32, dwFlickerFilter: u32, dwOverScanX: u32, dwOverScanY: u32, dwMaxUnscaledX: u32, dwMaxUnscaledY: u32, dwPositionX: u32, dwPositionY: u32, dwBrightness: u32, dwContrast: u32, dwCPType: u32, dwCPCommand: u32, dwCPStandard: u32, dwCPKey: u32, bCP_APSTriggerBits: u32, bOEMCopyProtection: [256]u8, }; pub const POINTFIX = extern struct { x: i32, y: i32, }; pub const RECTFX = extern struct { xLeft: i32, yTop: i32, xRight: i32, yBottom: i32, }; pub const FD_DEVICEMETRICS = extern struct { flRealizedType: u32, pteBase: POINTE, pteSide: POINTE, lD: i32, fxMaxAscender: i32, fxMaxDescender: i32, ptlUnderline1: POINTL, ptlStrikeOut: POINTL, ptlULThickness: POINTL, ptlSOThickness: POINTL, cxMax: u32, cyMax: u32, cjGlyphMax: u32, fdxQuantized: FD_XFORM, lNonLinearExtLeading: i32, lNonLinearIntLeading: i32, lNonLinearMaxCharWidth: i32, lNonLinearAvgCharWidth: i32, lMinA: i32, lMinC: i32, lMinD: i32, alReserved: [1]i32, }; pub const LIGATURE = extern struct { culSize: u32, pwsz: ?PWSTR, chglyph: u32, ahglyph: [1]u32, }; pub const FD_LIGATURE = extern struct { culThis: u32, ulType: u32, cLigatures: u32, alig: [1]LIGATURE, }; pub const POINTQF = extern struct { x: LARGE_INTEGER, y: LARGE_INTEGER, }; pub const WCRUN = extern struct { wcLow: u16, cGlyphs: u16, phg: ?*u32, }; pub const FD_GLYPHSET = extern struct { cjThis: u32, flAccel: u32, cGlyphsSupported: u32, cRuns: u32, awcrun: [1]WCRUN, }; pub const FD_GLYPHATTR = extern struct { cjThis: u32, cGlyphs: u32, iMode: u32, aGlyphAttr: [1]u8, }; pub const FD_KERNINGPAIR = extern struct { wcFirst: u16, wcSecond: u16, fwdKern: i16, }; pub const FONTDIFF = extern struct { jReserved1: u8, jReserved2: u8, jReserved3: u8, bWeight: u8, usWinWeight: u16, fsSelection: u16, fwdAveCharWidth: i16, fwdMaxCharInc: i16, ptlCaret: POINTL, }; pub const FONTSIM = extern struct { dpBold: i32, dpItalic: i32, dpBoldItalic: i32, }; pub const IFIEXTRA = extern struct { ulIdentifier: u32, dpFontSig: i32, cig: u32, dpDesignVector: i32, dpAxesInfoW: i32, aulReserved: [1]u32, }; pub const PFN = fn( ) callconv(@import("std").os.windows.WINAPI) isize; pub const DRVFN = extern struct { iFunc: u32, pfn: ?PFN, }; pub const DRVENABLEDATA = extern struct { iDriverVersion: u32, c: u32, pdrvfn: ?*DRVFN, }; pub const DEVINFO = extern struct { flGraphicsCaps: u32, lfDefaultFont: LOGFONTW, lfAnsiVarFont: LOGFONTW, lfAnsiFixFont: LOGFONTW, cFonts: u32, iDitherFormat: u32, cxDither: u16, cyDither: u16, hpalDefault: ?HPALETTE, flGraphicsCaps2: u32, }; pub const CIECHROMA = extern struct { x: i32, y: i32, Y: i32, }; pub const COLORINFO = extern struct { Red: CIECHROMA, Green: CIECHROMA, Blue: CIECHROMA, Cyan: CIECHROMA, Magenta: CIECHROMA, Yellow: CIECHROMA, AlignmentWhite: CIECHROMA, RedGamma: i32, GreenGamma: i32, BlueGamma: i32, MagentaInCyanDye: i32, YellowInCyanDye: i32, CyanInMagentaDye: i32, YellowInMagentaDye: i32, CyanInYellowDye: i32, MagentaInYellowDye: i32, }; pub const CDDDXGK_REDIRBITMAPPRESENTINFO = extern struct { NumDirtyRects: u32, DirtyRect: ?*RECT, NumContexts: u32, hContext: [65]?HANDLE, bDoNotSynchronizeWithDxContent: BOOLEAN, }; pub const GDIINFO = extern struct { ulVersion: u32, ulTechnology: u32, ulHorzSize: u32, ulVertSize: u32, ulHorzRes: u32, ulVertRes: u32, cBitsPixel: u32, cPlanes: u32, ulNumColors: u32, flRaster: u32, ulLogPixelsX: u32, ulLogPixelsY: u32, flTextCaps: u32, ulDACRed: u32, ulDACGreen: u32, ulDACBlue: u32, ulAspectX: u32, ulAspectY: u32, ulAspectXY: u32, xStyleStep: i32, yStyleStep: i32, denStyleStep: i32, ptlPhysOffset: POINTL, szlPhysSize: SIZE, ulNumPalReg: u32, ciDevice: COLORINFO, ulDevicePelsDPI: u32, ulPrimaryOrder: u32, ulHTPatternSize: u32, ulHTOutputFormat: u32, flHTFlags: u32, ulVRefresh: u32, ulBltAlignment: u32, ulPanningHorzRes: u32, ulPanningVertRes: u32, xPanningAlignment: u32, yPanningAlignment: u32, cxHTPat: u32, cyHTPat: u32, pHTPatA: ?*u8, pHTPatB: ?*u8, pHTPatC: ?*u8, flShadeBlend: u32, ulPhysicalPixelCharacteristics: u32, ulPhysicalPixelGamma: u32, }; pub const BRUSHOBJ = extern struct { iSolidColor: u32, pvRbrush: ?*anyopaque, flColorType: u32, }; pub const CLIPOBJ = extern struct { iUniq: u32, rclBounds: RECTL, iDComplexity: u8, iFComplexity: u8, iMode: u8, fjOptions: u8, }; // TODO: this function pointer causes dependency loop problems, so it's stubbed out pub const FREEOBJPROC = fn() callconv(@import("std").os.windows.WINAPI) void; pub const DRIVEROBJ = extern struct { pvObj: ?*anyopaque, pFreeProc: ?FREEOBJPROC, hdev: ?HDEV, dhpdev: DHPDEV, }; pub const FONTOBJ = extern struct { iUniq: u32, iFace: u32, cxMax: u32, flFontType: u32, iTTUniq: usize, iFile: usize, sizLogResPpi: SIZE, ulStyleSize: u32, pvConsumer: ?*anyopaque, pvProducer: ?*anyopaque, }; pub const BLENDOBJ = extern struct { BlendFunction: BLENDFUNCTION, }; pub const PALOBJ = extern struct { ulReserved: u32, }; pub const PATHOBJ = extern struct { fl: u32, cCurves: u32, }; pub const SURFOBJ = extern struct { dhsurf: DHSURF, hsurf: ?HSURF, dhpdev: DHPDEV, hdev: ?HDEV, sizlBitmap: SIZE, cjBits: u32, pvBits: ?*anyopaque, pvScan0: ?*anyopaque, lDelta: i32, iUniq: u32, iBitmapFormat: u32, iType: u16, fjBitmap: u16, }; pub const WNDOBJ = extern struct { coClient: CLIPOBJ, pvConsumer: ?*anyopaque, rclClient: RECTL, psoOwner: ?*SURFOBJ, }; pub const XFORMOBJ = extern struct { ulReserved: u32, }; pub const XLATEOBJ = extern struct { iUniq: u32, flXlate: u32, iSrcType: u16, iDstType: u16, cEntries: u32, pulXlate: ?*u32, }; pub const ENUMRECTS = extern struct { c: u32, arcl: [1]RECTL, }; pub const GLYPHBITS = extern struct { ptlOrigin: POINTL, sizlBitmap: SIZE, aj: [1]u8, }; pub const GLYPHDEF = extern union { pgb: ?*GLYPHBITS, ppo: ?*PATHOBJ, }; pub const GLYPHPOS = extern struct { hg: u32, pgdf: ?*GLYPHDEF, ptl: POINTL, }; pub const GLYPHDATA = extern struct { gdf: GLYPHDEF, hg: u32, fxD: i32, fxA: i32, fxAB: i32, fxInkTop: i32, fxInkBottom: i32, rclInk: RECTL, ptqD: POINTQF, }; pub const STROBJ = extern struct { cGlyphs: u32, flAccel: u32, ulCharInc: u32, rclBkGround: RECTL, pgp: ?*GLYPHPOS, pwszOrg: ?PWSTR, }; pub const FONTINFO = extern struct { cjThis: u32, flCaps: u32, cGlyphsSupported: u32, cjMaxGlyph1: u32, cjMaxGlyph4: u32, cjMaxGlyph8: u32, cjMaxGlyph32: u32, }; pub const PATHDATA = extern struct { flags: u32, count: u32, pptfx: ?*POINTFIX, }; pub const RUN = extern struct { iStart: i32, iStop: i32, }; pub const CLIPLINE = extern struct { ptfxA: POINTFIX, ptfxB: POINTFIX, lStyleState: i32, c: u32, arun: [1]RUN, }; pub const PERBANDINFO = extern struct { bRepeatThisBand: BOOL, szlBand: SIZE, ulHorzRes: u32, ulVertRes: u32, }; pub const GAMMARAMP = extern struct { Red: [256]u16, Green: [256]u16, Blue: [256]u16, }; pub const WNDOBJCHANGEPROC = fn( pwo: ?*WNDOBJ, fl: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const DEVHTINFO = extern struct { HTFlags: u32, HTPatternSize: u32, DevPelsDPI: u32, ColorInfo: COLORINFO, }; pub const DEVHTADJDATA = extern struct { DeviceFlags: u32, DeviceXDPI: u32, DeviceYDPI: u32, pDefHTInfo: ?*DEVHTINFO, pAdjHTInfo: ?*DEVHTINFO, }; pub const TYPE1_FONT = extern struct { hPFM: ?HANDLE, hPFB: ?HANDLE, ulIdentifier: u32, }; pub const ENGSAFESEMAPHORE = extern struct { hsem: ?HSEMAPHORE, lCount: i32, }; pub const SORTCOMP = fn( pv1: ?*const anyopaque, pv2: ?*const anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const ENG_TIME_FIELDS = extern struct { usYear: u16, usMonth: u16, usDay: u16, usHour: u16, usMinute: u16, usSecond: u16, usMilliseconds: u16, usWeekday: u16, }; pub const ENG_SYSTEM_ATTRIBUTE = enum(i32) { ProcessorFeature = 1, NumberOfProcessors = 2, OptimumAvailableUserMemory = 3, OptimumAvailableSystemMemory = 4, }; pub const EngProcessorFeature = ENG_SYSTEM_ATTRIBUTE.ProcessorFeature; pub const EngNumberOfProcessors = ENG_SYSTEM_ATTRIBUTE.NumberOfProcessors; pub const EngOptimumAvailableUserMemory = ENG_SYSTEM_ATTRIBUTE.OptimumAvailableUserMemory; pub const EngOptimumAvailableSystemMemory = ENG_SYSTEM_ATTRIBUTE.OptimumAvailableSystemMemory; pub const ENG_DEVICE_ATTRIBUTE = enum(i32) { RESERVED = 0, ACCELERATION_LEVEL = 1, }; pub const QDA_RESERVED = ENG_DEVICE_ATTRIBUTE.RESERVED; pub const QDA_ACCELERATION_LEVEL = ENG_DEVICE_ATTRIBUTE.ACCELERATION_LEVEL; pub const EMFINFO = extern struct { nSize: u32, hdc: ?HDC, pvEMF: ?*u8, pvCurrentRecord: ?*u8, }; pub const PFN_DrvEnableDriver = fn( param0: u32, param1: u32, param2: ?*DRVENABLEDATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvEnablePDEV = fn( param0: ?*DEVMODEW, param1: ?PWSTR, param2: u32, param3: ?*?HSURF, param4: u32, param5: ?*GDIINFO, param6: u32, param7: ?*DEVINFO, param8: ?HDEV, param9: ?PWSTR, param10: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) DHPDEV; pub const PFN_DrvCompletePDEV = fn( param0: DHPDEV, param1: ?HDEV, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvResetDevice = fn( param0: DHPDEV, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_DrvDisablePDEV = fn( param0: DHPDEV, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvSynchronize = fn( param0: DHPDEV, param1: ?*RECTL, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvEnableSurface = fn( param0: DHPDEV, ) callconv(@import("std").os.windows.WINAPI) ?HSURF; pub const PFN_DrvDisableDriver = fn( ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvDisableSurface = fn( param0: DHPDEV, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvAssertMode = fn( param0: DHPDEV, param1: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvTextOut = fn( param0: ?*SURFOBJ, param1: ?*STROBJ, param2: ?*FONTOBJ, param3: ?*CLIPOBJ, param4: ?*RECTL, param5: ?*RECTL, param6: ?*BRUSHOBJ, param7: ?*BRUSHOBJ, param8: ?*POINTL, param9: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvStretchBlt = fn( param0: ?*SURFOBJ, param1: ?*SURFOBJ, param2: ?*SURFOBJ, param3: ?*CLIPOBJ, param4: ?*XLATEOBJ, param5: ?*COLORADJUSTMENT, param6: ?*POINTL, param7: ?*RECTL, param8: ?*RECTL, param9: ?*POINTL, param10: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvStretchBltROP = fn( param0: ?*SURFOBJ, param1: ?*SURFOBJ, param2: ?*SURFOBJ, param3: ?*CLIPOBJ, param4: ?*XLATEOBJ, param5: ?*COLORADJUSTMENT, param6: ?*POINTL, param7: ?*RECTL, param8: ?*RECTL, param9: ?*POINTL, param10: u32, param11: ?*BRUSHOBJ, param12: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvTransparentBlt = fn( param0: ?*SURFOBJ, param1: ?*SURFOBJ, param2: ?*CLIPOBJ, param3: ?*XLATEOBJ, param4: ?*RECTL, param5: ?*RECTL, param6: u32, param7: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvPlgBlt = fn( param0: ?*SURFOBJ, param1: ?*SURFOBJ, param2: ?*SURFOBJ, param3: ?*CLIPOBJ, param4: ?*XLATEOBJ, param5: ?*COLORADJUSTMENT, param6: ?*POINTL, param7: ?*POINTFIX, param8: ?*RECTL, param9: ?*POINTL, param10: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvBitBlt = fn( param0: ?*SURFOBJ, param1: ?*SURFOBJ, param2: ?*SURFOBJ, param3: ?*CLIPOBJ, param4: ?*XLATEOBJ, param5: ?*RECTL, param6: ?*POINTL, param7: ?*POINTL, param8: ?*BRUSHOBJ, param9: ?*POINTL, param10: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvRealizeBrush = fn( param0: ?*BRUSHOBJ, param1: ?*SURFOBJ, param2: ?*SURFOBJ, param3: ?*SURFOBJ, param4: ?*XLATEOBJ, param5: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvCopyBits = fn( param0: ?*SURFOBJ, param1: ?*SURFOBJ, param2: ?*CLIPOBJ, param3: ?*XLATEOBJ, param4: ?*RECTL, param5: ?*POINTL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvDitherColor = fn( param0: DHPDEV, param1: u32, param2: u32, param3: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_DrvCreateDeviceBitmap = fn( param0: DHPDEV, param1: SIZE, param2: u32, ) callconv(@import("std").os.windows.WINAPI) ?HBITMAP; pub const PFN_DrvDeleteDeviceBitmap = fn( param0: DHSURF, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvSetPalette = fn( param0: DHPDEV, param1: ?*PALOBJ, param2: u32, param3: u32, param4: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvEscape = fn( param0: ?*SURFOBJ, param1: u32, param2: u32, param3: ?*anyopaque, param4: u32, param5: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_DrvDrawEscape = fn( param0: ?*SURFOBJ, param1: u32, param2: ?*CLIPOBJ, param3: ?*RECTL, param4: u32, param5: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_DrvQueryFont = fn( param0: DHPDEV, param1: usize, param2: u32, param3: ?*usize, ) callconv(@import("std").os.windows.WINAPI) ?*IFIMETRICS; pub const PFN_DrvQueryFontTree = fn( param0: DHPDEV, param1: usize, param2: u32, param3: u32, param4: ?*usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub const PFN_DrvQueryFontData = fn( param0: DHPDEV, param1: ?*FONTOBJ, param2: u32, param3: u32, param4: ?*GLYPHDATA, param5: ?*anyopaque, param6: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_DrvFree = fn( param0: ?*anyopaque, param1: usize, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvDestroyFont = fn( param0: ?*FONTOBJ, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvQueryFontCaps = fn( param0: u32, param1: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_DrvLoadFontFile = fn( param0: u32, param1: ?*usize, param2: ?*?*anyopaque, param3: ?*u32, param4: ?*DESIGNVECTOR, param5: u32, param6: u32, ) callconv(@import("std").os.windows.WINAPI) usize; pub const PFN_DrvUnloadFontFile = fn( param0: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvSetPointerShape = fn( param0: ?*SURFOBJ, param1: ?*SURFOBJ, param2: ?*SURFOBJ, param3: ?*XLATEOBJ, param4: i32, param5: i32, param6: i32, param7: i32, param8: ?*RECTL, param9: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_DrvMovePointer = fn( pso: ?*SURFOBJ, x: i32, y: i32, prcl: ?*RECTL, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvSendPage = fn( param0: ?*SURFOBJ, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvStartPage = fn( pso: ?*SURFOBJ, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvStartDoc = fn( pso: ?*SURFOBJ, pwszDocName: ?PWSTR, dwJobId: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvEndDoc = fn( pso: ?*SURFOBJ, fl: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvQuerySpoolType = fn( dhpdev: DHPDEV, pwchType: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvLineTo = fn( param0: ?*SURFOBJ, param1: ?*CLIPOBJ, param2: ?*BRUSHOBJ, param3: i32, param4: i32, param5: i32, param6: i32, param7: ?*RECTL, param8: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvStrokePath = fn( param0: ?*SURFOBJ, param1: ?*PATHOBJ, param2: ?*CLIPOBJ, param3: ?*XFORMOBJ, param4: ?*BRUSHOBJ, param5: ?*POINTL, param6: ?*LINEATTRS, param7: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvFillPath = fn( param0: ?*SURFOBJ, param1: ?*PATHOBJ, param2: ?*CLIPOBJ, param3: ?*BRUSHOBJ, param4: ?*POINTL, param5: u32, param6: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvStrokeAndFillPath = fn( param0: ?*SURFOBJ, param1: ?*PATHOBJ, param2: ?*CLIPOBJ, param3: ?*XFORMOBJ, param4: ?*BRUSHOBJ, param5: ?*LINEATTRS, param6: ?*BRUSHOBJ, param7: ?*POINTL, param8: u32, param9: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvPaint = fn( param0: ?*SURFOBJ, param1: ?*CLIPOBJ, param2: ?*BRUSHOBJ, param3: ?*POINTL, param4: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvGetGlyphMode = fn( dhpdev: DHPDEV, pfo: ?*FONTOBJ, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_DrvResetPDEV = fn( dhpdevOld: DHPDEV, dhpdevNew: DHPDEV, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvSaveScreenBits = fn( param0: ?*SURFOBJ, param1: u32, param2: usize, param3: ?*RECTL, ) callconv(@import("std").os.windows.WINAPI) usize; pub const PFN_DrvGetModes = fn( param0: ?HANDLE, param1: u32, param2: ?*DEVMODEW, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_DrvQueryTrueTypeTable = fn( param0: usize, param1: u32, param2: u32, param3: i32, param4: u32, param5: ?*u8, param6: ?*?*u8, param7: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_DrvQueryTrueTypeSection = fn( param0: u32, param1: u32, param2: u32, param3: ?*?HANDLE, param4: ?*i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_DrvQueryTrueTypeOutline = fn( param0: DHPDEV, param1: ?*FONTOBJ, param2: u32, param3: BOOL, param4: ?*GLYPHDATA, param5: u32, param6: ?*TTPOLYGONHEADER, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_DrvGetTrueTypeFile = fn( param0: usize, param1: ?*u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub const PFN_DrvQueryFontFile = fn( param0: usize, param1: u32, param2: u32, param3: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_DrvQueryGlyphAttrs = fn( param0: ?*FONTOBJ, param1: u32, ) callconv(@import("std").os.windows.WINAPI) ?*FD_GLYPHATTR; pub const PFN_DrvQueryAdvanceWidths = fn( param0: DHPDEV, param1: ?*FONTOBJ, param2: u32, param3: ?*u32, param4: ?*anyopaque, param5: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvFontManagement = fn( param0: ?*SURFOBJ, param1: ?*FONTOBJ, param2: u32, param3: u32, param4: ?*anyopaque, param5: u32, param6: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFN_DrvSetPixelFormat = fn( param0: ?*SURFOBJ, param1: i32, param2: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvDescribePixelFormat = fn( param0: DHPDEV, param1: i32, param2: u32, param3: ?*PIXELFORMATDESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_DrvSwapBuffers = fn( param0: ?*SURFOBJ, param1: ?*WNDOBJ, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvStartBanding = fn( param0: ?*SURFOBJ, ppointl: ?*POINTL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvNextBand = fn( param0: ?*SURFOBJ, ppointl: ?*POINTL, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvQueryPerBandInfo = fn( param0: ?*SURFOBJ, param1: ?*PERBANDINFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvEnableDirectDraw = fn( param0: DHPDEV, param1: ?*DD_CALLBACKS, param2: ?*DD_SURFACECALLBACKS, param3: ?*DD_PALETTECALLBACKS, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvDisableDirectDraw = fn( param0: DHPDEV, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvGetDirectDrawInfo = fn( param0: DHPDEV, param1: ?*DD_HALINFO, param2: ?*u32, param3: ?*VIDEOMEMORY, param4: ?*u32, param5: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvIcmCreateColorTransform = fn( param0: DHPDEV, param1: ?*LOGCOLORSPACEW, param2: ?*anyopaque, param3: u32, param4: ?*anyopaque, param5: u32, param6: ?*anyopaque, param7: u32, param8: u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub const PFN_DrvIcmDeleteColorTransform = fn( param0: DHPDEV, param1: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvIcmCheckBitmapBits = fn( param0: DHPDEV, param1: ?HANDLE, param2: ?*SURFOBJ, param3: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvIcmSetDeviceGammaRamp = fn( param0: DHPDEV, param1: u32, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvAlphaBlend = fn( param0: ?*SURFOBJ, param1: ?*SURFOBJ, param2: ?*CLIPOBJ, param3: ?*XLATEOBJ, param4: ?*RECTL, param5: ?*RECTL, param6: ?*BLENDOBJ, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvGradientFill = fn( param0: ?*SURFOBJ, param1: ?*CLIPOBJ, param2: ?*XLATEOBJ, param3: ?*TRIVERTEX, param4: u32, param5: ?*anyopaque, param6: u32, param7: ?*RECTL, param8: ?*POINTL, param9: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvQueryDeviceSupport = fn( param0: ?*SURFOBJ, param1: ?*XLATEOBJ, param2: ?*XFORMOBJ, param3: u32, param4: u32, param5: ?*anyopaque, param6: u32, param7: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvDeriveSurface = fn( param0: ?*DD_DIRECTDRAW_GLOBAL, param1: ?*DD_SURFACE_LOCAL, ) callconv(@import("std").os.windows.WINAPI) ?HBITMAP; pub const PFN_DrvSynchronizeSurface = fn( param0: ?*SURFOBJ, param1: ?*RECTL, param2: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvNotify = fn( param0: ?*SURFOBJ, param1: u32, param2: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvRenderHint = fn( dhpdev: DHPDEV, NotifyCode: u32, Length: usize, // TODO: what to do with BytesParamIndex 2? Data: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const DRH_APIBITMAPDATA = extern struct { pso: ?*SURFOBJ, b: BOOL, }; pub const PFN_EngCreateRectRgn = fn( left: i32, top: i32, right: i32, bottom: i32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub const PFN_EngDeleteRgn = fn( hrgn: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_EngCombineRgn = fn( hrgnTrg: ?HANDLE, hrgnSrc1: ?HANDLE, hrgnSrc2: ?HANDLE, imode: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_EngCopyRgn = fn( hrgnDst: ?HANDLE, hrgnSrc: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_EngIntersectRgn = fn( hrgnResult: ?HANDLE, hRgnA: ?HANDLE, hRgnB: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_EngSubtractRgn = fn( hrgnResult: ?HANDLE, hRgnA: ?HANDLE, hRgnB: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_EngUnionRgn = fn( hrgnResult: ?HANDLE, hRgnA: ?HANDLE, hRgnB: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_EngXorRgn = fn( hrgnResult: ?HANDLE, hRgnA: ?HANDLE, hRgnB: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFN_DrvCreateDeviceBitmapEx = fn( param0: DHPDEV, param1: SIZE, param2: u32, param3: u32, param4: DHSURF, param5: u32, param6: u32, param7: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) ?HBITMAP; pub const PFN_DrvDeleteDeviceBitmapEx = fn( param0: DHSURF, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvAssociateSharedSurface = fn( param0: ?*SURFOBJ, param1: ?HANDLE, param2: ?HANDLE, param3: SIZE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvSynchronizeRedirectionBitmaps = fn( param0: DHPDEV, param1: ?*u64, ) callconv(@import("std").os.windows.WINAPI) NTSTATUS; pub const PFN_DrvAccumulateD3DDirtyRect = fn( param0: ?*SURFOBJ, param1: ?*CDDDXGK_REDIRBITMAPPRESENTINFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvStartDxInterop = fn( param0: ?*SURFOBJ, param1: BOOL, KernelModeDeviceHandle: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvEndDxInterop = fn( param0: ?*SURFOBJ, param1: BOOL, param2: ?*BOOL, KernelModeDeviceHandle: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvLockDisplayArea = fn( param0: DHPDEV, param1: ?*RECTL, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvUnlockDisplayArea = fn( param0: DHPDEV, param1: ?*RECTL, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFN_DrvSurfaceComplete = fn( param0: DHPDEV, param1: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const INDIRECT_DISPLAY_INFO = extern struct { DisplayAdapterLuid: LUID, Flags: u32, NumMonitors: u32, DisplayAdapterTargetBase: u32, }; pub const VIDEO_VDM = extern struct { ProcessHandle: ?HANDLE, }; pub const VIDEO_REGISTER_VDM = extern struct { MinimumStateSize: u32, }; pub const VIDEO_MONITOR_DESCRIPTOR = extern struct { DescriptorSize: u32, Descriptor: [1]u8, }; pub const VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE = enum(i32) { PowerNotifyCallout = 1, EnumChildPdoNotifyCallout = 3, FindAdapterCallout = 4, PnpNotifyCallout = 7, DxgkDisplaySwitchCallout = 8, DxgkFindAdapterTdrCallout = 10, DxgkHardwareProtectionTeardown = 11, RepaintDesktop = 12, UpdateCursor = 13, DisableMultiPlaneOverlay = 14, DesktopDuplicationChange = 15, BlackScreenDiagnostics = 16, }; pub const VideoPowerNotifyCallout = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.PowerNotifyCallout; pub const VideoEnumChildPdoNotifyCallout = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.EnumChildPdoNotifyCallout; pub const VideoFindAdapterCallout = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.FindAdapterCallout; pub const VideoPnpNotifyCallout = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.PnpNotifyCallout; pub const VideoDxgkDisplaySwitchCallout = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.DxgkDisplaySwitchCallout; pub const VideoDxgkFindAdapterTdrCallout = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.DxgkFindAdapterTdrCallout; pub const VideoDxgkHardwareProtectionTeardown = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.DxgkHardwareProtectionTeardown; pub const VideoRepaintDesktop = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.RepaintDesktop; pub const VideoUpdateCursor = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.UpdateCursor; pub const VideoDisableMultiPlaneOverlay = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.DisableMultiPlaneOverlay; pub const VideoDesktopDuplicationChange = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.DesktopDuplicationChange; pub const VideoBlackScreenDiagnostics = VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE.BlackScreenDiagnostics; pub const BlackScreenDiagnosticsCalloutParam = enum(i32) { agnosticsData = 1, splayRecovery = 2, }; pub const BlackScreenDiagnosticsData = BlackScreenDiagnosticsCalloutParam.agnosticsData; pub const BlackScreenDisplayRecovery = BlackScreenDiagnosticsCalloutParam.splayRecovery; pub const DXGK_WIN32K_PARAM_DATA = extern struct { PathsArray: ?*anyopaque, ModesArray: ?*anyopaque, NumPathArrayElements: u32, NumModeArrayElements: u32, SDCFlags: u32, }; pub const VIDEO_WIN32K_CALLBACKS_PARAMS = extern struct { CalloutType: VIDEO_WIN32K_CALLBACKS_PARAMS_TYPE, PhysDisp: ?*anyopaque, Param: usize, Status: i32, LockUserSession: BOOLEAN, IsPostDevice: BOOLEAN, SurpriseRemoval: BOOLEAN, WaitForQueueReady: BOOLEAN, }; pub const PVIDEO_WIN32K_CALLOUT = fn( Params: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const VIDEO_WIN32K_CALLBACKS = extern struct { PhysDisp: ?*anyopaque, Callout: ?PVIDEO_WIN32K_CALLOUT, bACPI: u32, pPhysDeviceObject: ?HANDLE, DualviewFlags: u32, }; pub const VIDEO_DEVICE_SESSION_STATUS = extern struct { bEnable: u32, bSuccess: u32, }; pub const VIDEO_HARDWARE_STATE_HEADER = extern struct { Length: u32, PortValue: [48]u8, AttribIndexDataState: u32, BasicSequencerOffset: u32, BasicCrtContOffset: u32, BasicGraphContOffset: u32, BasicAttribContOffset: u32, BasicDacOffset: u32, BasicLatchesOffset: u32, ExtendedSequencerOffset: u32, ExtendedCrtContOffset: u32, ExtendedGraphContOffset: u32, ExtendedAttribContOffset: u32, ExtendedDacOffset: u32, ExtendedValidatorStateOffset: u32, ExtendedMiscDataOffset: u32, PlaneLength: u32, Plane1Offset: u32, Plane2Offset: u32, Plane3Offset: u32, Plane4Offset: u32, VGAStateFlags: u32, DIBOffset: u32, DIBBitsPerPixel: u32, DIBXResolution: u32, DIBYResolution: u32, DIBXlatOffset: u32, DIBXlatLength: u32, VesaInfoOffset: u32, FrameBufferData: ?*anyopaque, }; pub const VIDEO_HARDWARE_STATE = extern struct { StateHeader: ?*VIDEO_HARDWARE_STATE_HEADER, StateLength: u32, }; pub const VIDEO_NUM_MODES = extern struct { NumModes: u32, ModeInformationLength: u32, }; pub const VIDEO_MODE = extern struct { RequestedMode: u32, }; pub const VIDEO_MODE_INFORMATION = extern struct { Length: u32, ModeIndex: u32, VisScreenWidth: u32, VisScreenHeight: u32, ScreenStride: u32, NumberOfPlanes: u32, BitsPerPlane: u32, Frequency: u32, XMillimeter: u32, YMillimeter: u32, NumberRedBits: u32, NumberGreenBits: u32, NumberBlueBits: u32, RedMask: u32, GreenMask: u32, BlueMask: u32, AttributeFlags: u32, VideoMemoryBitmapWidth: u32, VideoMemoryBitmapHeight: u32, DriverSpecificAttributeFlags: u32, }; pub const VIDEO_LOAD_FONT_INFORMATION = extern struct { WidthInPixels: u16, HeightInPixels: u16, FontSize: u32, Font: [1]u8, }; pub const VIDEO_PALETTE_DATA = extern struct { NumEntries: u16, FirstEntry: u16, Colors: [1]u16, }; pub const VIDEO_CLUTDATA = extern struct { Red: u8, Green: u8, Blue: u8, Unused: u8, }; pub const VIDEO_CLUT = extern struct { NumEntries: u16, FirstEntry: u16, LookupTable: [1]extern union { RgbArray: VIDEO_CLUTDATA, RgbLong: u32, }, }; pub const VIDEO_CURSOR_POSITION = extern struct { Column: i16, Row: i16, }; pub const VIDEO_CURSOR_ATTRIBUTES = extern struct { Width: u16, Height: u16, Column: i16, Row: i16, Rate: u8, Enable: u8, }; pub const VIDEO_POINTER_POSITION = extern struct { Column: i16, Row: i16, }; pub const VIDEO_POINTER_ATTRIBUTES = extern struct { Flags: u32, Width: u32, Height: u32, WidthInBytes: u32, Enable: u32, Column: i16, Row: i16, Pixels: [1]u8, }; pub const VIDEO_POINTER_CAPABILITIES = extern struct { Flags: u32, MaxWidth: u32, MaxHeight: u32, HWPtrBitmapStart: u32, HWPtrBitmapEnd: u32, }; pub const VIDEO_BANK_SELECT = extern struct { Length: u32, Size: u32, BankingFlags: u32, BankingType: u32, PlanarHCBankingType: u32, BitmapWidthInBytes: u32, BitmapSize: u32, Granularity: u32, PlanarHCGranularity: u32, CodeOffset: u32, PlanarHCBankCodeOffset: u32, PlanarHCEnableCodeOffset: u32, PlanarHCDisableCodeOffset: u32, }; pub const VIDEO_BANK_TYPE = enum(i32) { VideoNotBanked = 0, VideoBanked1RW = 1, VideoBanked1R1W = 2, VideoBanked2RW = 3, NumVideoBankTypes = 4, }; pub const VideoNotBanked = VIDEO_BANK_TYPE.VideoNotBanked; pub const VideoBanked1RW = VIDEO_BANK_TYPE.VideoBanked1RW; pub const VideoBanked1R1W = VIDEO_BANK_TYPE.VideoBanked1R1W; pub const VideoBanked2RW = VIDEO_BANK_TYPE.VideoBanked2RW; pub const NumVideoBankTypes = VIDEO_BANK_TYPE.NumVideoBankTypes; pub const VIDEO_MEMORY = extern struct { RequestedVirtualAddress: ?*anyopaque, }; pub const VIDEO_SHARE_MEMORY = extern struct { ProcessHandle: ?HANDLE, ViewOffset: u32, ViewSize: u32, RequestedVirtualAddress: ?*anyopaque, }; pub const VIDEO_SHARE_MEMORY_INFORMATION = extern struct { SharedViewOffset: u32, SharedViewSize: u32, VirtualAddress: ?*anyopaque, }; pub const VIDEO_MEMORY_INFORMATION = extern struct { VideoRamBase: ?*anyopaque, VideoRamLength: u32, FrameBufferBase: ?*anyopaque, FrameBufferLength: u32, }; pub const VIDEO_PUBLIC_ACCESS_RANGES = extern struct { InIoSpace: u32, MappedInIoSpace: u32, VirtualAddress: ?*anyopaque, }; pub const VIDEO_COLOR_CAPABILITIES = extern struct { Length: u32, AttributeFlags: u32, RedPhosphoreDecay: i32, GreenPhosphoreDecay: i32, BluePhosphoreDecay: i32, WhiteChromaticity_x: i32, WhiteChromaticity_y: i32, WhiteChromaticity_Y: i32, RedChromaticity_x: i32, RedChromaticity_y: i32, GreenChromaticity_x: i32, GreenChromaticity_y: i32, BlueChromaticity_x: i32, BlueChromaticity_y: i32, WhiteGamma: i32, RedGamma: i32, GreenGamma: i32, BlueGamma: i32, }; pub const VIDEO_POWER_STATE = enum(i32) { Unspecified = 0, On = 1, StandBy = 2, Suspend = 3, Off = 4, Hibernate = 5, Shutdown = 6, Maximum = 7, }; pub const VideoPowerUnspecified = VIDEO_POWER_STATE.Unspecified; pub const VideoPowerOn = VIDEO_POWER_STATE.On; pub const VideoPowerStandBy = VIDEO_POWER_STATE.StandBy; pub const VideoPowerSuspend = VIDEO_POWER_STATE.Suspend; pub const VideoPowerOff = VIDEO_POWER_STATE.Off; pub const VideoPowerHibernate = VIDEO_POWER_STATE.Hibernate; pub const VideoPowerShutdown = VIDEO_POWER_STATE.Shutdown; pub const VideoPowerMaximum = VIDEO_POWER_STATE.Maximum; pub const VIDEO_POWER_MANAGEMENT = extern struct { Length: u32, DPMSVersion: u32, PowerState: u32, }; pub const VIDEO_COLOR_LUT_DATA = extern struct { Length: u32, LutDataFormat: u32, LutData: [1]u8, }; pub const VIDEO_LUT_RGB256WORDS = extern struct { Red: [256]u16, Green: [256]u16, Blue: [256]u16, }; pub const BANK_POSITION = extern struct { ReadBankPosition: u32, WriteBankPosition: u32, }; pub const DISPLAY_BRIGHTNESS = extern struct { ucDisplayPolicy: u8, ucACBrightness: u8, ucDCBrightness: u8, }; pub const VIDEO_BRIGHTNESS_POLICY = extern struct { DefaultToBiosPolicy: BOOLEAN, LevelCount: u8, Level: [1]extern struct { BatteryLevel: u8, Brightness: u8, }, }; pub const FSCNTL_SCREEN_INFO = extern struct { Position: COORD, ScreenSize: COORD, nNumberOfChars: u32, }; pub const FONT_IMAGE_INFO = extern struct { FontSize: COORD, ImageBits: ?*u8, }; pub const CHAR_IMAGE_INFO = extern struct { CharInfo: CHAR_INFO, FontImageInfo: FONT_IMAGE_INFO, }; pub const VGA_CHAR = extern struct { Char: CHAR, Attributes: CHAR, }; pub const FSVIDEO_COPY_FRAME_BUFFER = extern struct { SrcScreen: FSCNTL_SCREEN_INFO, DestScreen: FSCNTL_SCREEN_INFO, }; pub const FSVIDEO_WRITE_TO_FRAME_BUFFER = extern struct { SrcBuffer: ?*CHAR_IMAGE_INFO, DestScreen: FSCNTL_SCREEN_INFO, }; pub const FSVIDEO_REVERSE_MOUSE_POINTER = extern struct { Screen: FSCNTL_SCREEN_INFO, dwType: u32, }; pub const FSVIDEO_MODE_INFORMATION = extern struct { VideoMode: VIDEO_MODE_INFORMATION, VideoMemory: VIDEO_MEMORY_INFORMATION, }; pub const FSVIDEO_SCREEN_INFORMATION = extern struct { ScreenSize: COORD, FontSize: COORD, }; pub const FSVIDEO_CURSOR_POSITION = extern struct { Coord: VIDEO_CURSOR_POSITION, dwType: u32, }; pub const ENG_EVENT = extern struct { pKEvent: ?*anyopaque, fFlags: u32, }; pub const VIDEO_PERFORMANCE_COUNTER = extern struct { NbOfAllocationEvicted: [10]u64, NbOfAllocationMarked: [10]u64, NbOfAllocationRestored: [10]u64, KBytesEvicted: [10]u64, KBytesMarked: [10]u64, KBytesRestored: [10]u64, NbProcessCommited: u64, NbAllocationCommited: u64, NbAllocationMarked: u64, KBytesAllocated: u64, KBytesAvailable: u64, KBytesCurMarked: u64, Reference: u64, Unreference: u64, TrueReference: u64, NbOfPageIn: u64, KBytesPageIn: u64, NbOfPageOut: u64, KBytesPageOut: u64, NbOfRotateOut: u64, KBytesRotateOut: u64, }; pub const VIDEO_QUERY_PERFORMANCE_COUNTER = extern struct { BufferSize: u32, Buffer: ?*VIDEO_PERFORMANCE_COUNTER, }; pub const BRIGHTNESS_INTERFACE_VERSION = enum(i32) { @"1" = 1, @"2" = 2, @"3" = 3, }; pub const BRIGHTNESS_INTERFACE_VERSION_1 = BRIGHTNESS_INTERFACE_VERSION.@"1"; pub const BRIGHTNESS_INTERFACE_VERSION_2 = BRIGHTNESS_INTERFACE_VERSION.@"2"; pub const BRIGHTNESS_INTERFACE_VERSION_3 = BRIGHTNESS_INTERFACE_VERSION.@"3"; pub const PANEL_QUERY_BRIGHTNESS_CAPS = extern struct { Version: BRIGHTNESS_INTERFACE_VERSION, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, Value: u32, }, }; pub const BRIGHTNESS_LEVEL = extern struct { Count: u8, Level: [103]u8, }; pub const BRIGHTNESS_NIT_RANGE = extern struct { MinLevelInMillinit: u32, MaxLevelInMillinit: u32, StepSizeInMillinit: u32, }; pub const BRIGHTNESS_NIT_RANGES = extern struct { NormalRangeCount: u32, RangeCount: u32, PreferredMaximumBrightness: u32, SupportedRanges: [16]BRIGHTNESS_NIT_RANGE, }; pub const PANEL_QUERY_BRIGHTNESS_RANGES = extern struct { Version: BRIGHTNESS_INTERFACE_VERSION, Anonymous: extern union { BrightnessLevel: BRIGHTNESS_LEVEL, NitRanges: BRIGHTNESS_NIT_RANGES, }, }; pub const PANEL_GET_BRIGHTNESS = extern struct { Version: BRIGHTNESS_INTERFACE_VERSION, Anonymous: extern union { Level: u8, Anonymous: extern struct { CurrentInMillinits: u32, TargetInMillinits: u32, }, }, }; pub const CHROMATICITY_COORDINATE = extern struct { x: f32, y: f32, }; pub const PANEL_BRIGHTNESS_SENSOR_DATA = extern struct { Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, Value: u32, }, AlsReading: f32, ChromaticityCoordinate: CHROMATICITY_COORDINATE, ColorTemperature: f32, }; pub const PANEL_SET_BRIGHTNESS = extern struct { Version: BRIGHTNESS_INTERFACE_VERSION, Anonymous: extern union { Level: u8, Anonymous: extern struct { Millinits: u32, TransitionTimeInMs: u32, SensorData: PANEL_BRIGHTNESS_SENSOR_DATA, }, }, }; pub const PANEL_SET_BRIGHTNESS_STATE = extern struct { Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, Value: u32, }, }; pub const BACKLIGHT_OPTIMIZATION_LEVEL = enum(i32) { Disable = 0, Desktop = 1, Dynamic = 2, Dimmed = 3, EDR = 4, }; pub const BacklightOptimizationDisable = BACKLIGHT_OPTIMIZATION_LEVEL.Disable; pub const BacklightOptimizationDesktop = BACKLIGHT_OPTIMIZATION_LEVEL.Desktop; pub const BacklightOptimizationDynamic = BACKLIGHT_OPTIMIZATION_LEVEL.Dynamic; pub const BacklightOptimizationDimmed = BACKLIGHT_OPTIMIZATION_LEVEL.Dimmed; pub const BacklightOptimizationEDR = BACKLIGHT_OPTIMIZATION_LEVEL.EDR; pub const PANEL_SET_BACKLIGHT_OPTIMIZATION = extern struct { Level: BACKLIGHT_OPTIMIZATION_LEVEL, }; pub const BACKLIGHT_REDUCTION_GAMMA_RAMP = extern struct { R: [256]u16, G: [256]u16, B: [256]u16, }; pub const PANEL_GET_BACKLIGHT_REDUCTION = extern struct { BacklightUsersetting: u16, BacklightEffective: u16, GammaRamp: BACKLIGHT_REDUCTION_GAMMA_RAMP, }; pub const COLORSPACE_TRANSFORM_DATA_TYPE = enum(i32) { IXED_POINT = 0, LOAT = 1, }; pub const COLORSPACE_TRANSFORM_DATA_TYPE_FIXED_POINT = COLORSPACE_TRANSFORM_DATA_TYPE.IXED_POINT; pub const COLORSPACE_TRANSFORM_DATA_TYPE_FLOAT = COLORSPACE_TRANSFORM_DATA_TYPE.LOAT; pub const COLORSPACE_TRANSFORM_DATA_CAP = extern struct { DataType: COLORSPACE_TRANSFORM_DATA_TYPE, Anonymous: extern union { Anonymous1: extern struct { _bitfield: u32, }, Anonymous2: extern struct { _bitfield: u32, }, Value: u32, }, NumericRangeMin: f32, NumericRangeMax: f32, }; pub const COLORSPACE_TRANSFORM_1DLUT_CAP = extern struct { NumberOfLUTEntries: u32, DataCap: COLORSPACE_TRANSFORM_DATA_CAP, }; pub const COLORSPACE_TRANSFORM_MATRIX_CAP = extern struct { Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, Value: u32, }, DataCap: COLORSPACE_TRANSFORM_DATA_CAP, }; pub const COLORSPACE_TRANSFORM_TARGET_CAPS_VERSION = enum(i32) { DEFAULT = 0, @"1" = 1, // NOT_SUPPORTED = 0, this enum value conflicts with DEFAULT }; pub const COLORSPACE_TRANSFORM_VERSION_DEFAULT = COLORSPACE_TRANSFORM_TARGET_CAPS_VERSION.DEFAULT; pub const COLORSPACE_TRANSFORM_VERSION_1 = COLORSPACE_TRANSFORM_TARGET_CAPS_VERSION.@"1"; pub const COLORSPACE_TRANSFORM_VERSION_NOT_SUPPORTED = COLORSPACE_TRANSFORM_TARGET_CAPS_VERSION.DEFAULT; pub const COLORSPACE_TRANSFORM_TARGET_CAPS = extern struct { Version: COLORSPACE_TRANSFORM_TARGET_CAPS_VERSION, LookupTable1DDegammaCap: COLORSPACE_TRANSFORM_1DLUT_CAP, ColorMatrix3x3Cap: COLORSPACE_TRANSFORM_MATRIX_CAP, LookupTable1DRegammaCap: COLORSPACE_TRANSFORM_1DLUT_CAP, }; pub const COLORSPACE_TRANSFORM_TYPE = enum(i32) { UNINITIALIZED = 0, DEFAULT = 1, RGB256x3x16 = 2, DXGI_1 = 3, MATRIX_3x4 = 4, MATRIX_V2 = 5, }; pub const COLORSPACE_TRANSFORM_TYPE_UNINITIALIZED = COLORSPACE_TRANSFORM_TYPE.UNINITIALIZED; pub const COLORSPACE_TRANSFORM_TYPE_DEFAULT = COLORSPACE_TRANSFORM_TYPE.DEFAULT; pub const COLORSPACE_TRANSFORM_TYPE_RGB256x3x16 = COLORSPACE_TRANSFORM_TYPE.RGB256x3x16; pub const COLORSPACE_TRANSFORM_TYPE_DXGI_1 = COLORSPACE_TRANSFORM_TYPE.DXGI_1; pub const COLORSPACE_TRANSFORM_TYPE_MATRIX_3x4 = COLORSPACE_TRANSFORM_TYPE.MATRIX_3x4; pub const COLORSPACE_TRANSFORM_TYPE_MATRIX_V2 = COLORSPACE_TRANSFORM_TYPE.MATRIX_V2; pub const GAMMA_RAMP_RGB256x3x16 = extern struct { Red: [256]u16, Green: [256]u16, Blue: [256]u16, }; pub const GAMMA_RAMP_RGB = extern struct { Red: f32, Green: f32, Blue: f32, }; pub const GAMMA_RAMP_DXGI_1 = extern struct { Scale: GAMMA_RAMP_RGB, Offset: GAMMA_RAMP_RGB, GammaCurve: [1025]GAMMA_RAMP_RGB, }; pub const COLORSPACE_TRANSFORM_3x4 = extern struct { ColorMatrix3x4: [12]f32, ScalarMultiplier: f32, LookupTable1D: [4096]GAMMA_RAMP_RGB, }; pub const OUTPUT_WIRE_COLOR_SPACE_TYPE = enum(i32) { G22_P709 = 0, RESERVED = 4, G2084_P2020 = 12, G22_P709_WCG = 30, G22_P2020 = 31, G2084_P2020_HDR10PLUS = 32, G2084_P2020_DVLL = 33, }; pub const OUTPUT_WIRE_COLOR_SPACE_G22_P709 = OUTPUT_WIRE_COLOR_SPACE_TYPE.G22_P709; pub const OUTPUT_WIRE_COLOR_SPACE_RESERVED = OUTPUT_WIRE_COLOR_SPACE_TYPE.RESERVED; pub const OUTPUT_WIRE_COLOR_SPACE_G2084_P2020 = OUTPUT_WIRE_COLOR_SPACE_TYPE.G2084_P2020; pub const OUTPUT_WIRE_COLOR_SPACE_G22_P709_WCG = OUTPUT_WIRE_COLOR_SPACE_TYPE.G22_P709_WCG; pub const OUTPUT_WIRE_COLOR_SPACE_G22_P2020 = OUTPUT_WIRE_COLOR_SPACE_TYPE.G22_P2020; pub const OUTPUT_WIRE_COLOR_SPACE_G2084_P2020_HDR10PLUS = OUTPUT_WIRE_COLOR_SPACE_TYPE.G2084_P2020_HDR10PLUS; pub const OUTPUT_WIRE_COLOR_SPACE_G2084_P2020_DVLL = OUTPUT_WIRE_COLOR_SPACE_TYPE.G2084_P2020_DVLL; pub const OUTPUT_COLOR_ENCODING = enum(i32) { RGB = 0, YCBCR444 = 1, YCBCR422 = 2, YCBCR420 = 3, INTENSITY = 4, FORCE_UINT32 = -1, }; pub const OUTPUT_COLOR_ENCODING_RGB = OUTPUT_COLOR_ENCODING.RGB; pub const OUTPUT_COLOR_ENCODING_YCBCR444 = OUTPUT_COLOR_ENCODING.YCBCR444; pub const OUTPUT_COLOR_ENCODING_YCBCR422 = OUTPUT_COLOR_ENCODING.YCBCR422; pub const OUTPUT_COLOR_ENCODING_YCBCR420 = OUTPUT_COLOR_ENCODING.YCBCR420; pub const OUTPUT_COLOR_ENCODING_INTENSITY = OUTPUT_COLOR_ENCODING.INTENSITY; pub const OUTPUT_COLOR_ENCODING_FORCE_UINT32 = OUTPUT_COLOR_ENCODING.FORCE_UINT32; pub const OUTPUT_WIRE_FORMAT = extern struct { ColorEncoding: OUTPUT_COLOR_ENCODING, BitsPerPixel: u32, }; pub const COLORSPACE_TRANSFORM_STAGE_CONTROL = enum(i32) { No_Change = 0, Enable = 1, Bypass = 2, }; pub const ColorSpaceTransformStageControl_No_Change = COLORSPACE_TRANSFORM_STAGE_CONTROL.No_Change; pub const ColorSpaceTransformStageControl_Enable = COLORSPACE_TRANSFORM_STAGE_CONTROL.Enable; pub const ColorSpaceTransformStageControl_Bypass = COLORSPACE_TRANSFORM_STAGE_CONTROL.Bypass; pub const COLORSPACE_TRANSFORM_MATRIX_V2 = extern struct { StageControlLookupTable1DDegamma: COLORSPACE_TRANSFORM_STAGE_CONTROL, LookupTable1DDegamma: [4096]GAMMA_RAMP_RGB, StageControlColorMatrix3x3: COLORSPACE_TRANSFORM_STAGE_CONTROL, ColorMatrix3x3: [9]f32, StageControlLookupTable1DRegamma: COLORSPACE_TRANSFORM_STAGE_CONTROL, LookupTable1DRegamma: [4096]GAMMA_RAMP_RGB, }; pub const COLORSPACE_TRANSFORM = extern struct { Type: COLORSPACE_TRANSFORM_TYPE, Data: extern union { Rgb256x3x16: GAMMA_RAMP_RGB256x3x16, Dxgi1: GAMMA_RAMP_DXGI_1, T3x4: COLORSPACE_TRANSFORM_3x4, MatrixV2: COLORSPACE_TRANSFORM_MATRIX_V2, }, }; pub const COLORSPACE_TRANSFORM_SET_INPUT = extern struct { OutputWireColorSpaceExpected: OUTPUT_WIRE_COLOR_SPACE_TYPE, OutputWireFormatExpected: OUTPUT_WIRE_FORMAT, ColorSpaceTransform: COLORSPACE_TRANSFORM, }; pub const SET_ACTIVE_COLOR_PROFILE_NAME = extern struct { ColorProfileName: [1]u16, }; pub const MIPI_DSI_CAPS = extern struct { DSITypeMajor: u8, DSITypeMinor: u8, SpecVersionMajor: u8, SpecVersionMinor: u8, SpecVersionPatch: u8, TargetMaximumReturnPacketSize: u16, ResultCodeFlags: u8, ResultCodeStatus: u8, Revision: u8, Level: u8, DeviceClassHi: u8, DeviceClassLo: u8, ManufacturerHi: u8, ManufacturerLo: u8, ProductHi: u8, ProductLo: u8, LengthHi: u8, LengthLo: u8, }; pub const DSI_CONTROL_TRANSMISSION_MODE = enum(i32) { DEFAULT = 0, FORCE_LOW_POWER = 1, FORCE_HIGH_PERFORMANCE = 2, }; pub const DCT_DEFAULT = DSI_CONTROL_TRANSMISSION_MODE.DEFAULT; pub const DCT_FORCE_LOW_POWER = DSI_CONTROL_TRANSMISSION_MODE.FORCE_LOW_POWER; pub const DCT_FORCE_HIGH_PERFORMANCE = DSI_CONTROL_TRANSMISSION_MODE.FORCE_HIGH_PERFORMANCE; pub const MIPI_DSI_PACKET = extern struct { Anonymous1: extern union { DataId: u8, Anonymous: extern struct { _bitfield: u8, }, }, Anonymous2: extern union { Anonymous: extern struct { Data0: u8, Data1: u8, }, LongWriteWordCount: u16, }, EccFiller: u8, Payload: [8]u8, }; pub const MIPI_DSI_TRANSMISSION = extern struct { TotalBufferSize: u32, PacketCount: u8, FailedPacket: u8, Anonymous: extern struct { _bitfield: u16, }, ReadWordCount: u16, FinalCommandExtraPayload: u16, MipiErrors: u16, HostErrors: u16, Packets: [1]MIPI_DSI_PACKET, }; pub const MIPI_DSI_RESET = extern struct { Flags: u32, Anonymous: extern union { Anonymous: extern struct { _bitfield: u32, }, Results: u32, }, }; pub const AR_STATE = enum(i32) { ENABLED = 0, DISABLED = 1, SUPPRESSED = 2, REMOTESESSION = 4, MULTIMON = 8, NOSENSOR = 16, NOT_SUPPORTED = 32, DOCKED = 64, LAPTOP = 128, }; pub const AR_ENABLED = AR_STATE.ENABLED; pub const AR_DISABLED = AR_STATE.DISABLED; pub const AR_SUPPRESSED = AR_STATE.SUPPRESSED; pub const AR_REMOTESESSION = AR_STATE.REMOTESESSION; pub const AR_MULTIMON = AR_STATE.MULTIMON; pub const AR_NOSENSOR = AR_STATE.NOSENSOR; pub const AR_NOT_SUPPORTED = AR_STATE.NOT_SUPPORTED; pub const AR_DOCKED = AR_STATE.DOCKED; pub const AR_LAPTOP = AR_STATE.LAPTOP; pub const ORIENTATION_PREFERENCE = enum(i32) { NONE = 0, LANDSCAPE = 1, PORTRAIT = 2, LANDSCAPE_FLIPPED = 4, PORTRAIT_FLIPPED = 8, }; pub const ORIENTATION_PREFERENCE_NONE = ORIENTATION_PREFERENCE.NONE; pub const ORIENTATION_PREFERENCE_LANDSCAPE = ORIENTATION_PREFERENCE.LANDSCAPE; pub const ORIENTATION_PREFERENCE_PORTRAIT = ORIENTATION_PREFERENCE.PORTRAIT; pub const ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED = ORIENTATION_PREFERENCE.LANDSCAPE_FLIPPED; pub const ORIENTATION_PREFERENCE_PORTRAIT_FLIPPED = ORIENTATION_PREFERENCE.PORTRAIT_FLIPPED; pub const POINTE = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { x: f32, y: f32, }, .X86 => extern struct { x: u32, y: u32, }, }; pub const FLOAT_LONG = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern union { e: f32, l: i32, }, .X86 => extern union { e: u32, l: i32, }, }; pub const FD_XFORM = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { eXX: f32, eXY: f32, eYX: f32, eYY: f32, }, .X86 => extern struct { eXX: u32, eXY: u32, eYX: u32, eYY: u32, }, }; pub const IFIMETRICS = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { cjThis: u32, cjIfiExtra: u32, dpwszFamilyName: i32, dpwszStyleName: i32, dpwszFaceName: i32, dpwszUniqueName: i32, dpFontSim: i32, lEmbedId: i32, lItalicAngle: i32, lCharBias: i32, dpCharSets: i32, jWinCharSet: u8, jWinPitchAndFamily: u8, usWinWeight: u16, flInfo: u32, fsSelection: u16, fsType: u16, fwdUnitsPerEm: i16, fwdLowestPPEm: i16, fwdWinAscender: i16, fwdWinDescender: i16, fwdMacAscender: i16, fwdMacDescender: i16, fwdMacLineGap: i16, fwdTypoAscender: i16, fwdTypoDescender: i16, fwdTypoLineGap: i16, fwdAveCharWidth: i16, fwdMaxCharInc: i16, fwdCapHeight: i16, fwdXHeight: i16, fwdSubscriptXSize: i16, fwdSubscriptYSize: i16, fwdSubscriptXOffset: i16, fwdSubscriptYOffset: i16, fwdSuperscriptXSize: i16, fwdSuperscriptYSize: i16, fwdSuperscriptXOffset: i16, fwdSuperscriptYOffset: i16, fwdUnderscoreSize: i16, fwdUnderscorePosition: i16, fwdStrikeoutSize: i16, fwdStrikeoutPosition: i16, chFirstChar: u8, chLastChar: u8, chDefaultChar: u8, chBreakChar: u8, wcFirstChar: u16, wcLastChar: u16, wcDefaultChar: u16, wcBreakChar: u16, ptlBaseline: POINTL, ptlAspect: POINTL, ptlCaret: POINTL, rclFontBox: RECTL, achVendId: [4]u8, cKerningPairs: u32, ulPanoseCulture: u32, panose: PANOSE, Align: ?*anyopaque, }, .X86 => extern struct { cjThis: u32, cjIfiExtra: u32, dpwszFamilyName: i32, dpwszStyleName: i32, dpwszFaceName: i32, dpwszUniqueName: i32, dpFontSim: i32, lEmbedId: i32, lItalicAngle: i32, lCharBias: i32, dpCharSets: i32, jWinCharSet: u8, jWinPitchAndFamily: u8, usWinWeight: u16, flInfo: u32, fsSelection: u16, fsType: u16, fwdUnitsPerEm: i16, fwdLowestPPEm: i16, fwdWinAscender: i16, fwdWinDescender: i16, fwdMacAscender: i16, fwdMacDescender: i16, fwdMacLineGap: i16, fwdTypoAscender: i16, fwdTypoDescender: i16, fwdTypoLineGap: i16, fwdAveCharWidth: i16, fwdMaxCharInc: i16, fwdCapHeight: i16, fwdXHeight: i16, fwdSubscriptXSize: i16, fwdSubscriptYSize: i16, fwdSubscriptXOffset: i16, fwdSubscriptYOffset: i16, fwdSuperscriptXSize: i16, fwdSuperscriptYSize: i16, fwdSuperscriptXOffset: i16, fwdSuperscriptYOffset: i16, fwdUnderscoreSize: i16, fwdUnderscorePosition: i16, fwdStrikeoutSize: i16, fwdStrikeoutPosition: i16, chFirstChar: u8, chLastChar: u8, chDefaultChar: u8, chBreakChar: u8, wcFirstChar: u16, wcLastChar: u16, wcDefaultChar: u16, wcBreakChar: u16, ptlBaseline: POINTL, ptlAspect: POINTL, ptlCaret: POINTL, rclFontBox: RECTL, achVendId: [4]u8, cKerningPairs: u32, ulPanoseCulture: u32, panose: PANOSE, }, }; pub const LINEATTRS = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { fl: u32, iJoin: u32, iEndCap: u32, elWidth: FLOAT_LONG, eMiterLimit: f32, cstyle: u32, pstyle: ?*FLOAT_LONG, elStyleState: FLOAT_LONG, }, .X86 => extern struct { fl: u32, iJoin: u32, iEndCap: u32, elWidth: FLOAT_LONG, eMiterLimit: u32, cstyle: u32, pstyle: ?*FLOAT_LONG, elStyleState: FLOAT_LONG, }, }; pub const XFORML = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { eM11: f32, eM12: f32, eM21: f32, eM22: f32, eDx: f32, eDy: f32, }, .X86 => extern struct { eM11: u32, eM12: u32, eM21: u32, eM22: u32, eDx: u32, eDy: u32, }, }; pub const FLOATOBJ_XFORM = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { eM11: f32, eM12: f32, eM21: f32, eM22: f32, eDx: f32, eDy: f32, }, .X86 => extern struct { eM11: FLOATOBJ, eM12: FLOATOBJ, eM21: FLOATOBJ, eM22: FLOATOBJ, eDx: FLOATOBJ, eDy: FLOATOBJ, }, }; pub const FLOATOBJ = switch(@import("../zig.zig").arch) { .X86 => extern struct { ul1: u32, ul2: u32, }, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; //-------------------------------------------------------------------------------- // Section: Functions (119) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetNumberOfPhysicalMonitorsFromHMONITOR( hMonitor: ?HMONITOR, pdwNumberOfPhysicalMonitors: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetNumberOfPhysicalMonitorsFromIDirect3DDevice9( pDirect3DDevice9: ?*IDirect3DDevice9, pdwNumberOfPhysicalMonitors: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetPhysicalMonitorsFromHMONITOR( hMonitor: ?HMONITOR, dwPhysicalMonitorArraySize: u32, pPhysicalMonitorArray: [*]PHYSICAL_MONITOR, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetPhysicalMonitorsFromIDirect3DDevice9( pDirect3DDevice9: ?*IDirect3DDevice9, dwPhysicalMonitorArraySize: u32, pPhysicalMonitorArray: [*]PHYSICAL_MONITOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn DestroyPhysicalMonitor( hMonitor: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn DestroyPhysicalMonitors( dwPhysicalMonitorArraySize: u32, pPhysicalMonitorArray: [*]PHYSICAL_MONITOR, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetVCPFeatureAndVCPFeatureReply( hMonitor: ?HANDLE, bVCPCode: u8, pvct: ?*MC_VCP_CODE_TYPE, pdwCurrentValue: ?*u32, pdwMaximumValue: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SetVCPFeature( hMonitor: ?HANDLE, bVCPCode: u8, dwNewValue: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SaveCurrentSettings( hMonitor: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetCapabilitiesStringLength( hMonitor: ?HANDLE, pdwCapabilitiesStringLengthInCharacters: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn CapabilitiesRequestAndCapabilitiesReply( hMonitor: ?HANDLE, pszASCIICapabilitiesString: [*:0]u8, dwCapabilitiesStringLengthInCharacters: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetTimingReport( hMonitor: ?HANDLE, pmtrMonitorTimingReport: ?*MC_TIMING_REPORT, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorCapabilities( hMonitor: ?HANDLE, pdwMonitorCapabilities: ?*u32, pdwSupportedColorTemperatures: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SaveCurrentMonitorSettings( hMonitor: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorTechnologyType( hMonitor: ?HANDLE, pdtyDisplayTechnologyType: ?*MC_DISPLAY_TECHNOLOGY_TYPE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorBrightness( hMonitor: ?HANDLE, pdwMinimumBrightness: ?*u32, pdwCurrentBrightness: ?*u32, pdwMaximumBrightness: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorContrast( hMonitor: ?HANDLE, pdwMinimumContrast: ?*u32, pdwCurrentContrast: ?*u32, pdwMaximumContrast: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorColorTemperature( hMonitor: ?HANDLE, pctCurrentColorTemperature: ?*MC_COLOR_TEMPERATURE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorRedGreenOrBlueDrive( hMonitor: ?HANDLE, dtDriveType: MC_DRIVE_TYPE, pdwMinimumDrive: ?*u32, pdwCurrentDrive: ?*u32, pdwMaximumDrive: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorRedGreenOrBlueGain( hMonitor: ?HANDLE, gtGainType: MC_GAIN_TYPE, pdwMinimumGain: ?*u32, pdwCurrentGain: ?*u32, pdwMaximumGain: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SetMonitorBrightness( hMonitor: ?HANDLE, dwNewBrightness: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SetMonitorContrast( hMonitor: ?HANDLE, dwNewContrast: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SetMonitorColorTemperature( hMonitor: ?HANDLE, ctCurrentColorTemperature: MC_COLOR_TEMPERATURE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SetMonitorRedGreenOrBlueDrive( hMonitor: ?HANDLE, dtDriveType: MC_DRIVE_TYPE, dwNewDrive: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SetMonitorRedGreenOrBlueGain( hMonitor: ?HANDLE, gtGainType: MC_GAIN_TYPE, dwNewGain: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn DegaussMonitor( hMonitor: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorDisplayAreaSize( hMonitor: ?HANDLE, stSizeType: MC_SIZE_TYPE, pdwMinimumWidthOrHeight: ?*u32, pdwCurrentWidthOrHeight: ?*u32, pdwMaximumWidthOrHeight: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn GetMonitorDisplayAreaPosition( hMonitor: ?HANDLE, ptPositionType: MC_POSITION_TYPE, pdwMinimumPosition: ?*u32, pdwCurrentPosition: ?*u32, pdwMaximumPosition: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SetMonitorDisplayAreaSize( hMonitor: ?HANDLE, stSizeType: MC_SIZE_TYPE, dwNewDisplayAreaWidthOrHeight: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn SetMonitorDisplayAreaPosition( hMonitor: ?HANDLE, ptPositionType: MC_POSITION_TYPE, dwNewPosition: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn RestoreMonitorFactoryColorDefaults( hMonitor: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dxva2" fn RestoreMonitorFactoryDefaults( hMonitor: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn BRUSHOBJ_pvAllocRbrush( pbo: ?*BRUSHOBJ, cj: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn BRUSHOBJ_pvGetRbrush( pbo: ?*BRUSHOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn BRUSHOBJ_ulGetBrushColor( pbo: ?*BRUSHOBJ, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn BRUSHOBJ_hGetColorTransform( pbo: ?*BRUSHOBJ, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CLIPOBJ_cEnumStart( pco: ?*CLIPOBJ, bAll: BOOL, iType: u32, iDirection: u32, cLimit: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CLIPOBJ_bEnum( pco: ?*CLIPOBJ, cj: u32, pul: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn CLIPOBJ_ppoGetPath( pco: ?*CLIPOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*PATHOBJ; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_cGetAllGlyphHandles( pfo: ?*FONTOBJ, phg: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_vGetInfo( pfo: ?*FONTOBJ, cjSize: u32, pfi: ?*FONTINFO, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_cGetGlyphs( pfo: ?*FONTOBJ, iMode: u32, cGlyph: u32, phg: ?*u32, ppvGlyph: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pxoGetXform( pfo: ?*FONTOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*XFORMOBJ; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pifi( pfo: ?*FONTOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*IFIMETRICS; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pfdg( pfo: ?*FONTOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*FD_GLYPHSET; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pvTrueTypeFontFile( pfo: ?*FONTOBJ, pcjFile: ?*u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn FONTOBJ_pQueryGlyphAttrs( pfo: ?*FONTOBJ, iMode: u32, ) callconv(@import("std").os.windows.WINAPI) ?*FD_GLYPHATTR; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_vEnumStart( ppo: ?*PATHOBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_bEnum( ppo: ?*PATHOBJ, ppd: ?*PATHDATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_vEnumStartClipLines( ppo: ?*PATHOBJ, pco: ?*CLIPOBJ, pso: ?*SURFOBJ, pla: ?*LINEATTRS, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_bEnumClipLines( ppo: ?*PATHOBJ, cb: u32, pcl: ?*CLIPLINE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn PATHOBJ_vGetBounds( ppo: ?*PATHOBJ, prectfx: ?*RECTFX, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_vEnumStart( pstro: ?*STROBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_bEnum( pstro: ?*STROBJ, pc: ?*u32, ppgpos: ?*?*GLYPHPOS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_bEnumPositionsOnly( pstro: ?*STROBJ, pc: ?*u32, ppgpos: ?*?*GLYPHPOS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_dwGetCodePage( pstro: ?*STROBJ, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn STROBJ_bGetAdvanceWidths( pso: ?*STROBJ, iFirst: u32, c: u32, pptqD: ?*POINTQF, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XFORMOBJ_iGetXform( pxo: ?*XFORMOBJ, pxform: ?*XFORML, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XFORMOBJ_bApplyXform( pxo: ?*XFORMOBJ, iMode: u32, cPoints: u32, pvIn: ?*anyopaque, pvOut: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XLATEOBJ_iXlate( pxlo: ?*XLATEOBJ, iColor: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XLATEOBJ_piVector( pxlo: ?*XLATEOBJ, ) callconv(@import("std").os.windows.WINAPI) ?*u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XLATEOBJ_cGetPalette( pxlo: ?*XLATEOBJ, iPal: u32, cPal: u32, pPal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn XLATEOBJ_hGetColorTransform( pxlo: ?*XLATEOBJ, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateBitmap( sizl: SIZE, lWidth: i32, iFormat: u32, fl: u32, pvBits: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?HBITMAP; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateDeviceSurface( dhsurf: DHSURF, sizl: SIZE, iFormatCompat: u32, ) callconv(@import("std").os.windows.WINAPI) ?HSURF; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateDeviceBitmap( dhsurf: DHSURF, sizl: SIZE, iFormatCompat: u32, ) callconv(@import("std").os.windows.WINAPI) ?HBITMAP; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeleteSurface( hsurf: ?HSURF, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngLockSurface( hsurf: ?HSURF, ) callconv(@import("std").os.windows.WINAPI) ?*SURFOBJ; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngUnlockSurface( pso: ?*SURFOBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngEraseSurface( pso: ?*SURFOBJ, prcl: ?*RECTL, iColor: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngAssociateSurface( hsurf: ?HSURF, hdev: ?HDEV, flHooks: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngMarkBandingSurface( hsurf: ?HSURF, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCheckAbort( pso: ?*SURFOBJ, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeletePath( ppo: ?*PATHOBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreatePalette( iMode: u32, cColors: u32, pulColors: ?*u32, flRed: u32, flGreen: u32, flBlue: u32, ) callconv(@import("std").os.windows.WINAPI) ?HPALETTE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeletePalette( hpal: ?HPALETTE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateClip( ) callconv(@import("std").os.windows.WINAPI) ?*CLIPOBJ; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeleteClip( pco: ?*CLIPOBJ, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngBitBlt( psoTrg: ?*SURFOBJ, psoSrc: ?*SURFOBJ, psoMask: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, prclTrg: ?*RECTL, pptlSrc: ?*POINTL, pptlMask: ?*POINTL, pbo: ?*BRUSHOBJ, pptlBrush: ?*POINTL, rop4: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngLineTo( pso: ?*SURFOBJ, pco: ?*CLIPOBJ, pbo: ?*BRUSHOBJ, x1: i32, y1: i32, x2: i32, y2: i32, prclBounds: ?*RECTL, mix: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngStretchBlt( psoDest: ?*SURFOBJ, psoSrc: ?*SURFOBJ, psoMask: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, pca: ?*COLORADJUSTMENT, pptlHTOrg: ?*POINTL, prclDest: ?*RECTL, prclSrc: ?*RECTL, pptlMask: ?*POINTL, iMode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngStretchBltROP( psoDest: ?*SURFOBJ, psoSrc: ?*SURFOBJ, psoMask: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, pca: ?*COLORADJUSTMENT, pptlHTOrg: ?*POINTL, prclDest: ?*RECTL, prclSrc: ?*RECTL, pptlMask: ?*POINTL, iMode: u32, pbo: ?*BRUSHOBJ, rop4: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngAlphaBlend( psoDest: ?*SURFOBJ, psoSrc: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, prclDest: ?*RECTL, prclSrc: ?*RECTL, pBlendObj: ?*BLENDOBJ, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngGradientFill( psoDest: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, pVertex: ?*TRIVERTEX, nVertex: u32, pMesh: ?*anyopaque, nMesh: u32, prclExtents: ?*RECTL, pptlDitherOrg: ?*POINTL, ulMode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngTransparentBlt( psoDst: ?*SURFOBJ, psoSrc: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, prclDst: ?*RECTL, prclSrc: ?*RECTL, TransColor: u32, bCalledFromBitBlt: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngTextOut( pso: ?*SURFOBJ, pstro: ?*STROBJ, pfo: ?*FONTOBJ, pco: ?*CLIPOBJ, prclExtra: ?*RECTL, prclOpaque: ?*RECTL, pboFore: ?*BRUSHOBJ, pboOpaque: ?*BRUSHOBJ, pptlOrg: ?*POINTL, mix: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngStrokePath( pso: ?*SURFOBJ, ppo: ?*PATHOBJ, pco: ?*CLIPOBJ, pxo: ?*XFORMOBJ, pbo: ?*BRUSHOBJ, pptlBrushOrg: ?*POINTL, plineattrs: ?*LINEATTRS, mix: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngFillPath( pso: ?*SURFOBJ, ppo: ?*PATHOBJ, pco: ?*CLIPOBJ, pbo: ?*BRUSHOBJ, pptlBrushOrg: ?*POINTL, mix: u32, flOptions: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngStrokeAndFillPath( pso: ?*SURFOBJ, ppo: ?*PATHOBJ, pco: ?*CLIPOBJ, pxo: ?*XFORMOBJ, pboStroke: ?*BRUSHOBJ, plineattrs: ?*LINEATTRS, pboFill: ?*BRUSHOBJ, pptlBrushOrg: ?*POINTL, mixFill: u32, flOptions: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngPaint( pso: ?*SURFOBJ, pco: ?*CLIPOBJ, pbo: ?*BRUSHOBJ, pptlBrushOrg: ?*POINTL, mix: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCopyBits( psoDest: ?*SURFOBJ, psoSrc: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, prclDest: ?*RECTL, pptlSrc: ?*POINTL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngPlgBlt( psoTrg: ?*SURFOBJ, psoSrc: ?*SURFOBJ, psoMsk: ?*SURFOBJ, pco: ?*CLIPOBJ, pxlo: ?*XLATEOBJ, pca: ?*COLORADJUSTMENT, pptlBrushOrg: ?*POINTL, pptfx: ?*POINTFIX, prcl: ?*RECTL, pptl: ?*POINTL, iMode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn HT_Get8BPPFormatPalette( pPaletteEntry: ?*PALETTEENTRY, RedGamma: u16, GreenGamma: u16, BlueGamma: u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn HT_Get8BPPMaskPalette( pPaletteEntry: ?*PALETTEENTRY, Use8BPPMaskPal: BOOL, CMYMask: u8, RedGamma: u16, GreenGamma: u16, BlueGamma: u16, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngGetPrinterDataFileName( hdev: ?HDEV, ) callconv(@import("std").os.windows.WINAPI) ?PWSTR; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngGetDriverName( hdev: ?HDEV, ) callconv(@import("std").os.windows.WINAPI) ?PWSTR; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngLoadModule( pwsz: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngFindResource( h: ?HANDLE, iName: i32, iType: i32, pulSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngFreeModule( h: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngCreateSemaphore( ) callconv(@import("std").os.windows.WINAPI) ?HSEMAPHORE; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngAcquireSemaphore( hsem: ?HSEMAPHORE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngReleaseSemaphore( hsem: ?HSEMAPHORE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngDeleteSemaphore( hsem: ?HSEMAPHORE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngMultiByteToUnicodeN( // TODO: what to do with BytesParamIndex 1? UnicodeString: ?PWSTR, MaxBytesInUnicodeString: u32, BytesInUnicodeString: ?*u32, // TODO: what to do with BytesParamIndex 4? MultiByteString: ?[*]u8, BytesInMultiByteString: u32, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngUnicodeToMultiByteN( // TODO: what to do with BytesParamIndex 1? MultiByteString: ?[*]u8, MaxBytesInMultiByteString: u32, BytesInMultiByteString: ?*u32, // TODO: what to do with BytesParamIndex 4? UnicodeString: ?PWSTR, BytesInUnicodeString: u32, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngQueryLocalTime( param0: ?*ENG_TIME_FIELDS, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngComputeGlyphSet( nCodePage: i32, nFirstChar: i32, cChars: i32, ) callconv(@import("std").os.windows.WINAPI) ?*FD_GLYPHSET; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngMultiByteToWideChar( CodePage: u32, // TODO: what to do with BytesParamIndex 2? WideCharString: ?PWSTR, BytesInWideCharString: i32, // TODO: what to do with BytesParamIndex 4? MultiByteString: ?PSTR, BytesInMultiByteString: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngWideCharToMultiByte( CodePage: u32, // TODO: what to do with BytesParamIndex 2? WideCharString: ?PWSTR, BytesInWideCharString: i32, // TODO: what to do with BytesParamIndex 4? MultiByteString: ?PSTR, BytesInMultiByteString: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "GDI32" fn EngGetCurrentCodePage( OemCodePage: ?*u16, AnsiCodePage: ?*u16, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "GDI32" fn EngQueryEMFInfo( hdev: ?HDEV, pEMFInfo: ?*EMFINFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn GetDisplayConfigBufferSizes( flags: u32, numPathArrayElements: ?*u32, numModeInfoArrayElements: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn SetDisplayConfig( numPathArrayElements: u32, pathArray: ?[*]DISPLAYCONFIG_PATH_INFO, numModeInfoArrayElements: u32, modeInfoArray: ?[*]DISPLAYCONFIG_MODE_INFO, flags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn QueryDisplayConfig( flags: u32, numPathArrayElements: ?*u32, pathArray: [*]DISPLAYCONFIG_PATH_INFO, numModeInfoArrayElements: ?*u32, modeInfoArray: [*]DISPLAYCONFIG_MODE_INFO, currentTopologyId: ?*DISPLAYCONFIG_TOPOLOGY_ID, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn DisplayConfigGetDeviceInfo( requestPacket: ?*DISPLAYCONFIG_DEVICE_INFO_HEADER, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn DisplayConfigSetDeviceInfo( setPacket: ?*DISPLAYCONFIG_DEVICE_INFO_HEADER, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "USER32" fn GetAutoRotationState( pState: ?*AR_STATE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "USER32" fn GetDisplayAutoRotationPreferences( pOrientation: ?*ORIENTATION_PREFERENCE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "USER32" fn SetDisplayAutoRotationPreferences( orientation: ORIENTATION_PREFERENCE, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // 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 (45) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BLENDFUNCTION = @import("../graphics/gdi.zig").BLENDFUNCTION; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const CHAR = @import("../foundation.zig").CHAR; const CHAR_INFO = @import("../system/console.zig").CHAR_INFO; const COLORADJUSTMENT = @import("../graphics/gdi.zig").COLORADJUSTMENT; const COORD = @import("../system/console.zig").COORD; const DD_CALLBACKS = @import("../graphics/direct_draw.zig").DD_CALLBACKS; const DD_DIRECTDRAW_GLOBAL = @import("../graphics/direct_draw.zig").DD_DIRECTDRAW_GLOBAL; const DD_HALINFO = @import("../graphics/direct_draw.zig").DD_HALINFO; const DD_PALETTECALLBACKS = @import("../graphics/direct_draw.zig").DD_PALETTECALLBACKS; const DD_SURFACE_LOCAL = @import("../graphics/direct_draw.zig").DD_SURFACE_LOCAL; const DD_SURFACECALLBACKS = @import("../graphics/direct_draw.zig").DD_SURFACECALLBACKS; const DESIGNVECTOR = @import("../graphics/gdi.zig").DESIGNVECTOR; const DEVMODEW = @import("../graphics/gdi.zig").DEVMODEW; const DISPLAYCONFIG_COLOR_ENCODING = @import("../graphics/gdi.zig").DISPLAYCONFIG_COLOR_ENCODING; const HANDLE = @import("../foundation.zig").HANDLE; const HBITMAP = @import("../graphics/gdi.zig").HBITMAP; const HDC = @import("../graphics/gdi.zig").HDC; const HMONITOR = @import("../graphics/gdi.zig").HMONITOR; const HPALETTE = @import("../graphics/gdi.zig").HPALETTE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDirect3DDevice9 = @import("../graphics/direct3d9.zig").IDirect3DDevice9; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const LOGCOLORSPACEW = @import("../ui/color_system.zig").LOGCOLORSPACEW; const LOGFONTW = @import("../graphics/gdi.zig").LOGFONTW; const LUID = @import("../foundation.zig").LUID; const NTSTATUS = @import("../foundation.zig").NTSTATUS; const PALETTEENTRY = @import("../graphics/gdi.zig").PALETTEENTRY; const PANOSE = @import("../graphics/gdi.zig").PANOSE; const PIXELFORMATDESCRIPTOR = @import("../graphics/open_gl.zig").PIXELFORMATDESCRIPTOR; const POINTL = @import("../foundation.zig").POINTL; const PROPERTYKEY = @import("../ui/shell/properties_system.zig").PROPERTYKEY; 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 SIZE = @import("../foundation.zig").SIZE; const TRIVERTEX = @import("../graphics/gdi.zig").TRIVERTEX; const TTPOLYGONHEADER = @import("../graphics/gdi.zig").TTPOLYGONHEADER; const VIDEOMEMORY = @import("../graphics/direct_draw.zig").VIDEOMEMORY; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFN")) { _ = PFN; } if (@hasDecl(@This(), "WNDOBJCHANGEPROC")) { _ = WNDOBJCHANGEPROC; } if (@hasDecl(@This(), "SORTCOMP")) { _ = SORTCOMP; } if (@hasDecl(@This(), "PFN_DrvEnableDriver")) { _ = PFN_DrvEnableDriver; } if (@hasDecl(@This(), "PFN_DrvEnablePDEV")) { _ = PFN_DrvEnablePDEV; } if (@hasDecl(@This(), "PFN_DrvCompletePDEV")) { _ = PFN_DrvCompletePDEV; } if (@hasDecl(@This(), "PFN_DrvResetDevice")) { _ = PFN_DrvResetDevice; } if (@hasDecl(@This(), "PFN_DrvDisablePDEV")) { _ = PFN_DrvDisablePDEV; } if (@hasDecl(@This(), "PFN_DrvSynchronize")) { _ = PFN_DrvSynchronize; } if (@hasDecl(@This(), "PFN_DrvEnableSurface")) { _ = PFN_DrvEnableSurface; } if (@hasDecl(@This(), "PFN_DrvDisableDriver")) { _ = PFN_DrvDisableDriver; } if (@hasDecl(@This(), "PFN_DrvDisableSurface")) { _ = PFN_DrvDisableSurface; } if (@hasDecl(@This(), "PFN_DrvAssertMode")) { _ = PFN_DrvAssertMode; } if (@hasDecl(@This(), "PFN_DrvTextOut")) { _ = PFN_DrvTextOut; } if (@hasDecl(@This(), "PFN_DrvStretchBlt")) { _ = PFN_DrvStretchBlt; } if (@hasDecl(@This(), "PFN_DrvStretchBltROP")) { _ = PFN_DrvStretchBltROP; } if (@hasDecl(@This(), "PFN_DrvTransparentBlt")) { _ = PFN_DrvTransparentBlt; } if (@hasDecl(@This(), "PFN_DrvPlgBlt")) { _ = PFN_DrvPlgBlt; } if (@hasDecl(@This(), "PFN_DrvBitBlt")) { _ = PFN_DrvBitBlt; } if (@hasDecl(@This(), "PFN_DrvRealizeBrush")) { _ = PFN_DrvRealizeBrush; } if (@hasDecl(@This(), "PFN_DrvCopyBits")) { _ = PFN_DrvCopyBits; } if (@hasDecl(@This(), "PFN_DrvDitherColor")) { _ = PFN_DrvDitherColor; } if (@hasDecl(@This(), "PFN_DrvCreateDeviceBitmap")) { _ = PFN_DrvCreateDeviceBitmap; } if (@hasDecl(@This(), "PFN_DrvDeleteDeviceBitmap")) { _ = PFN_DrvDeleteDeviceBitmap; } if (@hasDecl(@This(), "PFN_DrvSetPalette")) { _ = PFN_DrvSetPalette; } if (@hasDecl(@This(), "PFN_DrvEscape")) { _ = PFN_DrvEscape; } if (@hasDecl(@This(), "PFN_DrvDrawEscape")) { _ = PFN_DrvDrawEscape; } if (@hasDecl(@This(), "PFN_DrvQueryFont")) { _ = PFN_DrvQueryFont; } if (@hasDecl(@This(), "PFN_DrvQueryFontTree")) { _ = PFN_DrvQueryFontTree; } if (@hasDecl(@This(), "PFN_DrvQueryFontData")) { _ = PFN_DrvQueryFontData; } if (@hasDecl(@This(), "PFN_DrvFree")) { _ = PFN_DrvFree; } if (@hasDecl(@This(), "PFN_DrvDestroyFont")) { _ = PFN_DrvDestroyFont; } if (@hasDecl(@This(), "PFN_DrvQueryFontCaps")) { _ = PFN_DrvQueryFontCaps; } if (@hasDecl(@This(), "PFN_DrvLoadFontFile")) { _ = PFN_DrvLoadFontFile; } if (@hasDecl(@This(), "PFN_DrvUnloadFontFile")) { _ = PFN_DrvUnloadFontFile; } if (@hasDecl(@This(), "PFN_DrvSetPointerShape")) { _ = PFN_DrvSetPointerShape; } if (@hasDecl(@This(), "PFN_DrvMovePointer")) { _ = PFN_DrvMovePointer; } if (@hasDecl(@This(), "PFN_DrvSendPage")) { _ = PFN_DrvSendPage; } if (@hasDecl(@This(), "PFN_DrvStartPage")) { _ = PFN_DrvStartPage; } if (@hasDecl(@This(), "PFN_DrvStartDoc")) { _ = PFN_DrvStartDoc; } if (@hasDecl(@This(), "PFN_DrvEndDoc")) { _ = PFN_DrvEndDoc; } if (@hasDecl(@This(), "PFN_DrvQuerySpoolType")) { _ = PFN_DrvQuerySpoolType; } if (@hasDecl(@This(), "PFN_DrvLineTo")) { _ = PFN_DrvLineTo; } if (@hasDecl(@This(), "PFN_DrvStrokePath")) { _ = PFN_DrvStrokePath; } if (@hasDecl(@This(), "PFN_DrvFillPath")) { _ = PFN_DrvFillPath; } if (@hasDecl(@This(), "PFN_DrvStrokeAndFillPath")) { _ = PFN_DrvStrokeAndFillPath; } if (@hasDecl(@This(), "PFN_DrvPaint")) { _ = PFN_DrvPaint; } if (@hasDecl(@This(), "PFN_DrvGetGlyphMode")) { _ = PFN_DrvGetGlyphMode; } if (@hasDecl(@This(), "PFN_DrvResetPDEV")) { _ = PFN_DrvResetPDEV; } if (@hasDecl(@This(), "PFN_DrvSaveScreenBits")) { _ = PFN_DrvSaveScreenBits; } if (@hasDecl(@This(), "PFN_DrvGetModes")) { _ = PFN_DrvGetModes; } if (@hasDecl(@This(), "PFN_DrvQueryTrueTypeTable")) { _ = PFN_DrvQueryTrueTypeTable; } if (@hasDecl(@This(), "PFN_DrvQueryTrueTypeSection")) { _ = PFN_DrvQueryTrueTypeSection; } if (@hasDecl(@This(), "PFN_DrvQueryTrueTypeOutline")) { _ = PFN_DrvQueryTrueTypeOutline; } if (@hasDecl(@This(), "PFN_DrvGetTrueTypeFile")) { _ = PFN_DrvGetTrueTypeFile; } if (@hasDecl(@This(), "PFN_DrvQueryFontFile")) { _ = PFN_DrvQueryFontFile; } if (@hasDecl(@This(), "PFN_DrvQueryGlyphAttrs")) { _ = PFN_DrvQueryGlyphAttrs; } if (@hasDecl(@This(), "PFN_DrvQueryAdvanceWidths")) { _ = PFN_DrvQueryAdvanceWidths; } if (@hasDecl(@This(), "PFN_DrvFontManagement")) { _ = PFN_DrvFontManagement; } if (@hasDecl(@This(), "PFN_DrvSetPixelFormat")) { _ = PFN_DrvSetPixelFormat; } if (@hasDecl(@This(), "PFN_DrvDescribePixelFormat")) { _ = PFN_DrvDescribePixelFormat; } if (@hasDecl(@This(), "PFN_DrvSwapBuffers")) { _ = PFN_DrvSwapBuffers; } if (@hasDecl(@This(), "PFN_DrvStartBanding")) { _ = PFN_DrvStartBanding; } if (@hasDecl(@This(), "PFN_DrvNextBand")) { _ = PFN_DrvNextBand; } if (@hasDecl(@This(), "PFN_DrvQueryPerBandInfo")) { _ = PFN_DrvQueryPerBandInfo; } if (@hasDecl(@This(), "PFN_DrvEnableDirectDraw")) { _ = PFN_DrvEnableDirectDraw; } if (@hasDecl(@This(), "PFN_DrvDisableDirectDraw")) { _ = PFN_DrvDisableDirectDraw; } if (@hasDecl(@This(), "PFN_DrvGetDirectDrawInfo")) { _ = PFN_DrvGetDirectDrawInfo; } if (@hasDecl(@This(), "PFN_DrvIcmCreateColorTransform")) { _ = PFN_DrvIcmCreateColorTransform; } if (@hasDecl(@This(), "PFN_DrvIcmDeleteColorTransform")) { _ = PFN_DrvIcmDeleteColorTransform; } if (@hasDecl(@This(), "PFN_DrvIcmCheckBitmapBits")) { _ = PFN_DrvIcmCheckBitmapBits; } if (@hasDecl(@This(), "PFN_DrvIcmSetDeviceGammaRamp")) { _ = PFN_DrvIcmSetDeviceGammaRamp; } if (@hasDecl(@This(), "PFN_DrvAlphaBlend")) { _ = PFN_DrvAlphaBlend; } if (@hasDecl(@This(), "PFN_DrvGradientFill")) { _ = PFN_DrvGradientFill; } if (@hasDecl(@This(), "PFN_DrvQueryDeviceSupport")) { _ = PFN_DrvQueryDeviceSupport; } if (@hasDecl(@This(), "PFN_DrvDeriveSurface")) { _ = PFN_DrvDeriveSurface; } if (@hasDecl(@This(), "PFN_DrvSynchronizeSurface")) { _ = PFN_DrvSynchronizeSurface; } if (@hasDecl(@This(), "PFN_DrvNotify")) { _ = PFN_DrvNotify; } if (@hasDecl(@This(), "PFN_DrvRenderHint")) { _ = PFN_DrvRenderHint; } if (@hasDecl(@This(), "PFN_EngCreateRectRgn")) { _ = PFN_EngCreateRectRgn; } if (@hasDecl(@This(), "PFN_EngDeleteRgn")) { _ = PFN_EngDeleteRgn; } if (@hasDecl(@This(), "PFN_EngCombineRgn")) { _ = PFN_EngCombineRgn; } if (@hasDecl(@This(), "PFN_EngCopyRgn")) { _ = PFN_EngCopyRgn; } if (@hasDecl(@This(), "PFN_EngIntersectRgn")) { _ = PFN_EngIntersectRgn; } if (@hasDecl(@This(), "PFN_EngSubtractRgn")) { _ = PFN_EngSubtractRgn; } if (@hasDecl(@This(), "PFN_EngUnionRgn")) { _ = PFN_EngUnionRgn; } if (@hasDecl(@This(), "PFN_EngXorRgn")) { _ = PFN_EngXorRgn; } if (@hasDecl(@This(), "PFN_DrvCreateDeviceBitmapEx")) { _ = PFN_DrvCreateDeviceBitmapEx; } if (@hasDecl(@This(), "PFN_DrvDeleteDeviceBitmapEx")) { _ = PFN_DrvDeleteDeviceBitmapEx; } if (@hasDecl(@This(), "PFN_DrvAssociateSharedSurface")) { _ = PFN_DrvAssociateSharedSurface; } if (@hasDecl(@This(), "PFN_DrvSynchronizeRedirectionBitmaps")) { _ = PFN_DrvSynchronizeRedirectionBitmaps; } if (@hasDecl(@This(), "PFN_DrvAccumulateD3DDirtyRect")) { _ = PFN_DrvAccumulateD3DDirtyRect; } if (@hasDecl(@This(), "PFN_DrvStartDxInterop")) { _ = PFN_DrvStartDxInterop; } if (@hasDecl(@This(), "PFN_DrvEndDxInterop")) { _ = PFN_DrvEndDxInterop; } if (@hasDecl(@This(), "PFN_DrvLockDisplayArea")) { _ = PFN_DrvLockDisplayArea; } if (@hasDecl(@This(), "PFN_DrvUnlockDisplayArea")) { _ = PFN_DrvUnlockDisplayArea; } if (@hasDecl(@This(), "PFN_DrvSurfaceComplete")) { _ = PFN_DrvSurfaceComplete; } if (@hasDecl(@This(), "PVIDEO_WIN32K_CALLOUT")) { _ = PVIDEO_WIN32K_CALLOUT; } @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/devices/display.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; pub const Reactor = struct { const BoxList = std.ArrayList(Box); pub const Pos = struct { x: isize, y: isize, z: isize, pub fn init(x: isize, y: isize, z: isize) Pos { var self = Pos{ .x = x, .y = y, .z = z }; return self; } }; const Box = struct { min: Pos, max: Pos, pub fn init(min: Pos, max: Pos) Box { var self = Box{ .min = min, .max = max }; return self; } pub fn volume(self: Box) usize { var vol: usize = 1; vol *= @intCast(usize, self.max.x - self.min.x) + 1; vol *= @intCast(usize, self.max.y - self.min.y) + 1; vol *= @intCast(usize, self.max.z - self.min.z) + 1; return vol; } pub fn clipped_volume(self: Box, clip: Box) usize { if (self.min.x > clip.max.x or self.min.y > clip.max.y or self.min.z > clip.max.z) return 0; if (self.max.x < clip.min.x or self.max.y < clip.min.y or self.max.z < clip.min.z) return 0; return self.volume(); } pub fn intersects(self: Box, other: Box) bool { if (self.max.x < other.min.x or other.max.x < self.min.x) return false; if (self.max.y < other.min.y or other.max.y < self.min.y) return false; if (self.max.z < other.min.z or other.max.z < self.min.z) return false; return true; } pub fn subtract(b0: Box, b1: Box, list: *BoxList) !void { var min = Pos.init( if (b0.min.x > b1.min.x) b0.min.x else b1.min.x, if (b0.min.y > b1.min.y) b0.min.y else b1.min.y, if (b0.min.z > b1.min.z) b0.min.z else b1.min.z, ); var max = Pos.init( if (b0.max.x < b1.max.x) b0.max.x else b1.max.x, if (b0.max.y < b1.max.y) b0.max.y else b1.max.y, if (b0.max.z < b1.max.z) b0.max.z else b1.max.z, ); var b2 = Box.init(min, max); if (b0.min.z < b2.min.z) try list.append(Box.init(Pos.init(b0.min.x, b0.min.y, b0.min.z), Pos.init(b0.max.x, b0.max.y, b2.min.z - 1))); if (b2.max.z < b0.max.z) try list.append(Box.init(Pos.init(b0.min.x, b0.min.y, b2.max.z + 1), Pos.init(b0.max.x, b0.max.y, b0.max.z))); if (b0.min.x < b2.min.x) try list.append(Box.init(Pos.init(b0.min.x, b0.min.y, b2.min.z), Pos.init(b2.min.x - 1, b0.max.y, b2.max.z))); if (b2.max.x < b0.max.x) try list.append(Box.init(Pos.init(b2.max.x + 1, b0.min.y, b2.min.z), Pos.init(b0.max.x, b0.max.y, b2.max.z))); if (b0.min.y < b2.min.y) try list.append(Box.init(Pos.init(b2.min.x, b0.min.y, b2.min.z), Pos.init(b2.max.x, b2.min.y - 1, b2.max.z))); if (b2.max.y < b0.max.y) try list.append(Box.init(Pos.init(b2.min.x, b2.max.y + 1, b2.min.z), Pos.init(b2.max.x, b0.max.y, b2.max.z))); } }; const Cube = struct { on: bool, box: Box, pub fn init(on: bool, box: Box) Cube { var self = Cube{ .on = on, .box = box }; return self; } }; cubes: std.ArrayList(Cube), clip: Box, pub fn init() Reactor { var self = Reactor{ .cubes = std.ArrayList(Cube).init(allocator), .clip = Box.init( Pos.init(std.math.minInt(isize), std.math.minInt(isize), std.math.minInt(isize)), Pos.init(std.math.maxInt(isize), std.math.maxInt(isize), std.math.maxInt(isize)), ), }; return self; } pub fn deinit(self: *Reactor) void { self.cubes.deinit(); } pub fn set_clip_cube(self: *Reactor, side: usize) void { const s = @intCast(isize, side); const min = -s; const max = s; self.clip = Box.init(Pos.init(min, min, min), Pos.init(max, max, max)); } pub fn process_line(self: *Reactor, data: []const u8) !void { var on: bool = false; var p_space: usize = 0; var it_space = std.mem.split(u8, data, " "); while (it_space.next()) |str| : (p_space += 1) { if (p_space == 0) { if (std.mem.eql(u8, str, "on")) { on = true; continue; } if (std.mem.eql(u8, str, "off")) { on = false; continue; } unreachable; } if (p_space == 1) { var box: Box = undefined; var pos_comma: usize = 0; var it_comma = std.mem.split(u8, str, ","); while (it_comma.next()) |range| : (pos_comma += 1) { self.parse_min_max(range, &box); } var cube = Cube.init(on, box); try self.cubes.append(cube); continue; } unreachable; } } pub fn run_reboot(self: *Reactor) !usize { var boxes = BoxList.init(allocator); defer boxes.deinit(); for (self.cubes.items) |c| { var list = BoxList.init(allocator); defer list.deinit(); for (boxes.items) |b| { if (b.intersects(c.box)) { try b.subtract(c.box, &list); } else { try list.append(b); } } if (c.on) { try list.append(c.box); } boxes.clearRetainingCapacity(); try boxes.appendSlice(list.items); } var count: usize = 0; for (boxes.items) |c| { count += c.clipped_volume(self.clip); } return count; } fn parse_min_max(_: *Reactor, range: []const u8, box: *Box) void { // std.debug.warn("PARSE {c}\n", .{range}); var axis: u8 = undefined; var pos_eq: usize = 0; var it_eq = std.mem.split(u8, range, "="); while (it_eq.next()) |definition| : (pos_eq += 1) { if (pos_eq == 0) { axis = definition[0]; continue; } var pos_dots: usize = 0; var it_dots = std.mem.split(u8, definition, ".."); while (it_dots.next()) |limit| : (pos_dots += 1) { if (pos_dots == 0) { const min = std.fmt.parseInt(isize, limit, 10) catch unreachable; if (axis == 'x') box.*.min.x = min; if (axis == 'y') box.*.min.y = min; if (axis == 'z') box.*.min.z = min; continue; } if (pos_dots == 1) { const max = std.fmt.parseInt(isize, limit, 10) catch unreachable; if (axis == 'x') box.*.max.x = max; if (axis == 'y') box.*.max.y = max; if (axis == 'z') box.*.max.z = max; continue; } unreachable; } } } }; test "sample part a small" { const data: []const u8 = \\on x=10..12,y=10..12,z=10..12 \\on x=11..13,y=11..13,z=11..13 \\off x=9..11,y=9..11,z=9..11 \\on x=10..10,y=10..10,z=10..10 ; var reactor = Reactor.init(); defer reactor.deinit(); reactor.set_clip_cube(50); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try reactor.process_line(line); } const cubes = try reactor.run_reboot(); try testing.expect(cubes == 39); } test "sample part a large" { const data: []const u8 = \\on x=-20..26,y=-36..17,z=-47..7 \\on x=-20..33,y=-21..23,z=-26..28 \\on x=-22..28,y=-29..23,z=-38..16 \\on x=-46..7,y=-6..46,z=-50..-1 \\on x=-49..1,y=-3..46,z=-24..28 \\on x=2..47,y=-22..22,z=-23..27 \\on x=-27..23,y=-28..26,z=-21..29 \\on x=-39..5,y=-6..47,z=-3..44 \\on x=-30..21,y=-8..43,z=-13..34 \\on x=-22..26,y=-27..20,z=-29..19 \\off x=-48..-32,y=26..41,z=-47..-37 \\on x=-12..35,y=6..50,z=-50..-2 \\off x=-48..-32,y=-32..-16,z=-15..-5 \\on x=-18..26,y=-33..15,z=-7..46 \\off x=-40..-22,y=-38..-28,z=23..41 \\on x=-16..35,y=-41..10,z=-47..6 \\off x=-32..-23,y=11..30,z=-14..3 \\on x=-49..-5,y=-3..45,z=-29..18 \\off x=18..30,y=-20..-8,z=-3..13 \\on x=-41..9,y=-7..43,z=-33..15 \\on x=-54112..-39298,y=-85059..-49293,z=-27449..7877 \\on x=967..23432,y=45373..81175,z=27513..53682 ; var reactor = Reactor.init(); defer reactor.deinit(); reactor.set_clip_cube(50); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try reactor.process_line(line); } const cubes = try reactor.run_reboot(); try testing.expect(cubes == 590784); } test "sample part b" { const data: []const u8 = \\on x=-5..47,y=-31..22,z=-19..33 \\on x=-44..5,y=-27..21,z=-14..35 \\on x=-49..-1,y=-11..42,z=-10..38 \\on x=-20..34,y=-40..6,z=-44..1 \\off x=26..39,y=40..50,z=-2..11 \\on x=-41..5,y=-41..6,z=-36..8 \\off x=-43..-33,y=-45..-28,z=7..25 \\on x=-33..15,y=-32..19,z=-34..11 \\off x=35..47,y=-46..-34,z=-11..5 \\on x=-14..36,y=-6..44,z=-16..29 \\on x=-57795..-6158,y=29564..72030,z=20435..90618 \\on x=36731..105352,y=-21140..28532,z=16094..90401 \\on x=30999..107136,y=-53464..15513,z=8553..71215 \\on x=13528..83982,y=-99403..-27377,z=-24141..23996 \\on x=-72682..-12347,y=18159..111354,z=7391..80950 \\on x=-1060..80757,y=-65301..-20884,z=-103788..-16709 \\on x=-83015..-9461,y=-72160..-8347,z=-81239..-26856 \\on x=-52752..22273,y=-49450..9096,z=54442..119054 \\on x=-29982..40483,y=-108474..-28371,z=-24328..38471 \\on x=-4958..62750,y=40422..118853,z=-7672..65583 \\on x=55694..108686,y=-43367..46958,z=-26781..48729 \\on x=-98497..-18186,y=-63569..3412,z=1232..88485 \\on x=-726..56291,y=-62629..13224,z=18033..85226 \\on x=-110886..-34664,y=-81338..-8658,z=8914..63723 \\on x=-55829..24974,y=-16897..54165,z=-121762..-28058 \\on x=-65152..-11147,y=22489..91432,z=-58782..1780 \\on x=-120100..-32970,y=-46592..27473,z=-11695..61039 \\on x=-18631..37533,y=-124565..-50804,z=-35667..28308 \\on x=-57817..18248,y=49321..117703,z=5745..55881 \\on x=14781..98692,y=-1341..70827,z=15753..70151 \\on x=-34419..55919,y=-19626..40991,z=39015..114138 \\on x=-60785..11593,y=-56135..2999,z=-95368..-26915 \\on x=-32178..58085,y=17647..101866,z=-91405..-8878 \\on x=-53655..12091,y=50097..105568,z=-75335..-4862 \\on x=-111166..-40997,y=-71714..2688,z=5609..50954 \\on x=-16602..70118,y=-98693..-44401,z=5197..76897 \\on x=16383..101554,y=4615..83635,z=-44907..18747 \\off x=-95822..-15171,y=-19987..48940,z=10804..104439 \\on x=-89813..-14614,y=16069..88491,z=-3297..45228 \\on x=41075..99376,y=-20427..49978,z=-52012..13762 \\on x=-21330..50085,y=-17944..62733,z=-112280..-30197 \\on x=-16478..35915,y=36008..118594,z=-7885..47086 \\off x=-98156..-27851,y=-49952..43171,z=-99005..-8456 \\off x=2032..69770,y=-71013..4824,z=7471..94418 \\on x=43670..120875,y=-42068..12382,z=-24787..38892 \\off x=37514..111226,y=-45862..25743,z=-16714..54663 \\off x=25699..97951,y=-30668..59918,z=-15349..69697 \\off x=-44271..17935,y=-9516..60759,z=49131..112598 \\on x=-61695..-5813,y=40978..94975,z=8655..80240 \\off x=-101086..-9439,y=-7088..67543,z=33935..83858 \\off x=18020..114017,y=-48931..32606,z=21474..89843 \\off x=-77139..10506,y=-89994..-18797,z=-80..59318 \\off x=8476..79288,y=-75520..11602,z=-96624..-24783 \\on x=-47488..-1262,y=24338..100707,z=16292..72967 \\off x=-84341..13987,y=2429..92914,z=-90671..-1318 \\off x=-37810..49457,y=-71013..-7894,z=-105357..-13188 \\off x=-27365..46395,y=31009..98017,z=15428..76570 \\off x=-70369..-16548,y=22648..78696,z=-1892..86821 \\on x=-53470..21291,y=-120233..-33476,z=-44150..38147 \\off x=-93533..-4276,y=-16170..68771,z=-104985..-24507 ; var reactor = Reactor.init(); defer reactor.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try reactor.process_line(line); } const cubes = try reactor.run_reboot(); try testing.expect(cubes == 2758514936282235); }
2021/p22/reactor.zig
const std = @import("std"); const mem = std.mem; const print = std.debug.print; const render_utils = @import("render_utils.zig"); pub fn highlightZigCode(raw_src: []const u8, out: anytype) !void { // TODO: who should be doing this cleanup? const src = mem.trim(u8, raw_src, " \n"); try out.writeAll("<pre><code class=\"zig\">"); var tokenizer = std.zig.Tokenizer.init(src); var index: usize = 0; var next_tok_is_fn = false; while (true) { const prev_tok_was_fn = next_tok_is_fn; next_tok_is_fn = false; const token = tokenizer.next(); try render_utils.writeEscaped(out, src[index..token.loc.start]); switch (token.id) { .Eof => break, .Keyword_align, .Keyword_and, .Keyword_asm, .Keyword_async, .Keyword_await, .Keyword_break, .Keyword_catch, .Keyword_comptime, .Keyword_const, .Keyword_continue, .Keyword_defer, .Keyword_else, .Keyword_enum, .Keyword_errdefer, .Keyword_error, .Keyword_export, .Keyword_extern, .Keyword_for, .Keyword_if, .Keyword_inline, .Keyword_noalias, .Keyword_noinline, .Keyword_nosuspend, .Keyword_opaque, .Keyword_or, .Keyword_orelse, .Keyword_packed, .Keyword_anyframe, .Keyword_pub, .Keyword_resume, .Keyword_return, .Keyword_linksection, .Keyword_callconv, .Keyword_struct, .Keyword_suspend, .Keyword_switch, .Keyword_test, .Keyword_threadlocal, .Keyword_try, .Keyword_union, .Keyword_unreachable, .Keyword_usingnamespace, .Keyword_var, .Keyword_volatile, .Keyword_allowzero, .Keyword_while, .Keyword_anytype, => { try out.writeAll("<span class=\"tok-kw\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); }, .Keyword_fn => { try out.writeAll("<span class=\"tok-kw\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); next_tok_is_fn = true; }, .Keyword_undefined, .Keyword_null, .Keyword_true, .Keyword_false, => { try out.writeAll("<span class=\"tok-null\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); }, .StringLiteral, .MultilineStringLiteralLine, .CharLiteral, => { try out.writeAll("<span class=\"tok-str\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); }, .Builtin => { try out.writeAll("<span class=\"tok-builtin\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); }, .LineComment, .DocComment, .ContainerDocComment, .ShebangLine, => { try out.writeAll("<span class=\"tok-comment\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); }, .Identifier => { if (prev_tok_was_fn) { try out.writeAll("<span class=\"tok-fn\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); } else { const is_int = blk: { if (src[token.loc.start] != 'i' and src[token.loc.start] != 'u') break :blk false; var i = token.loc.start + 1; if (i == token.loc.end) break :blk false; while (i != token.loc.end) : (i += 1) { if (src[i] < '0' or src[i] > '9') break :blk false; } break :blk true; }; if (is_int or isType(src[token.loc.start..token.loc.end])) { try out.writeAll("<span class=\"tok-type\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); } else { try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); } } }, .IntegerLiteral, .FloatLiteral, => { try out.writeAll("<span class=\"tok-number\">"); try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]); try out.writeAll("</span>"); }, .Bang, .Pipe, .PipePipe, .PipeEqual, .Equal, .EqualEqual, .EqualAngleBracketRight, .BangEqual, .LParen, .RParen, .Semicolon, .Percent, .PercentEqual, .LBrace, .RBrace, .LBracket, .RBracket, .Period, .PeriodAsterisk, .Ellipsis2, .Ellipsis3, .Caret, .CaretEqual, .Plus, .PlusPlus, .PlusEqual, .PlusPercent, .PlusPercentEqual, .Minus, .MinusEqual, .MinusPercent, .MinusPercentEqual, .Asterisk, .AsteriskEqual, .AsteriskAsterisk, .AsteriskPercent, .AsteriskPercentEqual, .Arrow, .Colon, .Slash, .SlashEqual, .Comma, .Ampersand, .AmpersandEqual, .QuestionMark, .AngleBracketLeft, .AngleBracketLeftEqual, .AngleBracketAngleBracketLeft, .AngleBracketAngleBracketLeftEqual, .AngleBracketRight, .AngleBracketRightEqual, .AngleBracketAngleBracketRight, .AngleBracketAngleBracketRightEqual, .Tilde, => try render_utils.writeEscaped(out, src[token.loc.start..token.loc.end]), .Invalid, .Invalid_ampersands, .Invalid_periodasterisks => return parseError( src, token, "syntax error", .{}, ), } index = token.loc.end; } try out.writeAll("</code></pre>"); } // TODO: this function returns anyerror, interesting fn parseError(src: []const u8, token: std.zig.Token, comptime fmt: []const u8, args: anytype) anyerror { const loc = getTokenLocation(src, token); // const args_prefix = .{ tokenizer.source_file_name, loc.line + 1, loc.column + 1 }; // print("{}:{}:{}: error: " ++ fmt ++ "\n", args_prefix ++ args); const args_prefix = .{ loc.line + 1, loc.column + 1 }; print("{}:{}: error: " ++ fmt ++ "\n", args_prefix ++ args); if (loc.line_start <= loc.line_end) { print("{}\n", .{src[loc.line_start..loc.line_end]}); { var i: usize = 0; while (i < loc.column) : (i += 1) { print(" ", .{}); } } { const caret_count = token.loc.end - token.loc.start; var i: usize = 0; while (i < caret_count) : (i += 1) { print("~", .{}); } } print("\n", .{}); } return error.ParseError; } const builtin_types = [_][]const u8{ "f16", "f32", "f64", "f128", "c_longdouble", "c_short", "c_ushort", "c_int", "c_uint", "c_long", "c_ulong", "c_longlong", "c_ulonglong", "c_char", "c_void", "void", "bool", "isize", "usize", "noreturn", "type", "anyerror", "comptime_int", "comptime_float", }; fn isType(name: []const u8) bool { for (builtin_types) |t| { if (mem.eql(u8, t, name)) return true; } return false; } const Location = struct { line: usize, column: usize, line_start: usize, line_end: usize, }; fn getTokenLocation(src: []const u8, token: std.zig.Token) Location { var loc = Location{ .line = 0, .column = 0, .line_start = 0, .line_end = 0, }; for (src) |c, i| { if (i == token.loc.start) { loc.line_end = i; while (loc.line_end < src.len and src[loc.line_end] != '\n') : (loc.line_end += 1) {} return loc; } if (c == '\n') { loc.line += 1; loc.column = 0; loc.line_start = i + 1; } else { loc.column += 1; } } return loc; }
src/doctest/syntax.zig
const std = @import( "std" ); const min = std.math.min; const max = std.math.max; const sqrt = std.math.sqrt; const minInt = std.math.minInt; const Atomic = std.atomic.Atomic; const milliTimestamp = std.time.milliTimestamp; usingnamespace @import( "core/util.zig" ); pub fn SimConfig( comptime N: usize, comptime P: usize ) type { return struct { frameInterval_MILLIS: i64, timestep: f64, xLimits: [N]Interval, particles: [P]Particle(N), accelerators: []*const Accelerator(N,P), }; } pub fn Accelerator( comptime N: usize, comptime P: usize ) type { return struct { const Self = @This(); addAccelerationFn: fn ( self: *const Self, xs: *const [N*P]f64, ms: *const [P]f64, p: usize, x: [N]f64, aSum_OUT: *[N]f64 ) void, computePotentialEnergyFn: fn ( self: *const Self, xs: *const [N*P]f64, ms: *const [P]f64 ) f64, pub fn addAcceleration( self: *const Self, xs: *const [N*P]f64, ms: *const [P]f64, p: usize, x: [N]f64, aSum_OUT: *[N]f64 ) void { return self.addAccelerationFn( self, xs, ms, p, x, aSum_OUT ); } pub fn computePotentialEnergy( self: *const Self, xs: *const [N*P]f64, ms: *const [P]f64 ) f64 { return self.computePotentialEnergyFn( self, xs, ms ); } }; } pub fn Particle( comptime N: usize ) type { return struct { const Self = @This(); m: f64, x: [N]f64, v: [N]f64, pub fn init( m: f64, x: [N]f64, v: [N]f64 ) Self { return .{ .m = m, .x = x, .v = v, }; } }; } pub fn SimFrame( comptime N: usize, comptime P: usize ) type { return struct { config: *const SimConfig(N,P), t: f64, ms: *const [P]f64, xs: *const [N*P]f64, vs: *const [N*P]f64, }; } pub fn SimListener( comptime N: usize, comptime P: usize ) type { return struct { const Self = @This(); handleFrameFn: fn ( self: *Self, simFrame: *const SimFrame(N,P) ) anyerror!void, pub fn handleFrame( self: *Self, simFrame: *const SimFrame(N,P) ) !void { return self.handleFrameFn( self, simFrame ); } }; } /// Caller must ensure that locations pointed to by input /// args remain valid until after this fn returns. pub fn runSimulation( comptime N: usize, comptime P: usize, config: *const SimConfig(N,P), listeners: []const *SimListener(N,P), running: *const Atomic(bool), ) !void { // TODO: Use SIMD Vectors? // TODO: Multi-thread? (If so, avoid false sharing) const tFull = config.timestep; const tHalf = 0.5*tFull; const accelerators = config.accelerators; var msArray = @as( [P]f64, undefined ); var xsStart = @as( [N*P]f64, undefined ); var vsStart = @as( [N*P]f64, undefined ); for ( config.particles ) |particle, p| { msArray[p] = particle.m; xsStart[ p*N.. ][ 0..N ].* = particle.x; vsStart[ p*N.. ][ 0..N ].* = particle.v; } const ms = &msArray; var xMins = @as( [N]f64, undefined ); var xMaxs = @as( [N]f64, undefined ); for ( config.xLimits ) |xLimit, n| { const xLimitA = xLimit.start; const xLimitB = xLimit.start + xLimit.span; xMins[n] = min( xLimitA, xLimitB ); xMaxs[n] = max( xLimitA, xLimitB ); } // Pre-compute the index of the first coord of each particle, for easy iteration later var particleFirstCoordIndices = @as( [P]usize, undefined ); { var p = @as( usize, 0 ); while ( p < P ) : ( p += 1 ) { particleFirstCoordIndices[p] = p * N; } } var coordArrays = @as( [7][N*P]f64, undefined ); var xsCurr = &coordArrays[0]; var xsNext = &coordArrays[1]; var vsCurr = &coordArrays[2]; var vsHalf = &coordArrays[3]; var vsNext = &coordArrays[4]; var asCurr = &coordArrays[5]; var asNext = &coordArrays[6]; xsCurr[ 0..N*P ].* = xsStart; vsCurr[ 0..N*P ].* = vsStart; for ( particleFirstCoordIndices ) |c0, p| { const xCurr = xsCurr[ c0.. ][ 0..N ]; var aCurr = asCurr[ c0.. ][ 0..N ]; aCurr.* = [1]f64 { 0.0 } ** N; for ( accelerators ) |accelerator| { accelerator.addAcceleration( xsCurr, ms, p, xCurr.*, aCurr ); } } const frameInterval_MILLIS = config.frameInterval_MILLIS; var nextFrame_PMILLIS = @as( i64, minInt( i64 ) ); var tElapsed = @as( f64, 0 ); while ( running.load( .SeqCst ) ) : ( tElapsed += tFull ) { // Send particle coords to the listener periodically const now_PMILLIS = milliTimestamp( ); if ( now_PMILLIS >= nextFrame_PMILLIS ) { const frame = SimFrame(N,P) { .config = config, .t = tElapsed, .ms = ms, .xs = xsCurr, .vs = vsCurr, }; for ( listeners ) |listener| { try listener.handleFrame( &frame ); } nextFrame_PMILLIS = now_PMILLIS + frameInterval_MILLIS; } // Update particle coords, but without checking for bounces for ( vsCurr ) |vCurr, c| { vsHalf[c] = vCurr + asCurr[c]*tHalf; } for ( xsCurr ) |xCurr, c| { xsNext[c] = xCurr + vsHalf[c]*tFull; } for ( particleFirstCoordIndices ) |c0, p| { var xNext = xsNext[ c0.. ][ 0..N ]; var aNext = asNext[ c0.. ][ 0..N ]; aNext.* = [1]f64 { 0.0 } ** N; for ( accelerators ) |accelerator| { accelerator.addAcceleration( xsCurr, ms, p, xNext.*, aNext ); } } for ( vsHalf ) |vHalf, c| { vsNext[c] = vHalf + asNext[c]*tHalf; } // Handle bounces for ( particleFirstCoordIndices ) |c0, p| { // TODO: Profile, speed up var xNext = xsNext[ c0.. ][ 0..N ]; // Bail immediately in the common case with no bounce var hasBounce = false; for ( xNext ) |xNext_n, n| { if ( xNext_n <= xMins[n] or xNext_n >= xMaxs[n] ) { hasBounce = true; break; } const aCurr_n = asCurr[ c0 + n ]; const vCurr_n = vsCurr[ c0 + n ]; const tTip_n = vCurr_n / ( -2.0 * aCurr_n ); if ( 0 <= tTip_n and tTip_n < tFull ) { const xCurr_n = xsCurr[ c0 + n ]; const xTip_n = xCurr_n + vCurr_n*tTip_n + 0.5*aCurr_n*tTip_n*tTip_n; if ( xTip_n <= xMins[n] or xTip_n >= xMaxs[n] ) { hasBounce = true; break; } } } if ( !hasBounce ) { continue; } var aNext = asNext[ c0.. ][ 0..N ]; var vNext = vsNext[ c0.. ][ 0..N ]; var vHalf = vsHalf[ c0.. ][ 0..N ]; var aCurr = @as( [N]f64, undefined ); var vCurr = @as( [N]f64, undefined ); var xCurr = @as( [N]f64, undefined ); aCurr = asCurr[ c0.. ][ 0..N ].*; vCurr = vsCurr[ c0.. ][ 0..N ].*; xCurr = xsCurr[ c0.. ][ 0..N ].*; while ( true ) { // Time of soonest bounce, and what to multiply each velocity coord by at that time var tBounce = std.math.inf( f64 ); var vBounceFactor = [1]f64 { 1.0 } ** N; for ( xNext ) |xNext_n, n| { var hasMinBounce = false; var hasMaxBounce = false; if ( xNext_n <= xMins[n] ) { hasMinBounce = true; } else if ( xNext_n >= xMaxs[n] ) { hasMaxBounce = true; } const tTip_n = vCurr[n] / ( -2.0 * aCurr[n] ); if ( 0 <= tTip_n and tTip_n < tFull ) { const xTip_n = xCurr[n] + vCurr[n]*tTip_n + 0.5*aCurr[n]*tTip_n*tTip_n; if ( xTip_n <= xMins[n] ) { hasMinBounce = true; } else if ( xTip_n >= xMaxs[n] ) { hasMaxBounce = true; } } // At most 4 bounce times will be appended var tsBounce_n_ = @as( [4]f64, undefined ); var tsBounce_n = Buffer.init( &tsBounce_n_ ); if ( hasMinBounce ) { appendBounceTimes( xCurr[n], vCurr[n], aCurr[n], xMins[n], &tsBounce_n ); } if ( hasMaxBounce ) { appendBounceTimes( xCurr[n], vCurr[n], aCurr[n], xMaxs[n], &tsBounce_n ); } for ( tsBounce_n.items[ 0..tsBounce_n.size ] ) |tBounce_n| { if ( 0 <= tBounce_n and tBounce_n < tFull ) { if ( tBounce_n < tBounce ) { tBounce = tBounce_n; vBounceFactor = [1]f64 { 1.0 } ** N; vBounceFactor[n] = -1.0; } else if ( tBounce_n == tBounce ) { vBounceFactor[n] = -1.0; } } } } // If soonest bounce is after timestep end, then bounce update is done if ( tBounce > tFull ) { break; } // Update from 0 to tBounce { var tFull_ = tBounce; var tHalf_ = 0.5 * tFull_; var aNext_ = @as( [N]f64, undefined ); var vNext_ = @as( [N]f64, undefined ); var xNext_ = @as( [N]f64, undefined ); for ( vCurr ) |vCurr_n, n| { vHalf[n] = vCurr_n + aCurr[n]*tHalf_; } for ( xCurr ) |xCurr_n, n| { xNext_[n] = xCurr_n + vHalf[n]*tFull_; } aNext_ = [1]f64 { 0.0 } ** N; for ( accelerators ) |accelerator| { accelerator.addAcceleration( xsCurr, ms, p, xNext_, &aNext_ ); } for ( vHalf ) |vHalf_n, n| { vNext_[n] = vHalf_n + aNext_[n]*tHalf_; } aCurr = aNext_; for ( vNext_ ) |vNext_n, n| { vCurr[n] = vBounceFactor[n] * vNext_n; } xCurr = xNext_; } // Update from tBounce to tFull { var tFull_ = tFull - tBounce; var tHalf_ = 0.5 * tFull_; for ( vCurr ) |vCurr_n, n| { vHalf[n] = vCurr_n + aCurr[n]*tHalf_; } for ( xCurr ) |xCurr_n, n| { xNext[n] = xCurr_n + vHalf[n]*tFull_; } aNext.* = [1]f64 { 0.0 } ** N; for ( accelerators ) |accelerator| { accelerator.addAcceleration( xsCurr, ms, p, xNext.*, aNext ); } for ( vHalf ) |vHalf_n, n| { vNext[n] = vHalf_n + aNext[n]*tHalf_; } } } } // Rotate slices swap( *[N*P]f64, &asCurr, &asNext ); swap( *[N*P]f64, &vsCurr, &vsNext ); swap( *[N*P]f64, &xsCurr, &xsNext ); } } const Buffer = struct { items: []f64, size: usize, pub fn init( items: []f64 ) Buffer { return Buffer { .items = items, .size = 0, }; } pub fn append( self: *Buffer, item: f64 ) void { if ( self.size < 0 or self.size >= self.items.len ) { std.debug.panic( "Failed to append to buffer: capacity = {d}, size = {d}", .{ self.items.len, self.size } ); } self.items[ self.size ] = item; self.size += 1; } }; /// May append up to 2 values to tsWall_OUT. fn appendBounceTimes( x: f64, v: f64, a: f64, xWall: f64, tsWall_OUT: *Buffer ) void { const A = 0.5*a; const B = v; const C = x - xWall; if ( A == 0.0 ) { // Bt + C = 0 const tWall = -C / B; tsWall_OUT.append( tWall ); } else { // AtΒ² + Bt + C = 0 const D = B*B - 4.0*A*C; if ( D >= 0.0 ) { const sqrtD = sqrt( D ); const oneOverTwoA = 0.5 / A; const tWallPlus = ( -B + sqrtD )*oneOverTwoA; const tWallMinus = ( -B - sqrtD )*oneOverTwoA; tsWall_OUT.append( tWallPlus ); tsWall_OUT.append( tWallMinus ); } } } fn swap( comptime T: type, a: *T, b: *T ) void { const temp = a.*; a.* = b.*; b.* = temp; }
src/sim.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Vec2 = tools.Vec2; fn powerOfCell(p: Vec2, SN: u32) i32 { const rackId = @intCast(u32, p.x + 10); var pow = @intCast(u32, p.y) * rackId; pow += SN; pow *= rackId; pow /= 100; pow = pow % 10; return @intCast(i32, pow) - 5; } pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { _ = input; const SN = 7403; // GridSerialNumber //std.debug.print("test (3,5) 8: {}\n", .{powerOfCell(Vec2{ .x = 3, .y = 5 }, 8)}); //std.debug.print("test (217,196) 39: {}\n", .{powerOfCell(Vec2{ .x = 217, .y = 196 }, 39)}); // chaque case = integrale de la surface en haut Γ  gauche const powergrid = try allocator.alloc(i32, 301 * 301); const stride = 301; defer allocator.free(powergrid); { var p = Vec2{ .x = 0, .y = 0 }; while (p.y <= 300) : (p.y += 1) { p.x = 0; while (p.x <= 300) : (p.x += 1) { if (p.x == 0 or p.y == 0) { powergrid[@intCast(usize, p.x + stride * p.y)] = 0; continue; } const p00 = Vec2.add(p, Vec2{ .x = 0, .y = 0 }); //const p01 = Vec2.add(p, Vec2{ .x = 0, .y = -1 }); //const p10 = Vec2.add(p, Vec2{ .x = -1, .y = 0 }); //const p11 = Vec2.add(p, Vec2{ .x = -1, .y = -1 }); const pow = powerOfCell(p00, SN); const acc01 = powergrid[@intCast(usize, (p.x - 1) + stride * (p.y - 0))]; const acc10 = powergrid[@intCast(usize, (p.x - 0) + stride * (p.y - 1))]; const acc11 = powergrid[@intCast(usize, (p.x - 1) + stride * (p.y - 1))]; powergrid[@intCast(usize, p.x + stride * p.y)] = pow + (acc01 + (acc10 - acc11)); } } } // part1 const ans1 = ans: { var best = Vec2{ .x = 0, .y = 0 }; var best_pow: i64 = -999999999; var p = Vec2{ .x = 1, .y = 1 }; while (p.y <= 300 - 3) : (p.y += 1) { p.x = 1; while (p.x <= 300 - 3) : (p.x += 1) { const sz = Vec2{ .x = 2, .y = 2 }; const acc00 = powergrid[@intCast(usize, (p.x - 1) + stride * (p.y - 1))]; const acc03 = powergrid[@intCast(usize, (p.x - 1) + stride * (p.y + sz.y))]; const acc30 = powergrid[@intCast(usize, (p.x + sz.x) + stride * (p.y - 1))]; const acc33 = powergrid[@intCast(usize, (p.x + sz.x) + stride * (p.y + sz.y))]; const pow = (acc33 - acc03) - (acc30 - acc00); if (best_pow < pow) { best_pow = pow; best = p; } } } break :ans best; }; // part2 const ans2 = ans: { var best: struct { p: Vec2, sz: i32 } = .{ .p = Vec2{ .x = 0, .y = 0 }, .sz = 0 }; var best_pow: i64 = -999999999; var p = Vec2{ .x = 1, .y = 1 }; while (p.y <= 300) : (p.y += 1) { p.x = 1; while (p.x <= 300) : (p.x += 1) { var sz: i32 = 0; while (sz <= (300 - p.x) and sz <= (300 - p.y)) : (sz += 1) { const acc00 = powergrid[@intCast(usize, (p.x - 1) + stride * (p.y - 1))]; const acc03 = powergrid[@intCast(usize, (p.x - 1) + stride * (p.y + sz))]; const acc30 = powergrid[@intCast(usize, (p.x + sz) + stride * (p.y - 1))]; const acc33 = powergrid[@intCast(usize, (p.x + sz) + stride * (p.y + sz))]; const pow = (acc33 - acc03) - (acc30 - acc00); if (best_pow < pow) { best_pow = pow; best = .{ .p = p, .sz = sz + 1 }; } } } } break :ans best; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day10.txt", run);
2018/day11.zig
const std = @import("std"); const testing = std.testing; const meta = std.meta; const trait = std.meta.trait; const log = std.log.scoped(.wasmtime_zig); pub const c = @import("c.zig"); var CALLBACK: usize = undefined; // @TODO: Split these up into own error sets pub const Error = error{ /// Failed to initialize an `Engine` (i.e. invalid config) EngineInit, /// Failed to initialize a `Store` StoreInit, /// Failed to initialize a `Module` ModuleInit, /// Failed to create a wasm function based on /// the given `Store` and functype FuncInit, /// Failed to initialize a new `Instance` InstanceInit, /// When the user provided a different ResultType to `Func.call` /// than what is defined by the wasm binary InvalidResultType, /// The given argument count to `Func.call` mismatches that /// of the func argument count of the wasm binary InvalidParamCount, /// The wasm function number of results mismatch that of the given /// ResultType to `Func.Call`. Note that `void` equals to 0 result types. InvalidResultCount, }; pub const Engine = opaque { /// Initializes a new `Engine` pub fn init() !*Engine { return wasm_engine_new() orelse Error.EngineInit; } /// Frees the resources of the `Engine` pub fn deinit(self: *Engine) void { wasm_engine_delete(self); } extern fn wasm_engine_new() ?*Engine; extern fn wasm_engine_delete(*Engine) void; }; pub const Store = opaque { /// Initializes a new `Store` based on the given `Engine` pub fn init(engine: *Engine) !*Store { return wasm_store_new(engine) orelse Error.StoreInit; } /// Frees the resource of the `Store` itself pub fn deinit(self: *Store) void { wasm_store_delete(self); } extern fn wasm_store_new(*Engine) ?*Store; extern fn wasm_store_delete(*Store) void; }; pub const Module = opaque { /// Initializes a new `Module` using the supplied engine and wasm bytecode pub fn initFromWasm(engine: *Engine, wasm: []const u8) !*Module { var wasm_bytes = c.ByteVec.initWithCapacity(wasm.len); defer wasm_bytes.deinit(); var i: usize = 0; var ptr = wasm_bytes.data; while (i < wasm.len) : (i += 1) { ptr.* = wasm[i]; ptr += 1; } return Module.init(engine, wasm_bytes); } /// Initializes a new `Module` by first converting the given wat format /// into wasm bytecode. pub fn initFromWat(engine: *Engine, wat: []const u8) !*Module { var wat_bytes = c.ByteVec.initWithCapacity(wat.len); defer wat_bytes.deinit(); var i: usize = 0; var ptr = wat_bytes.data; while (i < wat.len) : (i += 1) { ptr.* = wat[i]; ptr += 1; } var wasm_bytes: c.ByteVec = undefined; const err = c.wasmtime_wat2wasm(&wat_bytes, &wasm_bytes); defer if (err == null) wasm_bytes.deinit(); if (err) |e| { defer e.deinit(); var msg = e.getMessage(); defer msg.deinit(); log.err("unexpected error occurred: '{s}'", .{msg.toSlice()}); return Error.ModuleInit; } return Module.init(engine, &wasm_bytes); } fn init(engine: *Engine, wasm_bytes: *c.ByteVec) !*Module { var module: ?*Module = undefined; const err = wasmtime_module_new(engine, wasm_bytes, &module); if (err) |e| { defer e.deinit(); var msg = e.getMessage(); defer msg.deinit(); log.err("unexpected error occurred: '{s}'", .{msg.toSlice()}); return Error.ModuleInit; } return module.?; } pub fn deinit(self: *Module) void { wasm_module_delete(self); } extern fn wasmtime_module_new(*Engine, *c.ByteVec, *?*Module) ?*c.WasmError; extern fn wasm_module_delete(*Module) void; }; fn cb(params: ?*const c.Valtype, results: ?*c.Valtype) callconv(.C) ?*c.Trap { const func = @intToPtr(fn () void, CALLBACK); func(); return null; } pub const Func = opaque { pub fn init(store: *Store, callback: anytype) !*Func { const cb_meta = @typeInfo(@TypeOf(callback)); switch (cb_meta) { .Fn => { if (cb_meta.Fn.args.len > 0 or cb_meta.Fn.return_type.? != void) { @compileError("only callbacks with no input args and no results are currently supported"); } }, else => @compileError("only functions can be used as callbacks into Wasm"), } CALLBACK = @ptrToInt(callback); var args = c.ValtypeVec.empty(); var results = c.ValtypeVec.empty(); const functype = c.wasm_functype_new(&args, &results) orelse return Error.FuncInit; defer c.wasm_functype_delete(functype); return wasm_func_new(store, functype, cb) orelse Error.FuncInit; } /// Returns the `Func` as an `c.Extern` /// /// Owned by `self` and shouldn't be deinitialized pub fn asExtern(self: *Func) *c.Extern { return wasm_func_as_extern(self).?; } /// Returns the `Func` from an `c.Extern` /// return null if extern's type isn't a functype /// /// Owned by `extern_func` and shouldn't be deinitialized pub fn fromExtern(extern_func: *c.Extern) ?*Func { return @ptrCast(?*Func, extern_func.asFunc()); } /// Creates a copy of the current `Func` /// returned copy is owned by the caller and must be freed /// by the owner pub fn copy(self: *Func) *Func { return self.wasm_func_copy().?; } /// Tries to call the wasm function /// expects `args` to be tuple of arguments pub fn call(self: *Func, comptime ResultType: type, args: anytype) !ResultType { if (!comptime trait.isTuple(@TypeOf(args))) @compileError("Expected 'args' to be a tuple, but found type '" ++ @typeName(@TypeOf(args)) ++ "'"); const args_len = args.len; comptime var wasm_args: [args_len]c.Value = undefined; inline for (wasm_args) |*arg, i| { arg.* = switch (@TypeOf(args[i])) { i32, u32 => .{ .kind = .i32, .of = .{ .i32 = @intCast(i32, args[i]) } }, i64, u64 => .{ .kind = .i64, .of = .{ .i64 = @intCast(i64, args[i]) } }, f32 => .{ .kind = .f32, .of = .{ .f32 = args[i] } }, f64 => .{ .kind = .f64, .of = .{ .f64 = args[i] } }, *Func => .{ .kind = .funcref, .of = .{ .ref = args[i] } }, *c.Extern => .{ .kind = .anyref, .of = .{ .ref = args[i] } }, else => |ty| @compileError("Unsupported argument type '" ++ @typeName(ty) + "'"), }; } // TODO multiple return values const result_len: usize = if (ResultType == void) 0 else 1; if (result_len != self.wasm_func_result_arity()) return Error.InvalidResultCount; if (args_len != self.wasm_func_param_arity()) return Error.InvalidParamCount; const final_args = c.ValVec{ .size = args_len, .data = if (args_len == 0) undefined else @ptrCast([*]c.Value, &wasm_args), }; var trap: ?*c.Trap = null; var result_list = c.ValVec.initWithCapacity(result_len); defer result_list.deinit(); const err = wasmtime_func_call(self, &final_args, &result_list, &trap); if (err) |e| { defer e.deinit(); var msg = e.getMessage(); defer msg.deinit(); log.err("Unable to call function: '{s}'", .{msg.toSlice()}); return Error.InstanceInit; } if (trap) |t| { t.deinit(); // TODO handle trap message log.err("code unexpectedly trapped", .{}); return Error.InstanceInit; } if (ResultType == void) return; // TODO: Handle multiple returns const result_ty = result_list.data[0]; if (!matchesKind(ResultType, result_ty.kind)) return Error.InvalidResultType; return switch (ResultType) { i32, u32 => @intCast(ResultType, result_ty.of.i32), i64, u64 => @intCast(ResultType, result_ty.of.i64), f32 => result_ty.of.f32, f64 => result_ty.of.f64, *Func => @ptrCast(?*Func, result_ty.of.ref).?, *c.Extern => @ptrCast(?*c.Extern, result_ty.of.ref).?, else => |ty| @compileError("Unsupported result type '" ++ @typeName(ty) ++ "'"), }; } /// Returns tue if the given `kind` of `c.Valkind` can coerce to type `T` fn matchesKind(comptime T: type, kind: c.Valkind) bool { return switch (T) { i32, u32 => kind == .i32, i64, u64 => kind == .i64, f32 => kind == .f32, f64 => kind == .f64, *Func => kind == .funcref, *c.Extern => kind == .ref, else => false, }; } extern fn wasm_func_new(*Store, functype: ?*c_void, callback: c.Callback) ?*Func; extern fn wasm_func_as_extern(*Func) ?*c.Extern; extern fn wasm_func_copy(*Func) ?*Func; extern fn wasmtime_func_call( ?*Func, args: *const c.ValVec, results: *c.ValVec, trap: *?*c.Trap, ) ?*c.WasmError; extern fn wasm_func_result_arity(*Func) usize; extern fn wasm_func_param_arity(*Func) usize; }; pub const Instance = opaque { /// Initializes a new `Instance` using the given `store` and `mode`. /// The given slice defined in `import` must match what was initialized /// using the same `Store` as given. pub fn init(store: *Store, module: *Module, import: []const *Func) !*Instance { var trap: ?*c.Trap = null; var instance: ?*Instance = null; var imports = c.ExternVec.initWithCapacity(import.len); defer imports.deinit(); var ptr = imports.data; for (import) |func| { ptr.* = func.asExtern(); ptr += 1; } const err = wasmtime_instance_new(store, module, &imports, &instance, &trap); if (err) |e| { defer e.deinit(); var msg = e.getMessage(); defer msg.deinit(); log.err("unexpected error occurred: '{s}'", .{msg.toSlice()}); return Error.InstanceInit; } if (trap) |t| { defer t.deinit(); // TODO handle trap message log.err("code unexpectedly trapped", .{}); return Error.InstanceInit; } return instance.?; } /// Returns an export by its name if found /// returns null if not found /// The returned `Func` is a copy and must be freed by the caller pub fn getExportFunc(self: *Instance, name: []const u8) ?*Func { var externs: c.ExternVec = undefined; self.wasm_instance_exports(&externs); defer externs.deinit(); const instance_type = self.getType(); defer instance_type.deinit(); var type_exports = instance_type.exports(); defer type_exports.deinit(); return for (type_exports.toSlice()) |ty, index| { const t = ty orelse continue; const type_name = t.name(); defer type_name.deinit(); if (std.mem.eql(u8, name, type_name.toSlice())) { const ext = externs.data[index] orelse return null; break Func.fromExtern(ext).?.copy(); } } else null; } /// Returns the `c.InstanceType` of the `Instance` pub fn getType(self: *Instance) *c.InstanceType { return self.wasm_instance_type().?; } /// Frees the `Instance`'s resources pub fn deinit(self: *Instance) void { self.wasm_instance_delete(); } extern fn wasmtime_instance_new( store: *Store, module: *const Module, imports: *const c.ExternVec, instance: *?*Instance, trap: *?*c.Trap, ) ?*c.WasmError; extern fn wasmtime_instance_delete(*Instance) void; extern fn wasm_instance_exports(*Instance, *c.ExternVec) void; extern fn wasm_instance_type(*const Instance) ?*c.InstanceType; }; test "" { testing.refAllDecls(@This()); }
src/main.zig
const std = @import("std"); const fs = std.fs; const Answer = struct { gamma_rate: u32 = 0, epsilon_rate: u32 = 0, oxygen_rating: u32 = 0, co2_rating: u32 = 0 }; fn count_bits_in_line(counts: []u32, entry: u32, nbits: usize) !void { var i: u5 = 0; while (i < nbits) { // FIXME: how to get i-th bit? var mask: u32 = @as(u32, 1) << i; if (entry & mask != 0) { counts[i] += 1; } i += 1; } } fn get_answer_from_file(allocator: std.mem.Allocator, filename: []const u8, nlines: u32) !Answer { var file = try fs.cwd().openFile(filename, .{ .read = true }); defer file.close(); var reader = std.io.bufferedReader(file.reader()); var in_stream = reader.reader(); // NOTE: just hardcoding this here for the given inputs; avoids allocations! var one_bit_counts = [_]u32{0} ** 12; var entries = try allocator.alloc(u32, nlines); defer allocator.free(entries); // {{{ gather bit count in every position var buffer: [32]u8 = undefined; var nbits: usize = 0; { var i: u32 = 0; while (try in_stream.readUntilDelimiterOrEof(&buffer, '\n')) |line| { if (i == 0) { nbits = line.len; } entries[i] = try std.fmt.parseInt(u32, line, 2); try count_bits_in_line(&one_bit_counts, entries[i], nbits); i += 1; if (i >= nlines) { break; } } if (i < nlines) { std.debug.print("Read too few lines?", .{}); return Answer{}; } } // }}} // {{{ reconstruct gamma and epsilon var gamma_rate: u32 = 0; var epsilon_rate: u32 = 0; { var i: u5 = 0; while (i < nbits) { var mask: u32 = @as(u32, 1) << i; if (one_bit_counts[i] > (nlines - one_bit_counts[i])) { // NOTE: 1 was the most common bit -> put it in gamma gamma_rate |= mask; } else { // NOTE: 1 was the less common bit -> put it it epsilon epsilon_rate |= mask; } i += 1; } } // }}} // {{{ reconstruct oxygen and co2 var oxygen_rating: u32 = 0; var co2_rating: u32 = 0; { var i: u5 = 0; while (i < nbits) { i += 1; } } // }}} return Answer{ .gamma_rate = gamma_rate, .epsilon_rate = epsilon_rate, .oxygen_rating = oxygen_rating, .co2_rating = co2_rating, }; } pub fn main() void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var alloc = gpa.allocator(); defer _ = gpa.deinit(); var example = get_answer_from_file(alloc, "example.txt", 12) catch { std.debug.print("Couldn't read file.", .{}); return; }; std.debug.print("gamma {d} epsilon {d}\n", .{ example.gamma_rate, example.epsilon_rate }); std.debug.print("Your example answer was {d}.\n", .{example.gamma_rate * example.epsilon_rate}); std.debug.print("Your example answer was {d}.\n", .{example.oxygen_rating * example.co2_rating}); var answer = get_answer_from_file(alloc, "input.txt", 1000) catch { std.debug.print("Couldn't read file.", .{}); return; }; std.debug.print("gamma {d} epsilon {d}\n", .{ answer.gamma_rate, answer.epsilon_rate }); std.debug.print("Your puzzle answer was {d}.\n", .{answer.gamma_rate * answer.epsilon_rate}); std.debug.print("Your puzzle answer was {d}.\n", .{answer.oxygen_rating * answer.co2_rating}); }
day3/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const input_file = "input03.txt"; const Square = enum { open, tree, }; fn parseMap(allocator: *Allocator, map: []const u8) ![]const []const Square { var result = std.ArrayList([]const Square).init(allocator); var iter = std.mem.tokenize(map, "\n"); while (iter.next()) |row| { var parsed_row = try allocator.alloc(Square, row.len); for (row) |x, i| parsed_row[i] = switch (x) { '.' => .open, '#' => .tree, else => unreachable, }; try result.append(parsed_row); } return result.toOwnedSlice(); } fn freeMap(allocator: *Allocator, map: []const []const Square) void { for (map) |row| allocator.free(row); allocator.free(map); } test "parse" { const map = \\..##....... \\#...#...#.. \\.#....#..#. \\..#.#...#.# \\.#...##..#. \\..#.##..... \\.#.#.#....# \\.#........# \\#.##...#... \\#...##....# \\.#..#...#.# \\ ; const allocator = testing.allocator; const parsed = try parseMap(allocator, map); defer freeMap(allocator, parsed); try testing.expectEqual(parsed[0][0], .open); try testing.expectEqual(parsed[0][2], .tree); } fn countTrees(map: []const []const Square) u32 { var result: u32 = 0; var y: usize = 0; var x: usize = 0; while (y < map.len) : ({ y += 1; x = (x + 3) % map[0].len; }) { const square = map[y][x]; if (square == .tree) result += 1; } return result; } test "count trees" { const map = \\..##....... \\#...#...#.. \\.#....#..#. \\..#.#...#.# \\.#...##..#. \\..#.##..... \\.#.#.#....# \\.#........# \\#.##...#... \\#...##....# \\.#..#...#.# \\ ; const allocator = testing.allocator; const parsed = try parseMap(allocator, map); defer freeMap(allocator, parsed); try testing.expectEqual(@as(u32, 7), countTrees(parsed)); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = &gpa.allocator; var file = try std.fs.cwd().openFile(input_file, .{}); defer file.close(); const reader = file.reader(); const content = try reader.readAllAlloc(allocator, 4 * 1024 * 1024); defer allocator.free(content); const map = try parseMap(allocator, content); defer freeMap(allocator, map); const count = countTrees(map); std.debug.print("trees encountered: {}\n", .{count}); }
src/03.zig
const std = @import("std"); const util = @import("util.zig"); const testing = std.testing; const mem = std.mem; const net = std.net; const LF = "\n"; const CRLF = "\r" ++ LF; const WS = CRLF ++ " "; const BUFFER_SIZE = 4 * 1024; const DEFAULT_HEADERS = &[_]Header{}; const DEFAULT_BODY = ""; const DEFAULT_STATUS = 404; const DEFAULT_RESPONSE = Resp{ .status = DEFAULT_STATUS, .headers = DEFAULT_HEADERS, .body = DEFAULT_BODY }; pub const Error = error{ BadRequest, MethodNotImplemented, InternalError, UnsupportedHTTPVersion }; pub const Method = enum { Get, Post }; pub const Header = struct { key: []const u8, value: []const u8 }; pub const Req = struct { method: Method, path: []const u8, http_version: []const u8, headers: []const Header, body: ?[]const u8, }; pub const Resp = struct { const Self = @This(); status: u10, headers: []const Header = .{}, body: []const u8 = .{}, pub fn toRaw(self: Self, allocator: *mem.Allocator) ![]const u8 { var headers = try allocator.alloc(u8, 0); defer allocator.free(headers); // headers for (self.headers) |h| { const header_raw = &[_][]const u8{ headers, h.key, ": ", h.value, CRLF }; const total_len = util.totalLen(u8, header_raw); var index = headers.len; headers = try allocator.realloc(headers, headers.len + total_len); for (header_raw) |slice| { mem.copy(u8, headers[index..], slice); index += slice.len; } } // response // zig fmt: off return std.mem.concat(allocator, u8, &.{ // status line "HTTP/1.1 ", util.concatCodeWithMessage(self.status), LF, // headers headers, CRLF, // body self.body, }); // zig fmt: on } }; pub const RouteHandler = fn (Req, *Resp) void; pub const Route = struct { const Self = @This(); method: Method, path: []const u8, handler: RouteHandler, pub fn create(method: Method, path: []const u8, handler: RouteHandler) Self { return Self{ .method = method, .path = path, .handler = handler }; } pub fn get(path: []const u8, handler: RouteHandler) Self { return create(.Get, path, handler); } pub fn post(path: []const u8, handler: RouteHandler) Self { return create(.Post, path, handler); } }; pub const Zepo = struct { const Self = @This(); allocator: *mem.Allocator, routes: []const Route, server: net.StreamServer, cc: ?net.StreamServer.Connection, // current connection (cc) pub fn init(allocator: *mem.Allocator, routes: []const Route) Self { // zig fmt: off return Self{ .allocator = allocator, .server = net.StreamServer.init(.{ .reuse_address = true }), .routes = routes, .cc = null }; // zig fmt: on } pub fn deinit(self: *Self) void { self.server.deinit(); } /// NOTE: free headers fn parseRequest(self: Self, req: []const u8) !Req { if (req.len == 0) return Error.BadRequest; var request_line = try reader.readUntilDelimiterAlloc(&context.memory.allocator, '\n', 65536); var all_lines = mem.split(u8, req, CRLF); // Reading First Line const first_line = all_lines.next() orelse return Error.BadRequest; var fl_attrs = mem.split(u8, first_line, " "); // Parse Method const method_str = fl_attrs.next() orelse return Error.BadRequest; const method: Method = mb: { if (mem.eql(u8, method_str, "GET")) break :mb .Get else if (mem.eql(u8, method_str, "POST")) break :mb .Post else return Error.MethodNotImplemented; }; // Parse Path const path = fl_attrs.next() orelse return Error.BadRequest; if (path[0] != '/') return Error.BadRequest; // Parse Http Version var hv = mem.split(u8, fl_attrs.next() orelse return Error.BadRequest, "/"); const http_valid = hv.next() orelse return Error.BadRequest; if (!mem.eql(u8, http_valid, "HTTP")) return Error.BadRequest; const http_version = hv.next() orelse return Error.BadRequest; if (!mem.eql(u8, http_version, "1.1")) return Error.UnsupportedHTTPVersion; // Parse Headers var header_list = std.ArrayList(Header).init(self.allocator); while (all_lines.next()) |header_line| { if (header_line.len == 0) break; var hm = mem.split(u8, header_line, ":"); const key = hm.next() orelse continue; const value = hm.rest(); try header_list.append(.{ .key = mem.trim(u8, key, WS), .value = mem.trim(u8, value, WS) }); } // Body const body = if (method == .Post) all_lines.next() else null; // skip other methods body // zig fmt: off return Req{ .method = method, .path = path, .http_version = http_version, .headers = header_list.toOwnedSlice(), .body = body }; // zig fmt: on } fn sendRespA(self: Self, status: u10) !void { try self.sendRespF(status, DEFAULT_HEADERS, util.concatCodeWithMessage(status)); } fn sendRespF(self: Self, status: u10, headers: ?[]const Header, body: ?[]const u8) !void { try self.sendResp(Resp{ .status = status, .headers = headers orelse DEFAULT_HEADERS, .body = body orelse DEFAULT_BODY }); } // Send Response // directly convert Resp struct to raw and write to current connection (cc) fn sendResp(self: Self, resp: Resp) !void { const resp_raw = try resp.toRaw(self.allocator); defer self.allocator.free(resp_raw); try self.cc.?.stream.writer().writeAll(resp_raw); } // Handle Connections pub fn handle(self: *Self) !void { var buf: [BUFFER_SIZE]u8 = undefined; var req_raw = try self.allocator.alloc(u8, 0); defer self.allocator.free(req_raw); while (true) { errdefer self.sendRespA(503) catch {}; // Accept Connection const conn = try self.server.accept(); defer conn.stream.close(); self.cc = conn; // Read Request var last_read_len: usize = 0; while (true) { // Request Length var read_len = try conn.stream.reader().read(&buf); // Allocate enough memory for request req_raw = try self.allocator.realloc(req_raw, req_raw.len + read_len); // Copy buffer into request variable mem.copy(u8, req_raw[last_read_len..], buf[0..read_len]); last_read_len = read_len; if (read_len < buf.len) break; } // Parse Request const req = self.parseRequest(req_raw) catch |err| { switch (err) { Error.BadRequest => { try self.sendRespA(403); }, else => return err, } continue; }; defer self.allocator.free(req.headers); var resp = DEFAULT_RESPONSE; for (self.routes) |route| { if (mem.eql(u8, req.path, route.path)) { route.handler(req, &resp); break; } } // Send Response try self.sendResp(resp); } } // Start Listening address pub fn listen(self: *Self, address: net.Address) !void { try self.server.listen(address); try self.handle(); } }; test "Create Response" { const resp = Resp{ .status = 200, .headers = &[_]Header{Header{ .key = "Host", .value = "localhost" }}, .body = "im ok" }; var res = try resp.toRaw(testing.allocator); defer testing.allocator.free(res); try testing.expectEqualStrings("HTTP/1.1 200 OK\nHost: localhost\r\n\r\nim ok", res); } test "Parse Request" { var server = Zepo.init(testing.allocator); var res = try server.parseRequest("POST / HTTP/1.1\r\nHost : localhost:3000\r\nContent-Length: 5\r\n\r\nhello"); defer testing.allocator.free(res.headers); try testing.expect(.Post == res.method); try testing.expectEqualStrings("1.1", res.http_version); try testing.expectEqualStrings("Host", res.headers[0].key); try testing.expectEqualStrings("localhost:3000", res.headers[0].value); try testing.expectEqualStrings("Content-Length", res.headers[1].key); try testing.expectEqualStrings("5", res.headers[1].value); try testing.expectEqualStrings("hello", res.body.?); }
zepo.zig
const std = @import("std"); const os = std.os; const net = std.net; const print = std.debug.print; const builtin = std.builtin; const Address = net.Address; const router = @import("./router.zig"); const Error = error{UnknownPacket}; /// The definition on an IP packet header. pub const IP4Hdr = packed struct { version: u4, internet_header_length: u4, type_of_service: u8, total_length: u16, identification: u16, flags: u4, frag_offset: u12, time_to_live: u8, protocol: u8, checksum: u16, source: [4]u8, destination: [4]u8, }; /// Is a generic handler for source-destination sockets. It can work with any /// type of socket that read() and write() system calls apply to. Works for a TUN interface. pub const L3Peer = struct { peer: router.Peer, buffer: []u8, const Self = @This(); const Packet = struct { buf: []u8, dst: Address, }; /// Initializes the peer with a given socket and a buffer for operating on /// socket handling. pub fn init(src_sock: i32, buf: []u8) Self { return .{ .buffer = buf, .peer = .{ .socket = src_sock, .address = net.Address.initIp4([4]u8{ 0, 0, 0, 0 }, 0), .handleFn = handle, }, }; } /// Reads from a socket that has data available and immediately writes it out to destination. fn handle(peer: *router.Peer, map: *router.AddressMap) router.Error!void { const self = @fieldParentPtr(L3Peer, "peer", peer); const read = os.read(peer.socket, self.buffer) catch return error.HandlerRead; const packet = isolatePacket(self.buffer[0..read]) catch |err| { switch (err) { error.UnknownPacket => return, else => return error.HandlerRead, } }; var dst_sock: ?i32 = undefined; if (map.lock.tryAcquire()) |lock| { dst_sock = map.map.get(packet.dst.any); lock.release(); } if (dst_sock) |sock| { try writePacket(sock, packet.buf); } } fn isolatePacket(buffer: []u8) Error!Packet { const hdr = @ptrCast(*IP4Hdr, buffer.ptr); if (hdr.version != 4) return error.UnknownPacket; const length = mem.toNative(u16, hdr.total_length, builtin.Endian.Big); return Packet{ .buf = buffer[0..length], .dst = Address.initIp4(hdr.destination, 0), }; } fn writePacket(sock: i32, packet: []u8) router.Error!void { var written: usize = 0; while (written < packet.len) { written += os.write(sock, packet[written..packet.len]) catch |err| { // No error to deal with the write contingency, use HandlerRead for now. switch (err) { error.AccessDenied => return error.HandlerRead, error.BrokenPipe => return error.HandlerRead, else => continue, } }; } } }; const testing = std.testing; const expect = testing.expect; const mem = std.mem; test "routes packet" { var data = [_]u8{ 0x45, // ver + hdr 0x00, // dcsp + ecn 0x00, 0x19, // total len 0x10, 0x10, // id 0x40, 0x00, // flags + frag offset 0x40, // ttl 0x06, // protocol 0x7c, 0x2c, // crc 192, 168, 1, 1, // src 172, 168, 2, 32, // dst 'H', 'e', 'l', 'l', 'o', // data }; const allocator = std.heap.page_allocator; const inPipes = try os.pipe(); defer os.close(inPipes[0]); defer os.close(inPipes[1]); const outPipes = try os.pipe(); defer os.close(outPipes[0]); defer os.close(outPipes[1]); var map = router.AddressMap.init(allocator); defer map.deinit(allocator); var addr = Address.initIp4([4]u8{ 172, 168, 2, 32 }, 0); try map.map.put(allocator, addr.any, outPipes[1]); const bytesWritten = try os.write(inPipes[1], data[0..]); expect(bytesWritten == 25); var buffer: [100]u8 = undefined; var peer = L3Peer.init(inPipes[0], buffer[0..]); try peer.peer.handle(&map); var outbuf: [100]u8 = undefined; const bytesRead = try os.read(outPipes[0], outbuf[0..]); expect(bytesRead == 25); } test "IP header parses" { var data = [_]u8{ 0x45, // ver + hdr 0x00, // dcsp + ecn 0x00, 0x19, // total len 0x10, 0x10, // id 0x40, 0x00, // flags + frag offset 0x40, // ttl 0x06, // protocol 0x7c, 0x2c, // crc 192, 168, 1, 1, // src 172, 168, 2, 32, // dst 'h', 'e', 'l', 'l', 'o', }; const hdr = @ptrCast(*IP4Hdr, &data); const want = [4]u8{ 172, 168, 2, 32 }; expect(mem.eql(u8, hdr.destination[0..], want[0..])); }
src/l3tun.zig
usingnamespace @import("c.zig"); const Mutex = @import("std").Mutex; const vertex_shader_source = @embedFile("shaders/vertex.glsl"); const fragment_shader_source = @embedFile("shaders/fragment.glsl"); /// Our texture quad const vertices = &[_]GLfloat{ 1, -1, 0.0, 1.0, 0.0, // bottom right 1, 1, 0.0, 1.0, 1.0, // top right -1, -1, 0.0, 0.0, 0.0, // bottom left -1, 1, 0.0, 0.0, 1.0, // top left }; /// Texture height const height: c_int = 32; /// Texture width const width: c_int = 64; /// Texture represents a quad texture that can be /// used to render the display of our 8chip video memory pub const Texture = struct { /// Vertex Array Object vao: GLuint, /// Vertex Buffer Object vbo: GLuint, /// Shader program shader_program: GLuint, /// texture id id: GLuint, /// texture pixel bytes in RGBA format /// The buffer is initialy filled by zeroes (making it transparant) buffer: [height * width * 4]u8 = [_]u8{255} ** width ** height ** 4, mutex: Mutex, /// Creates a new Texture using the given width and height pub fn init() !Texture { const fragment_id = try createShader(fragment_shader_source, GL_FRAGMENT_SHADER); const vertex_id = try createShader(vertex_shader_source, GL_VERTEX_SHADER); var program_id = glCreateProgram(); glAttachShader(program_id, vertex_id); glAttachShader(program_id, fragment_id); glLinkProgram(program_id); var ok: c_int = undefined; glGetProgramiv(program_id, GL_LINK_STATUS, &ok); if (ok == GL_FALSE) { return error.ProgramLinkFailed; } glValidateProgram(program_id); glDeleteShader(vertex_id); glDeleteShader(fragment_id); var vao: GLuint = undefined; var vbo: GLuint = undefined; var tex_id: GLuint = undefined; glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glGenTextures(1, &tex_id); glBindVertexArray(vao); // temporary empty buffer to load our gpu with a zeroes transparant texture var emptybuffer = [_]u8{0} ** width ** height ** 4; // create our texture glBindTexture(GL_TEXTURE_2D, tex_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, @ptrCast(*c_void, &emptybuffer), ); // our vertices buffer glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vertices.len * @sizeOf(GLfloat), @ptrCast(*const c_void, vertices), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * @sizeOf(GLfloat), null); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * @sizeOf(GLfloat), @intToPtr(*c_int, 3 * @sizeOf(GLfloat))); // unbind glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); return Texture{ .vao = vao, .vbo = vbo, .shader_program = program_id, .id = tex_id, .mutex = Mutex.init(), }; } /// Updates the texture based on the pixels of the given frame pub fn update(self: *Texture, frame: []u1) void { var lock = self.mutex.acquire(); defer lock.release(); // Perhaps write a more performant version of this var h = @intCast(usize, height); var i: usize = 0; var offset: usize = 0; var pixel: usize = 0; while (i < width) : (i += 1) { var j: usize = 0; while (j < height) : (j += 1) { self.buffer[offset + 3] = @intCast(u8, frame[pixel]) * 255; offset += 4; pixel += 1; } } } /// Renders the quad texture pub fn draw(self: *Texture) void { glUseProgram(self.shader_program); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, self.id); glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, @ptrCast(*c_void, &self.buffer), ); glBindVertexArray(self.vao); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } /// Destroys the vao, vbo, shader program, and then itself pub fn deinit(self: *Texture) void { glDeleteVertexArrays(1, &self.vao); glDeleteBuffers(1, &self.vbo); glDeleteShader(self.shader_program); self.mutex.deinit(); self.* = undefined; } }; /// Creates a new shader source fn createShader(source: []const u8, kind: GLenum) !GLuint { const id = glCreateShader(kind); const ptr: ?[*]const u8 = source.ptr; const len = @intCast(GLint, source.len); glShaderSource(id, 1, &ptr, null); glCompileShader(id); var ok: GLint = undefined; glGetShaderiv(id, GL_COMPILE_STATUS, &ok); if (ok != 0) return id; return error.ShaderCompilationFailed; }
src/texture.zig
const std = @import("std"); const Location = @This(); source: ?[]const u8 = null, line: u32, column: u32, pub fn min(a: Location, b: Location) Location { if (a.source != null and b.source != null) { if (!std.mem.eql(u8, a.source.?, b.source.?)) @panic("a and b must be from the same source file!"); } var loc = Location{ .line = undefined, .column = undefined, .source = a.source orelse b.source, }; if (a.line < b.line) { loc.line = a.line; loc.column = a.column; } else if (a.line > b.line) { loc.line = b.line; loc.column = b.column; } else { loc.line = a.line; loc.column = std.math.min(a.column, b.column); } return loc; } pub fn max(a: Location, b: Location) Location { if (a.source != null and b.source != null) { if (!std.mem.eql(u8, a.source.?, b.source.?)) @panic("a and b must be from the same source file!"); } var loc = Location{ .line = undefined, .column = undefined, .source = a.source orelse b.source, }; if (a.line > b.line) { loc.line = a.line; loc.column = a.column; } else if (a.line < b.line) { loc.line = b.line; loc.column = b.column; } else { loc.line = a.line; loc.column = std.math.max(a.column, b.column); } return loc; } pub fn adavance(self: *Location, str: []const u8) void { for (str) |c| { if (c == '\n') { self.line += 1; self.column = 1; } else { self.column += 1; } } } test "min" { const a = Location{ .source = "source", .line = 10, .column = 30 }; const b = Location{ .source = "source", .line = 10, .column = 40 }; const c = Location{ .source = "source", .line = 12, .column = 20 }; const ab = min(a, b); const bc = min(b, c); const ac = min(a, c); try std.testing.expectEqual(a.line, ab.line); try std.testing.expectEqual(a.column, ab.column); try std.testing.expectEqual(b.line, bc.line); try std.testing.expectEqual(b.column, bc.column); try std.testing.expectEqual(a.line, ac.line); try std.testing.expectEqual(a.column, ac.column); } test "max" { const a = Location{ .source = "source", .line = 10, .column = 30 }; const b = Location{ .source = "source", .line = 10, .column = 40 }; const c = Location{ .source = "source", .line = 12, .column = 20 }; const ab = max(a, b); const bc = max(b, c); const ac = max(a, c); try std.testing.expectEqual(b.line, ab.line); try std.testing.expectEqual(b.column, ab.column); try std.testing.expectEqual(c.line, bc.line); try std.testing.expectEqual(c.column, bc.column); try std.testing.expectEqual(c.line, ac.line); try std.testing.expectEqual(c.column, ac.column); }
src/Location.zig
const std = @import("std"); const mem = std.mem; const heap = std.heap; const fmt = std.fmt; const Allocator = std.mem.Allocator; const fe310 = @import("target/soc/fe310-g002.zig"); const prci = fe310.prci; const gpio = fe310.gpio; const uart = fe310.uart; const kmain = @import("main.zig").kmain; extern var __data_source_start: u8; extern var __data_source_end: u8; extern var __data_dest_start: u8; extern var __data_dest_end: u8; extern var __bss_start: u8; extern var __bss_end: u8; extern var __stack_end: u8; extern var __heap_start: u8; extern var __heap_end: u8; var _main_allocator: heap.LoggingAllocator(.debug, .err) = undefined; var main_allocator: Allocator = undefined; export fn _start() align(4) linksection(".text.start") callconv(.Naked) noreturn { // Set up stack and frame pointers. _ = asm volatile ( \\mv sp, %[initial_stack_pointer_address] \\mv fp, sp : : [initial_stack_pointer_address] "r" (@ptrToInt(&__stack_end)), : "sp", "fp" ); // Initialise data and BSS. const data_length = @ptrToInt(&__data_source_end) - @ptrToInt(&__data_source_start); const data_source = @ptrCast([*]volatile u8, &__data_source_start); const data_dest = @ptrCast([*]volatile u8, &__data_dest_start); for (data_source[0..data_length]) |b, i| data_dest[i] = b; const bss_length = @ptrToInt(&__bss_end) - @ptrToInt(&__bss_start); const bss_dest = @ptrCast([*]volatile u8, &__bss_start); for (bss_dest[0..bss_length]) |*b| b.* = 0; init_uart(); init_heap(); kmain(main_allocator); } fn init_uart() void { prci.useExternalCrystalOscillator(); gpio.setupUart0Gpio(); uart.Uart0.setBaudRate(); uart.Uart0.enableTx(); uart.Uart0.writeString("UART0 initialized\r\n"); } fn init_heap() void { const heap_size = @ptrToInt(&__heap_end) - @ptrToInt(&__heap_start); const heap_start_pointer = @ptrCast([*]u8, &__heap_start); const heap_slice = heap_start_pointer[0..heap_size]; // TODO: Use thread safe allocator? var heap_allocator = heap.FixedBufferAllocator.init(heap_slice); _main_allocator = heap.loggingAllocator(heap_allocator.allocator()); main_allocator = _main_allocator.allocator(); std.log.debug("Heap initialized", .{}); } pub fn log( comptime level: std.log.Level, comptime scope: @TypeOf(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { var buffer = [_]u8{0} ** 256; const level_txt = comptime level.asText(); const prefix2 = if (scope == .default) " " else "(" ++ @tagName(scope) ++ ") "; const string = fmt.bufPrint(&buffer, "[" ++ level_txt ++ "]" ++ prefix2 ++ format ++ "\r\n", args) catch return uart.Uart0.writeString("Log line did not fit in buffer!\r\n"); uart.Uart0.writeString(string); } pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace) noreturn { _ = stack_trace; uart.Uart0.writeString("\r\n!!! LUXOS PANIC !!!\r\n"); uart.Uart0.writeString(message); uart.Uart0.writeString("\r\n"); while (true) {} }
src/start.zig
const std = @import("std"); const core = @import("../index.zig"); const Coord = core.geometry.Coord; const Matrix = core.matrix.Matrix; pub const Floor = enum { unknown, dirt, marble, lava, hatch, stairs_down, }; pub const Wall = enum { unknown, air, dirt, stone, centaur_transformer, }; pub const Species = enum { human, orc, centaur, turtle, rhino, kangaroo, }; pub const TerrainChunk = struct { rel_position: Coord, matrix: Matrix(TerrainSpace), }; pub const TerrainSpace = struct { floor: Floor, wall: Wall, }; pub const Request = union(enum) { act: Action, rewind, }; pub const Action = union(enum) { wait, move: Coord, fast_move: Coord, attack: Coord, kick: Coord, }; pub const Response = union(enum) { /// this happens on startup (from your perspective) and on rewind load_state: PerceivedFrame, /// a typical turn happens stuff_happens: PerceivedHappening, /// ur doin it rong, and nothing happened. try again. reject_request, }; /// what you see each turn pub const PerceivedHappening = struct { /// Sequential order of simultaneous events. /// The last frame will always have all things with .none PerceivedActivity, /// unless you're are dead, in which case, the last frame includes your death. frames: []PerceivedFrame, }; /// Represents what you can observe with your eyes happening simultaneously. /// There can be multiple of these per turn. pub const PerceivedFrame = struct { terrain: TerrainChunk, self: PerceivedThing, others: []PerceivedThing, winning_score: ?i32, }; pub const ThingPosition = union(enum) { small: Coord, /// 0: head, 1: tail large: [2]Coord, }; pub const PerceivedThing = struct { rel_position: ThingPosition, species: Species, status_conditions: StatusConditions, has_shield: bool, activity: PerceivedActivity, }; pub const StatusConditions = u2; pub const StatusCondition_wounded_leg: StatusConditions = 0x1; /// you can't move. pub const StatusCondition_limping: StatusConditions = 0x2; pub const PerceivedActivity = union(enum) { none, movement: Coord, failed_movement: Coord, attack: Attack, kick: Coord, polymorph: Species, death, pub const Attack = struct { direction: Coord, distance: i32, }; }; /// Despite all the generic elegance of the Channel classes, /// this is what we use everywhere. pub const Socket = struct { in_stream: std.fs.File.Reader, out_stream: std.fs.File.Writer, pub fn init( in_stream: std.fs.File.Reader, out_stream: std.fs.File.Writer, ) Socket { return Socket{ .in_stream = in_stream, .out_stream = out_stream, }; } pub const FileInChannel = InChannel(std.fs.File.Reader); pub fn in(self: *Socket, allocator: *std.mem.Allocator) FileInChannel { return initInChannel(allocator, self.in_stream); } pub const FileOutChannel = OutChannel(std.fs.File.Writer); pub fn out(self: *Socket) FileOutChannel { return initOutChannel(self.out_stream); } pub fn close(self: *Socket, final_message: anytype) void { self.out().write(final_message) catch {}; self.out_stream.file.close(); // FIXME: revisit closing the in_stream when we have async/await maybe. } }; pub fn initOutChannel(out_stream: anytype) OutChannel(@TypeOf(out_stream)) { return OutChannel(@TypeOf(out_stream)).init(out_stream); } pub fn OutChannel(comptime Writer: type) type { return struct { const Self = @This(); stream: Writer, pub fn init(stream: Writer) Self { return Self{ .stream = stream }; } pub fn write(self: Self, x: anytype) !void { const T = @TypeOf(x); switch (@typeInfo(T)) { .Int => return self.writeInt(x), .Bool => return self.writeInt(@boolToInt(x)), .Enum => return self.writeInt(@enumToInt(x)), .Struct => |info| { inline for (info.fields) |field| { try self.write(@field(x, field.name)); } }, .Array => { for (x) |x_i| { try self.write(x_i); } }, .Pointer => |info| { switch (info.size) { .Slice => { try self.writeInt(x.len); for (x) |x_i| { try self.write(x_i); } }, else => @compileError("not supported: " ++ @typeName(T)), } }, .Union => |info| { const tag = @as(info.tag_type.?, x); try self.writeInt(@enumToInt(tag)); inline for (info.fields) |u_field| { if (tag == @field(T, u_field.name)) { // FIXME: this `if` is because inferred error sets require at least one error. return if (u_field.field_type != void) { try self.write(@field(x, u_field.name)); }; } } unreachable; }, .Optional => |info| { if (x) |child| { try self.write(true); try self.write(child); } else { try self.write(false); } }, else => @compileError("not supported: " ++ @typeName(T)), } } pub fn writeInt(self: Self, x: anytype) !void { const int_info = @typeInfo(@TypeOf(x)).Int; const T_aligned = @Type(std.builtin.TypeInfo{ .Int = .{ .signedness = int_info.signedness, .bits = @divTrunc(int_info.bits + 7, 8) * 8, }, }); try self.stream.writeIntLittle(T_aligned, x); } }; } pub fn initInChannel(allocator: *std.mem.Allocator, in_stream: anytype) InChannel(@TypeOf(in_stream)) { return InChannel(@TypeOf(in_stream)).init(allocator, in_stream); } pub fn InChannel(comptime Reader: type) type { return struct { const Self = @This(); allocator: *std.mem.Allocator, stream: Reader, pub fn init(allocator: *std.mem.Allocator, stream: Reader) Self { return Self{ .allocator = allocator, .stream = stream, }; } pub fn read(self: Self, comptime T: type) !T { switch (@typeInfo(T)) { .Int => return self.readInt(T), .Bool => return 0 != try self.readInt(u1), .Enum => return @intToEnum(T, try self.readInt(@TagType(T))), .Struct => |info| { var x: T = undefined; inline for (info.fields) |field| { @field(x, field.name) = try self.read(field.field_type); } return x; }, .Array => { var x: T = undefined; for (x) |*x_i| { x_i.* = try self.read(@TypeOf(x_i.*)); } return x; }, .Pointer => |info| { switch (info.size) { .Slice => { const len = try self.readInt(usize); var x = try self.allocator.alloc(info.child, len); for (x) |*x_i| { x_i.* = try self.read(info.child); } return x; }, else => @compileError("not supported: " ++ @typeName(T)), } }, .Union => |info| { const tag = try self.read(info.tag_type.?); inline for (info.fields) |u_field| { if (tag == @field(T, u_field.name)) { // FIXME: this `if` is because inferred error sets require at least one error. return @unionInit(T, u_field.name, if (u_field.field_type == void) {} else try self.read(u_field.field_type)); } } unreachable; }, .Optional => |info| { const non_null = try self.read(bool); if (!non_null) return null; return try self.read(info.child); }, else => @compileError("not supported: " ++ @typeName(T)), } } pub fn readInt(self: Self, comptime T: type) !T { const int_info = @typeInfo(T).Int; const T_aligned = @Type(std.builtin.TypeInfo{ .Int = .{ .signedness = int_info.signedness, .bits = @divTrunc(int_info.bits + 7, 8) * 8, }, }); const x_aligned = try self.stream.readIntLittle(T_aligned); return std.math.cast(T, x_aligned); } }; } pub fn deepClone(allocator: *std.mem.Allocator, x: anytype) (error{OutOfMemory})!@TypeOf(x) { // TODO: actually do it return x; } test "channel int" { var buffer = [_]u8{0} ** 256; var _out_stream = std.io.SliceOutStream.init(buffer[0..]); var _in_stream = std.io.SliceInStream.init(buffer[0..]); var out_channel = initOutChannel(&_out_stream.stream); var in_channel = initInChannel(std.debug.global_allocator, &_in_stream.stream); _out_stream.reset(); _in_stream.pos = 0; try out_channel.writeInt(u0(0)); // zero size try out_channel.writeInt(u3(2)); try out_channel.writeInt(i3(-2)); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 2, 0xfe })); std.testing.expect(0 == try in_channel.read(u0)); std.testing.expect(2 == try in_channel.read(u3)); std.testing.expect(-2 == try in_channel.read(i3)); _out_stream.reset(); _in_stream.pos = 0; try out_channel.writeInt(u64(3)); try out_channel.writeInt(i64(4)); try out_channel.writeInt(i64(-5)); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, })); std.testing.expect(3 == try in_channel.read(u64)); std.testing.expect(4 == try in_channel.read(i64)); std.testing.expect(-5 == try in_channel.read(i64)); _out_stream.reset(); _in_stream.pos = 0; try out_channel.writeInt(u64(0xffffffffffffffff)); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, })); std.testing.expect(0xffffffffffffffff == try in_channel.read(u64)); _out_stream.reset(); _in_stream.pos = 0; try out_channel.writeInt(i64(-0x8000000000000000)); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0x80, })); std.testing.expect(-0x8000000000000000 == try in_channel.read(i64)); } test "channel" { var buffer = [_]u8{0} ** 256; var _out_stream = std.io.SliceOutStream.init(buffer[0..]); var _in_stream = std.io.SliceInStream.init(buffer[0..]); var out_channel = initOutChannel(&_out_stream.stream); var in_channel = initInChannel(std.debug.global_allocator, &_in_stream.stream); // enum _out_stream.reset(); _in_stream.pos = 0; try out_channel.write(Wall.stone); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{@enumToInt(Wall.stone)})); std.testing.expect(Wall.stone == try in_channel.read(Wall)); // bool _out_stream.reset(); _in_stream.pos = 0; try out_channel.write(false); try out_channel.write(true); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 0, 1 })); std.testing.expect(false == try in_channel.read(bool)); std.testing.expect(true == try in_channel.read(bool)); // struct _out_stream.reset(); _in_stream.pos = 0; try out_channel.write(Coord{ .x = 1, .y = 2 }); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 1, 0, 0, 0, 2, 0, 0, 0, })); std.testing.expect((Coord{ .x = 1, .y = 2 }).equals(try in_channel.read(Coord))); // fixed-size array _out_stream.reset(); _in_stream.pos = 0; try out_channel.write([_]u8{ 1, 2, 3 }); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 1, 2, 3 })); std.testing.expect(std.mem.eql(u8, [_]u8{ 1, 2, 3 }, try in_channel.read([3]u8))); // slice _out_stream.reset(); _in_stream.pos = 0; try out_channel.write(([_]u8{ 1, 2, 3 })[0..]); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 3, 0, 0, 0, 0, 0, 0, 0, } ++ [_]u8{ 1, 2, 3 })); std.testing.expect(std.mem.eql(u8, [_]u8{ 1, 2, 3 }, try in_channel.read([]u8))); // union(enum) _out_stream.reset(); _in_stream.pos = 0; try out_channel.write(Action{ .move = Coord{ .x = 3, .y = -4 } }); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{@enumToInt(Action.move)} ++ [_]u8{ 3, 0, 0, 0, 0xfc, 0xff, 0xff, 0xff, })); std.testing.expect((Coord{ .x = 3, .y = -4 }).equals((try in_channel.read(Action)).move)); // nullable _out_stream.reset(); _in_stream.pos = 0; try out_channel.write((?u8)(null)); try out_channel.write((?u8)(5)); std.testing.expect(std.mem.eql(u8, _out_stream.getWritten(), [_]u8{ 0, 1, 5 })); std.testing.expect(null == try in_channel.read(?u8)); std.testing.expect(5 == (try in_channel.read(?u8)).?); }
src/core/protocol.zig
const c = @cImport({ @cInclude("cfl_window.h"); }); const widget = @import("widget.zig"); const group = @import("group.zig"); const enums = @import("enums.zig"); pub const Window = struct { inner: ?*c.Fl_Double_Window, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Window { const ptr = c.Fl_Double_Window_new(x, y, w, h, title); if (ptr == null) unreachable; return Window{ .inner = ptr, }; } pub fn raw(self: *Window) ?*c.Fl_Double_Window { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Double_Window) Window { return Window{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) Window { return Window{ .inner = @ptrCast(?*c.Fl_Double_Window, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) Window { return Window{ .inner = @ptrCast(?*c.Fl_Double_Window, ptr), }; } pub fn toVoidPtr(self: *Window) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const Window) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asGroup(self: *Window) group.Group { return group.Group{ .inner = @ptrCast(group.GroupPtr, self.inner), }; } pub fn handle(self: *Window, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Double_Window_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *Window, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Double_Window_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } pub fn sizeRange(self: *Window, min_w: i32, min_h: i32, max_w: i32, max_h: i32) void { return c.Fl_Double_Window_size_range(self.inner, min_w, min_h, max_w, max_h); } pub fn iconize(self: *Window) void { return c.Fl_Double_Window_iconize(self.inner); } pub fn freePosition(self: *Window) void { return c.Fl_Double_Window_free_position(self.inner); } pub fn setCursor(self: *Window, cursor: enums.Cursor) void { return c.Fl_Double_Window_set_cursor(self.inner, cursor); } pub fn makeModal(self: *Window, val: bool) void { return c.Fl_Double_Window_make_modal(self.inner, @boolToInt(val)); } pub fn fullscreen(self: *Window, val: bool) void { return c.Fl_Double_Window_fullscreen(self.inner, @boolToInt(val)); } }; test "" { @import("std").testing.refAllDecls(@This()); }
src/window.zig
const getty = @import("getty"); const std = @import("std"); const escape = @import("impl/formatter/details/escape.zig").escape; pub fn Serializer(comptime Writer: type, comptime Formatter: type) type { return struct { writer: Writer, formatter: Formatter, const Self = @This(); const impl = @"impl Serializer"(Self); pub fn init(writer: Writer, formatter: Formatter) Self { return .{ .writer = writer, .formatter = formatter, }; } pub usingnamespace getty.Serializer( *Self, impl.serializer.Ok, impl.serializer.Error, impl.serializer.MapSerialize, impl.serializer.SequenceSerialize, impl.serializer.StructSerialize, impl.serializer.TupleSerialize, impl.serializer.serializeBool, impl.serializer.serializeEnum, impl.serializer.serializeFloat, impl.serializer.serializeInt, impl.serializer.serializeMap, impl.serializer.serializeNull, impl.serializer.serializeSequence, impl.serializer.serializeSome, impl.serializer.serializeString, impl.serializer.serializeStruct, impl.serializer.serializeTuple, impl.serializer.serializeNull, ); }; } fn @"impl Serializer"(comptime Self: type) type { const S = Serialize(Self); return struct { pub const serializer = struct { pub const Ok = void; pub const Error = getty.ser.Error || error{ /// Failure to read or write bytes on an IO stream. Io, /// Input was syntactically incorrect. Syntax, /// Input data was semantically incorrect. /// /// For example, JSON containing a number is semantically incorrect /// when the type being deserialized into holds a String. Data, /// Prematurely reached the end of the input data. /// /// Callers that process streaming input may be interested in /// retrying the deserialization once more data is available. Eof, }; pub const MapSerialize = S; pub const SequenceSerialize = S; pub const StructSerialize = S; pub const TupleSerialize = S; pub fn serializeBool(self: *Self, value: bool) Error!Ok { self.formatter.writeBool(self.writer, value) catch return Error.Io; } pub fn serializeEnum(self: *Self, value: anytype) Error!Ok { serializeString(self, @tagName(value)) catch return Error.Io; } pub fn serializeFloat(self: *Self, value: anytype) Error!Ok { if (@TypeOf(value) != comptime_float and (std.math.isNan(value) or std.math.isInf(value))) { self.formatter.writeNull(self.writer) catch return Error.Io; } else { self.formatter.writeFloat(self.writer, value) catch return Error.Io; } } pub fn serializeInt(self: *Self, value: anytype) Error!Ok { self.formatter.writeInt(self.writer, value) catch return Error.Io; } pub fn serializeMap(self: *Self, length: ?usize) Error!MapSerialize { self.formatter.beginObject(self.writer) catch return Error.Io; if (length) |l| { if (l == 0) { self.formatter.endObject(self.writer) catch return Error.Io; return MapSerialize{ .ser = self, .state = .empty }; } } return MapSerialize{ .ser = self, .state = .first }; } pub fn serializeNull(self: *Self) Error!Ok { self.formatter.writeNull(self.writer) catch return Error.Io; } pub fn serializeSequence(self: *Self, length: ?usize) Error!SequenceSerialize { self.formatter.beginArray(self.writer) catch return Error.Io; if (length) |l| { if (l == 0) { self.formatter.endArray(self.writer) catch return Error.Io; return SequenceSerialize{ .ser = self, .state = .empty }; } } return SequenceSerialize{ .ser = self, .state = .first }; } pub fn serializeSome(self: *Self, value: anytype) Error!Ok { try getty.serialize(value, self.serializer()); } pub fn serializeString(self: *Self, value: anytype) Error!Ok { if (!std.unicode.utf8ValidateSlice(value)) { return Error.Syntax; } self.formatter.beginString(self.writer) catch return Error.Io; escape(value, self.writer, self.formatter) catch return Error.Syntax; self.formatter.endString(self.writer) catch return Error.Io; } pub fn serializeStruct(self: *Self, comptime name: []const u8, length: usize) Error!StructSerialize { _ = name; self.formatter.beginObject(self.writer) catch return Error.Io; if (length == 0) { self.formatter.endObject(self.writer) catch return Error.Io; return StructSerialize{ .ser = self, .state = .empty }; } return StructSerialize{ .ser = self, .state = .first }; } pub fn serializeTuple(self: *Self, length: ?usize) Error!TupleSerialize { return serializeSequence(self, length); } }; }; } fn Serialize(comptime Ser: type) type { return struct { ser: *Ser, state: enum { empty, first, rest }, const Self = @This(); const impl = @"impl Serialize"(Ser); pub usingnamespace getty.ser.MapSerialize( *Self, impl.mapSerialize.Ok, impl.mapSerialize.Error, impl.mapSerialize.serializeKey, impl.mapSerialize.serializeValue, impl.mapSerialize.end, ); pub usingnamespace getty.ser.SequenceSerialize( *Self, impl.sequenceSerialize.Ok, impl.sequenceSerialize.Error, impl.sequenceSerialize.serializeElement, impl.sequenceSerialize.end, ); pub usingnamespace getty.ser.StructSerialize( *Self, impl.structSerialize.Ok, impl.structSerialize.Error, impl.structSerialize.serializeField, impl.mapSerialize.end, ); pub usingnamespace getty.ser.TupleSerialize( *Self, impl.sequenceSerialize.Ok, impl.sequenceSerialize.Error, impl.sequenceSerialize.serializeElement, impl.sequenceSerialize.end, ); }; } fn @"impl Serialize"(comptime Ser: type) type { const Self = Serialize(Ser); return struct { pub const mapSerialize = struct { pub const Ok = @"impl Serializer"(Ser).serializer.Ok; pub const Error = @"impl Serializer"(Ser).serializer.Error; // TODO: serde-json passes in MapKeySerializer instead of self to // `getty.serialize`. This works though, so should we change it? pub fn serializeKey(self: *Self, key: anytype) Error!void { self.ser.formatter.beginObjectKey(self.ser.writer, self.state == .first) catch return Error.Io; try getty.serialize(key, self.ser.serializer()); self.ser.formatter.endObjectKey(self.ser.writer) catch return Error.Io; self.state = .rest; } pub fn serializeValue(self: *Self, value: anytype) Error!void { self.ser.formatter.beginObjectValue(self.ser.writer) catch return Error.Io; try getty.serialize(value, self.ser.serializer()); self.ser.formatter.endObjectValue(self.ser.writer) catch return Error.Io; } pub fn end(self: *Self) Error!Ok { if (self.state != .empty) { self.ser.formatter.endObject(self.ser.writer) catch return Error.Io; } } }; pub const sequenceSerialize = struct { pub const Ok = @"impl Serializer"(Ser).serializer.Ok; pub const Error = @"impl Serializer"(Ser).serializer.Error; pub fn serializeElement(self: *Self, value: anytype) Error!Ok { self.ser.formatter.beginArrayValue(self.ser.writer, self.state == .first) catch return Error.Io; try getty.serialize(value, self.ser.serializer()); self.ser.formatter.endArrayValue(self.ser.writer) catch return Error.Io; self.state = .rest; } pub fn end(self: *Self) Error!Ok { if (self.state != .empty) { self.ser.formatter.endArray(self.ser.writer) catch return Error.Io; } } }; pub const structSerialize = struct { pub const Ok = @"impl Serializer"(Ser).serializer.Ok; pub const Error = @"impl Serializer"(Ser).serializer.Error; pub fn serializeField(self: *Self, comptime key: []const u8, value: anytype) Error!void { var k = blk: { var k: [key.len + 2]u8 = undefined; k[0] = '"'; k[k.len - 1] = '"'; var fbs = std.io.fixedBufferStream(&k); fbs.seekTo(1) catch unreachable; // UNREACHABLE: The length of `k` is guaranteed to be > 1. fbs.writer().writeAll(key) catch return error.Io; break :blk k; }; self.ser.formatter.beginObjectKey(self.ser.writer, self.state == .first) catch return error.Io; self.ser.formatter.writeRawFragment(self.ser.writer, &k) catch return error.Io; self.ser.formatter.endObjectKey(self.ser.writer) catch return error.Io; try self.mapSerialize().serializeValue(value); self.state = .rest; } }; }; }
src/ser/serializer.zig
usingnamespace @import("bits.zig"); // PM pub const PM_REMOVE = 0x0001; pub const PM_NOREMOVE = 0x0000; pub const PM_NOYIELD = 0x0002; // WM pub const WM_NULL = 0x0000; pub const WM_CREATE = 0x0001; pub const WM_DESTROY = 0x0002; pub const WM_MOVE = 0x0003; pub const WM_SIZE = 0x0005; pub const WM_ACTIVATE = 0x0006; pub const WM_PAINT = 0x000F; pub const WM_CLOSE = 0x0010; pub const WM_QUIT = 0x0012; pub const WM_SETFOCUS = 0x0007; pub const WM_KILLFOCUS = 0x0008; pub const WM_ENABLE = 0x000A; pub const WM_SETREDRAW = 0x000B; pub const WM_SYSCOLORCHANGE = 0x0015; pub const WM_SHOWWINDOW = 0x0018; pub const WM_WINDOWPOSCHANGING = 0x0046; pub const WM_WINDOWPOSCHANGED = 0x0047; pub const WM_POWER = 0x0048; pub const WM_CONTEXTMENU = 0x007B; pub const WM_STYLECHANGING = 0x007C; pub const WM_STYLECHANGED = 0x007D; pub const WM_DISPLAYCHANGE = 0x007E; pub const WM_GETICON = 0x007F; pub const WM_SETICON = 0x0080; pub const WM_INPUT_DEVICE_CHANGE = 0x00fe; pub const WM_INPUT = 0x00FF; pub const WM_KEYFIRST = 0x0100; pub const WM_KEYDOWN = 0x0100; pub const WM_KEYUP = 0x0101; pub const WM_CHAR = 0x0102; pub const WM_DEADCHAR = 0x0103; pub const WM_SYSKEYDOWN = 0x0104; pub const WM_SYSKEYUP = 0x0105; pub const WM_SYSCHAR = 0x0106; pub const WM_SYSDEADCHAR = 0x0107; pub const WM_UNICHAR = 0x0109; pub const WM_KEYLAST = 0x0109; pub const WM_COMMAND = 0x0111; pub const WM_SYSCOMMAND = 0x0112; pub const WM_TIMER = 0x0113; pub const WM_MOUSEFIRST = 0x0200; pub const WM_MOUSEMOVE = 0x0200; pub const WM_LBUTTONDOWN = 0x0201; pub const WM_LBUTTONUP = 0x0202; pub const WM_LBUTTONDBLCLK = 0x0203; pub const WM_RBUTTONDOWN = 0x0204; pub const WM_RBUTTONUP = 0x0205; pub const WM_RBUTTONDBLCLK = 0x0206; pub const WM_MBUTTONDOWN = 0x0207; pub const WM_MBUTTONUP = 0x0208; pub const WM_MBUTTONDBLCLK = 0x0209; pub const WM_MOUSEWHEEL = 0x020A; pub const WM_XBUTTONDOWN = 0x020B; pub const WM_XBUTTONUP = 0x020C; pub const WM_XBUTTONDBLCLK = 0x020D; // WA pub const WA_INACTIVE = 0; pub const WA_ACTIVE = 0x0006; // WS pub const WS_OVERLAPPED = 0x00000000; pub const WS_CAPTION = 0x00C00000; pub const WS_SYSMENU = 0x00080000; pub const WS_THICKFRAME = 0x00040000; pub const WS_MINIMIZEBOX = 0x00020000; pub const WS_MAXIMIZEBOX = 0x00010000; // PFD pub const PFD_DRAW_TO_WINDOW = 0x00000004; pub const PFD_SUPPORT_OPENGL = 0x00000020; pub const PFD_DOUBLEBUFFER = 0x00000001; pub const PFD_MAIN_PLANE = 0; pub const PFD_TYPE_RGBA = 0; // CS pub const CS_HREDRAW = 0x0002; pub const CS_VREDRAW = 0x0001; pub const CS_OWNDC = 0x0020; // SW pub const SW_HIDE = 0; pub const SW_SHOW = 5; pub const WNDPROC = fn (HWND, UINT, WPARAM, LPARAM) callconv(WINAPI) LRESULT; pub const WNDCLASSEXA = extern struct { cbSize: UINT = @sizeOf(WNDCLASSEXA), style: UINT, lpfnWndProc: WNDPROC, cbClsExtra: i32, cbWndExtra: i32, hInstance: HINSTANCE, hIcon: ?HICON, hCursor: ?HCURSOR, hbrBackground: ?HBRUSH, lpszMenuName: ?LPCSTR, lpszClassName: LPCSTR, hIconSm: ?HICON, }; pub const POINT = extern struct { x: c_long, y: c_long }; pub const MSG = extern struct { hWnd: ?HWND, message: UINT, wParam: WPARAM, lParam: LPARAM, time: DWORD, pt: POINT, lPrivate: DWORD, }; pub extern "user32" fn CreateWindowExA( dwExStyle: DWORD, lpClassName: LPCSTR, lpWindowName: LPCSTR, dwStyle: DWORD, X: i32, Y: i32, nWidth: i32, nHeight: i32, hWindParent: ?HWND, hMenu: ?HMENU, hInstance: HINSTANCE, lpParam: ?LPVOID, ) callconv(WINAPI) ?HWND; pub extern "user32" fn RegisterClassExA(*const WNDCLASSEXA) callconv(WINAPI) c_ushort; pub extern "user32" fn DefWindowProcA(HWND, Msg: UINT, WPARAM, LPARAM) callconv(WINAPI) LRESULT; pub extern "user32" fn ShowWindow(hWnd: ?HWND, nCmdShow: i32) callconv(WINAPI) bool; pub extern "user32" fn UpdateWindow(hWnd: ?HWND) callconv(WINAPI) bool; pub extern "user32" fn GetDC(hWnd: ?HWND) callconv(WINAPI) ?HDC; pub extern "user32" fn PeekMessageA( lpMsg: ?*MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, wRemoveMsg: UINT, ) callconv(WINAPI) bool; pub extern "user32" fn GetMessageA( lpMsg: ?*MSG, hWnd: ?HWND, wMsgFilterMin: UINT, wMsgFilterMax: UINT, ) callconv(WINAPI) bool; pub extern "user32" fn TranslateMessage(lpMsg: *const MSG) callconv(WINAPI) bool; pub extern "user32" fn DispatchMessageA(lpMsg: *const MSG) callconv(WINAPI) LRESULT; pub extern "user32" fn PostQuitMessage(nExitCode: i32) callconv(WINAPI) void;
lib/std/os/windows/user32.zig
const std = @import("../std.zig"); const build = std.build; const Step = build.Step; const Builder = build.Builder; const WriteFileStep = build.WriteFileStep; const LibExeObjStep = build.LibExeObjStep; const CheckFileStep = build.CheckFileStep; const fs = std.fs; const mem = std.mem; const CrossTarget = std.zig.CrossTarget; pub const TranslateCStep = struct { step: Step, builder: *Builder, source: build.FileSource, include_dirs: std.ArrayList([]const u8), output_dir: ?[]const u8, out_basename: []const u8, target: CrossTarget = CrossTarget{}, pub fn create(builder: *Builder, source: build.FileSource) *TranslateCStep { const self = builder.allocator.create(TranslateCStep) catch unreachable; self.* = TranslateCStep{ .step = Step.init(.TranslateC, "translate-c", builder.allocator, make), .builder = builder, .source = source, .include_dirs = std.ArrayList([]const u8).init(builder.allocator), .output_dir = null, .out_basename = undefined, }; source.addStepDependencies(&self.step); return self; } /// Unless setOutputDir was called, this function must be called only in /// the make step, from a step that has declared a dependency on this one. /// To run an executable built with zig build, use `run`, or create an install step and invoke it. pub fn getOutputPath(self: *TranslateCStep) []const u8 { return fs.path.join( self.builder.allocator, &[_][]const u8{ self.output_dir.?, self.out_basename }, ) catch unreachable; } pub fn setTarget(self: *TranslateCStep, target: CrossTarget) void { self.target = target; } /// Creates a step to build an executable from the translated source. pub fn addExecutable(self: *TranslateCStep) *LibExeObjStep { return self.builder.addExecutableSource("translated_c", @as(build.FileSource, .{ .translate_c = self })); } pub fn addIncludeDir(self: *TranslateCStep, include_dir: []const u8) void { self.include_dirs.append(include_dir) catch unreachable; } pub fn addCheckFile(self: *TranslateCStep, expected_matches: []const []const u8) *CheckFileStep { return CheckFileStep.create(self.builder, .{ .translate_c = self }, expected_matches); } fn make(step: *Step) !void { const self = @fieldParentPtr(TranslateCStep, "step", step); var argv_list = std.ArrayList([]const u8).init(self.builder.allocator); try argv_list.append(self.builder.zig_exe); try argv_list.append("translate-c"); try argv_list.append("-lc"); try argv_list.append("--enable-cache"); if (!self.target.isNative()) { try argv_list.append("-target"); try argv_list.append(try self.target.zigTriple(self.builder.allocator)); } for (self.include_dirs.items) |include_dir| { try argv_list.append("-I"); try argv_list.append(include_dir); } try argv_list.append(self.source.getPath(self.builder)); const output_path_nl = try self.builder.execFromStep(argv_list.items, &self.step); const output_path = mem.trimRight(u8, output_path_nl, "\r\n"); self.out_basename = fs.path.basename(output_path); if (self.output_dir) |output_dir| { const full_dest = try fs.path.join(self.builder.allocator, &[_][]const u8{ output_dir, self.out_basename }); try self.builder.updateFile(output_path, full_dest); } else { self.output_dir = fs.path.dirname(output_path).?; } } };
lib/std/build/translate_c.zig
const Emit = @This(); const std = @import("std"); const assert = std.debug.assert; const bits = @import("bits.zig"); const abi = @import("abi.zig"); const leb128 = std.leb; const link = @import("../../link.zig"); const log = std.log.scoped(.codegen); const math = std.math; const mem = std.mem; const testing = std.testing; const Air = @import("../../Air.zig"); const Allocator = mem.Allocator; const CodeGen = @import("CodeGen.zig"); const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput; const DW = std.dwarf; const Encoder = bits.Encoder; const ErrorMsg = Module.ErrorMsg; const MCValue = @import("CodeGen.zig").MCValue; const Mir = @import("Mir.zig"); const Module = @import("../../Module.zig"); const Instruction = bits.Instruction; const Register = bits.Register; const Type = @import("../../type.zig").Type; mir: Mir, bin_file: *link.File, debug_output: DebugInfoOutput, target: *const std.Target, err_msg: ?*ErrorMsg = null, src_loc: Module.SrcLoc, code: *std.ArrayList(u8), prev_di_line: u32, prev_di_column: u32, /// Relative to the beginning of `code`. prev_di_pc: usize, code_offset_mapping: std.AutoHashMapUnmanaged(Mir.Inst.Index, usize) = .{}, relocs: std.ArrayListUnmanaged(Reloc) = .{}, const InnerError = error{ OutOfMemory, EmitFail, }; const Reloc = struct { /// Offset of the instruction. source: usize, /// Target of the relocation. target: Mir.Inst.Index, /// Offset of the relocation within the instruction. offset: usize, /// Length of the instruction. length: u5, }; pub fn lowerMir(emit: *Emit) InnerError!void { const mir_tags = emit.mir.instructions.items(.tag); for (mir_tags) |tag, index| { const inst = @intCast(u32, index); try emit.code_offset_mapping.putNoClobber(emit.bin_file.allocator, inst, emit.code.items.len); switch (tag) { .adc => try emit.mirArith(.adc, inst), .add => try emit.mirArith(.add, inst), .sub => try emit.mirArith(.sub, inst), .xor => try emit.mirArith(.xor, inst), .@"and" => try emit.mirArith(.@"and", inst), .@"or" => try emit.mirArith(.@"or", inst), .sbb => try emit.mirArith(.sbb, inst), .cmp => try emit.mirArith(.cmp, inst), .mov => try emit.mirArith(.mov, inst), .adc_mem_imm => try emit.mirArithMemImm(.adc, inst), .add_mem_imm => try emit.mirArithMemImm(.add, inst), .sub_mem_imm => try emit.mirArithMemImm(.sub, inst), .xor_mem_imm => try emit.mirArithMemImm(.xor, inst), .and_mem_imm => try emit.mirArithMemImm(.@"and", inst), .or_mem_imm => try emit.mirArithMemImm(.@"or", inst), .sbb_mem_imm => try emit.mirArithMemImm(.sbb, inst), .cmp_mem_imm => try emit.mirArithMemImm(.cmp, inst), .mov_mem_imm => try emit.mirArithMemImm(.mov, inst), .adc_scale_src => try emit.mirArithScaleSrc(.adc, inst), .add_scale_src => try emit.mirArithScaleSrc(.add, inst), .sub_scale_src => try emit.mirArithScaleSrc(.sub, inst), .xor_scale_src => try emit.mirArithScaleSrc(.xor, inst), .and_scale_src => try emit.mirArithScaleSrc(.@"and", inst), .or_scale_src => try emit.mirArithScaleSrc(.@"or", inst), .sbb_scale_src => try emit.mirArithScaleSrc(.sbb, inst), .cmp_scale_src => try emit.mirArithScaleSrc(.cmp, inst), .mov_scale_src => try emit.mirArithScaleSrc(.mov, inst), .adc_scale_dst => try emit.mirArithScaleDst(.adc, inst), .add_scale_dst => try emit.mirArithScaleDst(.add, inst), .sub_scale_dst => try emit.mirArithScaleDst(.sub, inst), .xor_scale_dst => try emit.mirArithScaleDst(.xor, inst), .and_scale_dst => try emit.mirArithScaleDst(.@"and", inst), .or_scale_dst => try emit.mirArithScaleDst(.@"or", inst), .sbb_scale_dst => try emit.mirArithScaleDst(.sbb, inst), .cmp_scale_dst => try emit.mirArithScaleDst(.cmp, inst), .mov_scale_dst => try emit.mirArithScaleDst(.mov, inst), .adc_scale_imm => try emit.mirArithScaleImm(.adc, inst), .add_scale_imm => try emit.mirArithScaleImm(.add, inst), .sub_scale_imm => try emit.mirArithScaleImm(.sub, inst), .xor_scale_imm => try emit.mirArithScaleImm(.xor, inst), .and_scale_imm => try emit.mirArithScaleImm(.@"and", inst), .or_scale_imm => try emit.mirArithScaleImm(.@"or", inst), .sbb_scale_imm => try emit.mirArithScaleImm(.sbb, inst), .cmp_scale_imm => try emit.mirArithScaleImm(.cmp, inst), .mov_scale_imm => try emit.mirArithScaleImm(.mov, inst), .adc_mem_index_imm => try emit.mirArithMemIndexImm(.adc, inst), .add_mem_index_imm => try emit.mirArithMemIndexImm(.add, inst), .sub_mem_index_imm => try emit.mirArithMemIndexImm(.sub, inst), .xor_mem_index_imm => try emit.mirArithMemIndexImm(.xor, inst), .and_mem_index_imm => try emit.mirArithMemIndexImm(.@"and", inst), .or_mem_index_imm => try emit.mirArithMemIndexImm(.@"or", inst), .sbb_mem_index_imm => try emit.mirArithMemIndexImm(.sbb, inst), .cmp_mem_index_imm => try emit.mirArithMemIndexImm(.cmp, inst), .mov_mem_index_imm => try emit.mirArithMemIndexImm(.mov, inst), .mov_sign_extend => try emit.mirMovSignExtend(inst), .mov_zero_extend => try emit.mirMovZeroExtend(inst), .movabs => try emit.mirMovabs(inst), .fisttp => try emit.mirFisttp(inst), .fld => try emit.mirFld(inst), .lea => try emit.mirLea(inst), .lea_pie => try emit.mirLeaPie(inst), .shl => try emit.mirShift(.shl, inst), .sal => try emit.mirShift(.sal, inst), .shr => try emit.mirShift(.shr, inst), .sar => try emit.mirShift(.sar, inst), .imul => try emit.mirMulDiv(.imul, inst), .mul => try emit.mirMulDiv(.mul, inst), .idiv => try emit.mirMulDiv(.idiv, inst), .div => try emit.mirMulDiv(.div, inst), .imul_complex => try emit.mirIMulComplex(inst), .cwd => try emit.mirCwd(inst), .push => try emit.mirPushPop(.push, inst), .pop => try emit.mirPushPop(.pop, inst), .jmp => try emit.mirJmpCall(.jmp_near, inst), .call => try emit.mirJmpCall(.call_near, inst), .cond_jmp_greater_less, .cond_jmp_above_below, .cond_jmp_eq_ne, => try emit.mirCondJmp(tag, inst), .cond_set_byte_greater_less, .cond_set_byte_above_below, .cond_set_byte_eq_ne, .cond_set_byte_overflow, => try emit.mirCondSetByte(tag, inst), .cond_mov_eq => try emit.mirCondMov(.cmove, inst), .cond_mov_lt => try emit.mirCondMov(.cmovl, inst), .cond_mov_below => try emit.mirCondMov(.cmovb, inst), .ret => try emit.mirRet(inst), .syscall => try emit.mirSyscall(), .@"test" => try emit.mirTest(inst), .interrupt => try emit.mirInterrupt(inst), .nop => try emit.mirNop(), .call_extern => try emit.mirCallExtern(inst), .dbg_line => try emit.mirDbgLine(inst), .dbg_prologue_end => try emit.mirDbgPrologueEnd(inst), .dbg_epilogue_begin => try emit.mirDbgEpilogueBegin(inst), .push_regs_from_callee_preserved_regs => try emit.mirPushPopRegsFromCalleePreservedRegs(.push, inst), .pop_regs_from_callee_preserved_regs => try emit.mirPushPopRegsFromCalleePreservedRegs(.pop, inst), else => { return emit.fail("Implement MIR->Emit lowering for x86_64 for pseudo-inst: {s}", .{tag}); }, } } try emit.fixupRelocs(); } pub fn deinit(emit: *Emit) void { emit.relocs.deinit(emit.bin_file.allocator); emit.code_offset_mapping.deinit(emit.bin_file.allocator); emit.* = undefined; } fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError { @setCold(true); assert(emit.err_msg == null); emit.err_msg = try ErrorMsg.create(emit.bin_file.allocator, emit.src_loc, format, args); return error.EmitFail; } fn fixupRelocs(emit: *Emit) InnerError!void { // TODO this function currently assumes all relocs via JMP/CALL instructions are 32bit in size. // This should be reversed like it is done in aarch64 MIR emit code: start with the smallest // possible resolution, i.e., 8bit, and iteratively converge on the minimum required resolution // until the entire decl is correctly emitted with all JMP/CALL instructions within range. for (emit.relocs.items) |reloc| { const target = emit.code_offset_mapping.get(reloc.target) orelse return emit.fail("JMP/CALL relocation target not found!", .{}); const disp = @intCast(i32, @intCast(i64, target) - @intCast(i64, reloc.source + reloc.length)); mem.writeIntLittle(i32, emit.code.items[reloc.offset..][0..4], disp); } } fn mirInterrupt(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .interrupt); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => return lowerToZoEnc(.int3, emit.code), else => return emit.fail("TODO handle variant 0b{b} of interrupt instruction", .{ops.flags}), } } fn mirNop(emit: *Emit) InnerError!void { return lowerToZoEnc(.nop, emit.code); } fn mirSyscall(emit: *Emit) InnerError!void { return lowerToZoEnc(.syscall, emit.code); } fn mirPushPop(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { // PUSH/POP reg return lowerToOEnc(tag, ops.reg1, emit.code); }, 0b01 => { // PUSH/POP r/m64 const imm = emit.mir.instructions.items(.data)[inst].imm; const ptr_size: Memory.PtrSize = switch (immOpSize(imm)) { 16 => .word_ptr, else => .qword_ptr, }; return lowerToMEnc(tag, RegisterOrMemory.mem(ptr_size, .{ .disp = imm, .base = ops.reg1, }), emit.code); }, 0b10 => { // PUSH imm32 assert(tag == .push); const imm = emit.mir.instructions.items(.data)[inst].imm; return lowerToIEnc(.push, imm, emit.code); }, 0b11 => unreachable, } } fn mirPushPopRegsFromCalleePreservedRegs(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const payload = emit.mir.instructions.items(.data)[inst].payload; const data = emit.mir.extraData(Mir.RegsToPushOrPop, payload).data; const regs = data.regs; var disp: u32 = data.disp + 8; for (abi.callee_preserved_regs) |reg, i| { if ((regs >> @intCast(u5, i)) & 1 == 0) continue; if (tag == .push) { try lowerToMrEnc(.mov, RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, -@intCast(i32, disp)), .base = ops.reg1, }), reg.to64(), emit.code); } else { try lowerToRmEnc(.mov, reg.to64(), RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, -@intCast(i32, disp)), .base = ops.reg1, }), emit.code); } disp += 8; } } fn mirJmpCall(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { const target = emit.mir.instructions.items(.data)[inst].inst; const source = emit.code.items.len; try lowerToDEnc(tag, 0, emit.code); try emit.relocs.append(emit.bin_file.allocator, .{ .source = source, .target = target, .offset = emit.code.items.len - 4, .length = 5, }); }, 0b01 => { if (ops.reg1 == .none) { // JMP/CALL [imm] const imm = emit.mir.instructions.items(.data)[inst].imm; const ptr_size: Memory.PtrSize = switch (immOpSize(imm)) { 16 => .word_ptr, else => .qword_ptr, }; return lowerToMEnc(tag, RegisterOrMemory.mem(ptr_size, .{ .disp = imm }), emit.code); } // JMP/CALL reg return lowerToMEnc(tag, RegisterOrMemory.reg(ops.reg1), emit.code); }, 0b10 => { // JMP/CALL r/m64 const imm = emit.mir.instructions.items(.data)[inst].imm; return lowerToMEnc(tag, RegisterOrMemory.mem(Memory.PtrSize.fromBits(ops.reg1.size()), .{ .disp = imm, .base = ops.reg1, }), emit.code); }, 0b11 => return emit.fail("TODO unused JMP/CALL variant 0b11", .{}), } } fn mirCondJmp(emit: *Emit, mir_tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const target = emit.mir.instructions.items(.data)[inst].inst; const tag = switch (mir_tag) { .cond_jmp_greater_less => switch (ops.flags) { 0b00 => Tag.jge, 0b01 => Tag.jg, 0b10 => Tag.jl, 0b11 => Tag.jle, }, .cond_jmp_above_below => switch (ops.flags) { 0b00 => Tag.jae, 0b01 => Tag.ja, 0b10 => Tag.jb, 0b11 => Tag.jbe, }, .cond_jmp_eq_ne => switch (@truncate(u1, ops.flags)) { 0b0 => Tag.jne, 0b1 => Tag.je, }, else => unreachable, }; const source = emit.code.items.len; try lowerToDEnc(tag, 0, emit.code); try emit.relocs.append(emit.bin_file.allocator, .{ .source = source, .target = target, .offset = emit.code.items.len - 4, .length = 6, }); } fn mirCondSetByte(emit: *Emit, mir_tag: Mir.Inst.Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const tag = switch (mir_tag) { .cond_set_byte_greater_less => switch (ops.flags) { 0b00 => Tag.setge, 0b01 => Tag.setg, 0b10 => Tag.setl, 0b11 => Tag.setle, }, .cond_set_byte_above_below => switch (ops.flags) { 0b00 => Tag.setae, 0b01 => Tag.seta, 0b10 => Tag.setb, 0b11 => Tag.setbe, }, .cond_set_byte_eq_ne => switch (@truncate(u1, ops.flags)) { 0b0 => Tag.setne, 0b1 => Tag.sete, }, .cond_set_byte_overflow => switch (ops.flags) { 0b00 => Tag.seto, 0b01 => Tag.setno, 0b10 => Tag.setc, 0b11 => Tag.setnc, }, else => unreachable, }; return lowerToMEnc(tag, RegisterOrMemory.reg(ops.reg1.to8()), emit.code); } fn mirCondMov(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); if (ops.flags == 0b00) { return lowerToRmEnc(tag, ops.reg1, RegisterOrMemory.reg(ops.reg2), emit.code); } const imm = emit.mir.instructions.items(.data)[inst].imm; const ptr_size: Memory.PtrSize = switch (ops.flags) { 0b00 => unreachable, 0b01 => .word_ptr, 0b10 => .dword_ptr, 0b11 => .qword_ptr, }; return lowerToRmEnc(tag, ops.reg1, RegisterOrMemory.mem(ptr_size, .{ .disp = imm, .base = ops.reg2, }), emit.code); } fn mirTest(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .@"test"); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { if (ops.reg2 == .none) { // TEST r/m64, imm32 // MI const imm = emit.mir.instructions.items(.data)[inst].imm; if (ops.reg1.to64() == .rax) { // TEST rax, imm32 // I return lowerToIEnc(.@"test", imm, emit.code); } return lowerToMiEnc(.@"test", RegisterOrMemory.reg(ops.reg1), imm, emit.code); } // TEST r/m64, r64 return lowerToMrEnc(.@"test", RegisterOrMemory.reg(ops.reg1), ops.reg2, emit.code); }, else => return emit.fail("TODO more TEST alternatives", .{}), } } fn mirRet(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .ret); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { // RETF imm16 // I const imm = emit.mir.instructions.items(.data)[inst].imm; return lowerToIEnc(.ret_far, imm, emit.code); }, 0b01 => { return lowerToZoEnc(.ret_far, emit.code); }, 0b10 => { // RET imm16 // I const imm = emit.mir.instructions.items(.data)[inst].imm; return lowerToIEnc(.ret_near, imm, emit.code); }, 0b11 => { return lowerToZoEnc(.ret_near, emit.code); }, } } fn mirArith(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { if (ops.reg2 == .none) { // mov reg1, imm32 // MI const imm = emit.mir.instructions.items(.data)[inst].imm; return lowerToMiEnc(tag, RegisterOrMemory.reg(ops.reg1), imm, emit.code); } // mov reg1, reg2 // RM return lowerToRmEnc(tag, ops.reg1, RegisterOrMemory.reg(ops.reg2), emit.code); }, 0b01 => { // mov reg1, [reg2 + imm32] // RM const imm = emit.mir.instructions.items(.data)[inst].imm; const src_reg: ?Register = if (ops.reg2 == .none) null else ops.reg2; return lowerToRmEnc(tag, ops.reg1, RegisterOrMemory.mem(Memory.PtrSize.fromBits(ops.reg1.size()), .{ .disp = imm, .base = src_reg, }), emit.code); }, 0b10 => { if (ops.reg2 == .none) { return emit.fail("TODO unused variant: mov reg1, none, 0b10", .{}); } // mov [reg1 + imm32], reg2 // MR const imm = emit.mir.instructions.items(.data)[inst].imm; return lowerToMrEnc(tag, RegisterOrMemory.mem(Memory.PtrSize.fromBits(ops.reg2.size()), .{ .disp = imm, .base = ops.reg1, }), ops.reg2, emit.code); }, 0b11 => { return emit.fail("TODO unused variant: mov reg1, reg2, 0b11", .{}); }, } } fn mirArithMemImm(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); assert(ops.reg2 == .none); const payload = emit.mir.instructions.items(.data)[inst].payload; const imm_pair = emit.mir.extraData(Mir.ImmPair, payload).data; const ptr_size: Memory.PtrSize = switch (ops.flags) { 0b00 => .byte_ptr, 0b01 => .word_ptr, 0b10 => .dword_ptr, 0b11 => .qword_ptr, }; return lowerToMiEnc(tag, RegisterOrMemory.mem(ptr_size, .{ .disp = imm_pair.dest_off, .base = ops.reg1, }), imm_pair.operand, emit.code); } inline fn setRexWRegister(reg: Register) bool { if (reg.size() == 64) return true; return switch (reg) { .ah, .bh, .ch, .dh => true, else => false, }; } inline fn immOpSize(u_imm: u32) u8 { const imm = @bitCast(i32, u_imm); if (math.minInt(i8) <= imm and imm <= math.maxInt(i8)) { return 8; } if (math.minInt(i16) <= imm and imm <= math.maxInt(i16)) { return 16; } return 32; } fn mirArithScaleSrc(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const scale = ops.flags; const imm = emit.mir.instructions.items(.data)[inst].imm; // OP reg1, [reg2 + scale*rcx + imm32] const scale_index = ScaleIndex{ .scale = scale, .index = .rcx, }; return lowerToRmEnc(tag, ops.reg1, RegisterOrMemory.mem(Memory.PtrSize.fromBits(ops.reg1.size()), .{ .disp = imm, .base = ops.reg2, .scale_index = scale_index, }), emit.code); } fn mirArithScaleDst(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const scale = ops.flags; const imm = emit.mir.instructions.items(.data)[inst].imm; const scale_index = ScaleIndex{ .scale = scale, .index = .rax, }; if (ops.reg2 == .none) { // OP qword ptr [reg1 + scale*rax + 0], imm32 return lowerToMiEnc(tag, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0, .base = ops.reg1, .scale_index = scale_index, }), imm, emit.code); } // OP [reg1 + scale*rax + imm32], reg2 return lowerToMrEnc(tag, RegisterOrMemory.mem(Memory.PtrSize.fromBits(ops.reg2.size()), .{ .disp = imm, .base = ops.reg1, .scale_index = scale_index, }), ops.reg2, emit.code); } fn mirArithScaleImm(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const scale = ops.flags; const payload = emit.mir.instructions.items(.data)[inst].payload; const imm_pair = emit.mir.extraData(Mir.ImmPair, payload).data; const scale_index = ScaleIndex{ .scale = scale, .index = .rax, }; // OP qword ptr [reg1 + scale*rax + imm32], imm32 return lowerToMiEnc(tag, RegisterOrMemory.mem(.qword_ptr, .{ .disp = imm_pair.dest_off, .base = ops.reg1, .scale_index = scale_index, }), imm_pair.operand, emit.code); } fn mirArithMemIndexImm(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); assert(ops.reg2 == .none); const payload = emit.mir.instructions.items(.data)[inst].payload; const imm_pair = emit.mir.extraData(Mir.ImmPair, payload).data; const ptr_size: Memory.PtrSize = switch (ops.flags) { 0b00 => .byte_ptr, 0b01 => .word_ptr, 0b10 => .dword_ptr, 0b11 => .qword_ptr, }; const scale_index = ScaleIndex{ .scale = 0, .index = .rax, }; // OP ptr [reg1 + rax*1 + imm32], imm32 return lowerToMiEnc(tag, RegisterOrMemory.mem(ptr_size, .{ .disp = imm_pair.dest_off, .base = ops.reg1, .scale_index = scale_index, }), imm_pair.operand, emit.code); } fn mirMovSignExtend(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const mir_tag = emit.mir.instructions.items(.tag)[inst]; assert(mir_tag == .mov_sign_extend); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const imm = if (ops.flags != 0b00) emit.mir.instructions.items(.data)[inst].imm else undefined; switch (ops.flags) { 0b00 => { const tag: Tag = if (ops.reg2.size() == 32) .movsxd else .movsx; return lowerToRmEnc(tag, ops.reg1, RegisterOrMemory.reg(ops.reg2), emit.code); }, 0b01 => { return lowerToRmEnc(.movsx, ops.reg1, RegisterOrMemory.mem(.byte_ptr, .{ .disp = imm, .base = ops.reg2, }), emit.code); }, 0b10 => { return lowerToRmEnc(.movsx, ops.reg1, RegisterOrMemory.mem(.word_ptr, .{ .disp = imm, .base = ops.reg2, }), emit.code); }, 0b11 => { return lowerToRmEnc(.movsxd, ops.reg1, RegisterOrMemory.mem(.dword_ptr, .{ .disp = imm, .base = ops.reg2, }), emit.code); }, } } fn mirMovZeroExtend(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const mir_tag = emit.mir.instructions.items(.tag)[inst]; assert(mir_tag == .mov_zero_extend); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const imm = if (ops.flags != 0b00) emit.mir.instructions.items(.data)[inst].imm else undefined; switch (ops.flags) { 0b00 => { return lowerToRmEnc(.movzx, ops.reg1, RegisterOrMemory.reg(ops.reg2), emit.code); }, 0b01 => { return lowerToRmEnc(.movzx, ops.reg1, RegisterOrMemory.mem(.byte_ptr, .{ .disp = imm, .base = ops.reg2, }), emit.code); }, 0b10 => { return lowerToRmEnc(.movzx, ops.reg1, RegisterOrMemory.mem(.word_ptr, .{ .disp = imm, .base = ops.reg2, }), emit.code); }, 0b11 => { return emit.fail("TODO unused variant: movzx 0b11", .{}); }, } } fn mirMovabs(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .movabs); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const imm: u64 = if (ops.reg1.size() == 64) blk: { const payload = emit.mir.instructions.items(.data)[inst].payload; const imm = emit.mir.extraData(Mir.Imm64, payload).data; break :blk imm.decode(); } else emit.mir.instructions.items(.data)[inst].imm; if (ops.flags == 0b00) { // movabs reg, imm64 // OI return lowerToOiEnc(.mov, ops.reg1, imm, emit.code); } if (ops.reg1 == .none) { // movabs moffs64, rax // TD return lowerToTdEnc(.mov, imm, ops.reg2, emit.code); } // movabs rax, moffs64 // FD return lowerToFdEnc(.mov, ops.reg1, imm, emit.code); } fn mirFisttp(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .fisttp); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); // the selecting between operand sizes for this particular `fisttp` instruction // is done via opcode instead of the usual prefixes. const opcode: Tag = switch (ops.flags) { 0b00 => .fisttp16, 0b01 => .fisttp32, 0b10 => .fisttp64, else => unreachable, }; const mem_or_reg = Memory{ .base = ops.reg1, .disp = emit.mir.instructions.items(.data)[inst].imm, .ptr_size = Memory.PtrSize.dword_ptr, // to prevent any prefix from being used }; return lowerToMEnc(opcode, .{ .memory = mem_or_reg }, emit.code); } fn mirFld(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .fld); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); // the selecting between operand sizes for this particular `fisttp` instruction // is done via opcode instead of the usual prefixes. const opcode: Tag = switch (ops.flags) { 0b01 => .fld32, 0b10 => .fld64, else => unreachable, }; const mem_or_reg = Memory{ .base = ops.reg1, .disp = emit.mir.instructions.items(.data)[inst].imm, .ptr_size = Memory.PtrSize.dword_ptr, // to prevent any prefix from being used }; return lowerToMEnc(opcode, .{ .memory = mem_or_reg }, emit.code); } fn mirShift(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { // sal reg1, 1 // M1 return lowerToM1Enc(tag, RegisterOrMemory.reg(ops.reg1), emit.code); }, 0b01 => { // sal reg1, .cl // MC return lowerToMcEnc(tag, RegisterOrMemory.reg(ops.reg1), emit.code); }, 0b10 => { // sal reg1, imm8 // MI const imm = @truncate(u8, emit.mir.instructions.items(.data)[inst].imm); return lowerToMiImm8Enc(tag, RegisterOrMemory.reg(ops.reg1), imm, emit.code); }, 0b11 => { return emit.fail("TODO unused variant: SHIFT reg1, 0b11", .{}); }, } } fn mirMulDiv(emit: *Emit, tag: Tag, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); if (ops.reg1 != .none) { assert(ops.reg2 == .none); return lowerToMEnc(tag, RegisterOrMemory.reg(ops.reg1), emit.code); } assert(ops.reg1 == .none); assert(ops.reg2 != .none); const imm = emit.mir.instructions.items(.data)[inst].imm; const ptr_size: Memory.PtrSize = switch (ops.flags) { 0b00 => .byte_ptr, 0b01 => .word_ptr, 0b10 => .dword_ptr, 0b11 => .qword_ptr, }; return lowerToMEnc(tag, RegisterOrMemory.mem(ptr_size, .{ .disp = imm, .base = ops.reg2, }), emit.code); } fn mirIMulComplex(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .imul_complex); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { return lowerToRmEnc(.imul, ops.reg1, RegisterOrMemory.reg(ops.reg2), emit.code); }, 0b01 => { const imm = emit.mir.instructions.items(.data)[inst].imm; const src_reg: ?Register = if (ops.reg2 == .none) null else ops.reg2; return lowerToRmEnc(.imul, ops.reg1, RegisterOrMemory.mem(.qword_ptr, .{ .disp = imm, .base = src_reg, }), emit.code); }, 0b10 => { const imm = emit.mir.instructions.items(.data)[inst].imm; return lowerToRmiEnc(.imul, ops.reg1, RegisterOrMemory.reg(ops.reg2), imm, emit.code); }, 0b11 => { const payload = emit.mir.instructions.items(.data)[inst].payload; const imm_pair = emit.mir.extraData(Mir.ImmPair, payload).data; return lowerToRmiEnc(.imul, ops.reg1, RegisterOrMemory.mem(.qword_ptr, .{ .disp = imm_pair.dest_off, .base = ops.reg2, }), imm_pair.operand, emit.code); }, } } fn mirCwd(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const tag: Tag = switch (ops.flags) { 0b00 => .cbw, 0b01 => .cwd, 0b10 => .cdq, 0b11 => .cqo, }; return lowerToZoEnc(tag, emit.code); } fn mirLea(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .lea); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); switch (ops.flags) { 0b00 => { // lea reg1, [reg2 + imm32] // RM const imm = emit.mir.instructions.items(.data)[inst].imm; const src_reg: ?Register = if (ops.reg2 == .none) null else ops.reg2; return lowerToRmEnc( .lea, ops.reg1, RegisterOrMemory.mem(Memory.PtrSize.fromBits(ops.reg1.size()), .{ .disp = imm, .base = src_reg, }), emit.code, ); }, 0b01 => { // lea reg1, [rip + imm32] // RM const start_offset = emit.code.items.len; try lowerToRmEnc( .lea, ops.reg1, RegisterOrMemory.rip(Memory.PtrSize.fromBits(ops.reg1.size()), 0), emit.code, ); const end_offset = emit.code.items.len; // Backpatch the displacement const payload = emit.mir.instructions.items(.data)[inst].payload; const imm = emit.mir.extraData(Mir.Imm64, payload).data.decode(); const disp = @intCast(i32, @intCast(i64, imm) - @intCast(i64, end_offset - start_offset)); mem.writeIntLittle(i32, emit.code.items[end_offset - 4 ..][0..4], disp); }, 0b10 => { // lea reg, [rbp + rcx + imm32] const imm = emit.mir.instructions.items(.data)[inst].imm; const src_reg: ?Register = if (ops.reg2 == .none) null else ops.reg2; const scale_index = ScaleIndex{ .scale = 0, .index = .rcx, }; return lowerToRmEnc( .lea, ops.reg1, RegisterOrMemory.mem(Memory.PtrSize.fromBits(ops.reg1.size()), .{ .disp = imm, .base = src_reg, .scale_index = scale_index, }), emit.code, ); }, 0b11 => return emit.fail("TODO unused LEA variant 0b11", .{}), } } fn mirLeaPie(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .lea_pie); const ops = Mir.Ops.decode(emit.mir.instructions.items(.ops)[inst]); const load_reloc = emit.mir.instructions.items(.data)[inst].load_reloc; // lea reg1, [rip + reloc] // RM try lowerToRmEnc( .lea, ops.reg1, RegisterOrMemory.rip(Memory.PtrSize.fromBits(ops.reg1.size()), 0), emit.code, ); const end_offset = emit.code.items.len; if (emit.bin_file.cast(link.File.MachO)) |macho_file| { const reloc_type = switch (ops.flags) { 0b00 => @enumToInt(std.macho.reloc_type_x86_64.X86_64_RELOC_GOT), 0b01 => @enumToInt(std.macho.reloc_type_x86_64.X86_64_RELOC_SIGNED), else => return emit.fail("TODO unused LEA PIE variants 0b10 and 0b11", .{}), }; const atom = macho_file.atom_by_index_table.get(load_reloc.atom_index).?; log.debug("adding reloc of type {} to local @{d}", .{ reloc_type, load_reloc.sym_index }); try atom.relocs.append(emit.bin_file.allocator, .{ .offset = @intCast(u32, end_offset - 4), .target = .{ .local = load_reloc.sym_index }, .addend = 0, .subtractor = null, .pcrel = true, .length = 2, .@"type" = reloc_type, }); } else { return emit.fail( "TODO implement lea reg, [rip + reloc] for linking backends different than MachO", .{}, ); } } fn mirCallExtern(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .call_extern); const extern_fn = emit.mir.instructions.items(.data)[inst].extern_fn; const offset = blk: { // callq try lowerToDEnc(.call_near, 0, emit.code); break :blk @intCast(u32, emit.code.items.len) - 4; }; if (emit.bin_file.cast(link.File.MachO)) |macho_file| { // Add relocation to the decl. const atom = macho_file.atom_by_index_table.get(extern_fn.atom_index).?; try atom.relocs.append(emit.bin_file.allocator, .{ .offset = offset, .target = .{ .global = extern_fn.sym_name }, .addend = 0, .subtractor = null, .pcrel = true, .length = 2, .@"type" = @enumToInt(std.macho.reloc_type_x86_64.X86_64_RELOC_BRANCH), }); } else { return emit.fail("TODO implement call_extern for linking backends different than MachO", .{}); } } fn mirDbgLine(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .dbg_line); const payload = emit.mir.instructions.items(.data)[inst].payload; const dbg_line_column = emit.mir.extraData(Mir.DbgLineColumn, payload).data; log.debug("mirDbgLine", .{}); try emit.dbgAdvancePCAndLine(dbg_line_column.line, dbg_line_column.column); } fn dbgAdvancePCAndLine(emit: *Emit, line: u32, column: u32) InnerError!void { const delta_line = @intCast(i32, line) - @intCast(i32, emit.prev_di_line); const delta_pc: usize = emit.code.items.len - emit.prev_di_pc; log.debug(" (advance pc={d} and line={d})", .{ delta_line, delta_pc }); switch (emit.debug_output) { .dwarf => |dw| { // TODO Look into using the DWARF special opcodes to compress this data. // It lets you emit single-byte opcodes that add different numbers to // both the PC and the line number at the same time. const dbg_line = &dw.dbg_line; try dbg_line.ensureUnusedCapacity(11); dbg_line.appendAssumeCapacity(DW.LNS.advance_pc); leb128.writeULEB128(dbg_line.writer(), delta_pc) catch unreachable; if (delta_line != 0) { dbg_line.appendAssumeCapacity(DW.LNS.advance_line); leb128.writeILEB128(dbg_line.writer(), delta_line) catch unreachable; } dbg_line.appendAssumeCapacity(DW.LNS.copy); emit.prev_di_line = line; emit.prev_di_column = column; emit.prev_di_pc = emit.code.items.len; }, .plan9 => |dbg_out| { if (delta_pc <= 0) return; // only do this when the pc changes // we have already checked the target in the linker to make sure it is compatable const quant = @import("../../link/Plan9/aout.zig").getPCQuant(emit.target.cpu.arch) catch unreachable; // increasing the line number try @import("../../link/Plan9.zig").changeLine(dbg_out.dbg_line, delta_line); // increasing the pc const d_pc_p9 = @intCast(i64, delta_pc) - quant; if (d_pc_p9 > 0) { // minus one because if its the last one, we want to leave space to change the line which is one quanta var diff = @divExact(d_pc_p9, quant) - quant; while (diff > 0) { if (diff < 64) { try dbg_out.dbg_line.append(@intCast(u8, diff + 128)); diff = 0; } else { try dbg_out.dbg_line.append(@intCast(u8, 64 + 128)); diff -= 64; } } if (dbg_out.pcop_change_index.*) |pci| dbg_out.dbg_line.items[pci] += 1; dbg_out.pcop_change_index.* = @intCast(u32, dbg_out.dbg_line.items.len - 1); } else if (d_pc_p9 == 0) { // we don't need to do anything, because adding the quant does it for us } else unreachable; if (dbg_out.start_line.* == null) dbg_out.start_line.* = emit.prev_di_line; dbg_out.end_line.* = line; // only do this if the pc changed emit.prev_di_line = line; emit.prev_di_column = column; emit.prev_di_pc = emit.code.items.len; }, .none => {}, } } fn mirDbgPrologueEnd(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .dbg_prologue_end); switch (emit.debug_output) { .dwarf => |dw| { try dw.dbg_line.append(DW.LNS.set_prologue_end); log.debug("mirDbgPrologueEnd (line={d}, col={d})", .{ emit.prev_di_line, emit.prev_di_column }); try emit.dbgAdvancePCAndLine(emit.prev_di_line, emit.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirDbgEpilogueBegin(emit: *Emit, inst: Mir.Inst.Index) InnerError!void { const tag = emit.mir.instructions.items(.tag)[inst]; assert(tag == .dbg_epilogue_begin); switch (emit.debug_output) { .dwarf => |dw| { try dw.dbg_line.append(DW.LNS.set_epilogue_begin); log.debug("mirDbgEpilogueBegin (line={d}, col={d})", .{ emit.prev_di_line, emit.prev_di_column }); try emit.dbgAdvancePCAndLine(emit.prev_di_line, emit.prev_di_column); }, .plan9 => {}, .none => {}, } } const Tag = enum { adc, add, sub, xor, @"and", @"or", sbb, cmp, mov, movsx, movsxd, movzx, lea, jmp_near, call_near, push, pop, @"test", int3, nop, imul, mul, idiv, div, syscall, ret_near, ret_far, fisttp16, fisttp32, fisttp64, fld32, fld64, jo, jno, jb, jbe, jc, jnae, jnc, jae, je, jz, jne, jnz, jna, jnb, jnbe, ja, js, jns, jpe, jp, jpo, jnp, jnge, jl, jge, jnl, jle, jng, jg, jnle, seto, setno, setb, setc, setnae, setnb, setnc, setae, sete, setz, setne, setnz, setbe, setna, seta, setnbe, sets, setns, setp, setpe, setnp, setop, setl, setnge, setnl, setge, setle, setng, setnle, setg, shl, sal, shr, sar, cbw, cwd, cdq, cqo, cmove, cmovz, cmovl, cmovng, cmovb, cmovnae, fn isSetCC(tag: Tag) bool { return switch (tag) { .seto, .setno, .setb, .setc, .setnae, .setnb, .setnc, .setae, .sete, .setz, .setne, .setnz, .setbe, .setna, .seta, .setnbe, .sets, .setns, .setp, .setpe, .setnp, .setop, .setl, .setnge, .setnl, .setge, .setle, .setng, .setnle, .setg, => true, else => false, }; } }; const Encoding = enum { /// OP zo, /// OP rel32 d, /// OP r/m64 m, /// OP r64 o, /// OP imm32 i, /// OP r/m64, 1 m1, /// OP r/m64, .cl mc, /// OP r/m64, imm32 mi, /// OP r/m64, imm8 mi8, /// OP r/m64, r64 mr, /// OP r64, r/m64 rm, /// OP r64, imm64 oi, /// OP al/ax/eax/rax, moffs fd, /// OP moffs, al/ax/eax/rax td, /// OP r64, r/m64, imm32 rmi, }; const OpCode = union(enum) { one_byte: u8, two_byte: struct { _1: u8, _2: u8 }, fn oneByte(opc: u8) OpCode { return .{ .one_byte = opc }; } fn twoByte(opc1: u8, opc2: u8) OpCode { return .{ .two_byte = .{ ._1 = opc1, ._2 = opc2 } }; } fn encode(opc: OpCode, encoder: Encoder) void { switch (opc) { .one_byte => |v| encoder.opcode_1byte(v), .two_byte => |v| encoder.opcode_2byte(v._1, v._2), } } fn encodeWithReg(opc: OpCode, encoder: Encoder, reg: Register) void { assert(opc == .one_byte); encoder.opcode_withReg(opc.one_byte, reg.lowId()); } }; inline fn getOpCode(tag: Tag, enc: Encoding, is_one_byte: bool) ?OpCode { switch (enc) { .zo => return switch (tag) { .ret_near => OpCode.oneByte(0xc3), .ret_far => OpCode.oneByte(0xcb), .int3 => OpCode.oneByte(0xcc), .nop => OpCode.oneByte(0x90), .syscall => OpCode.twoByte(0x0f, 0x05), .cbw => OpCode.oneByte(0x98), .cwd, .cdq, .cqo => OpCode.oneByte(0x99), else => null, }, .d => return switch (tag) { .jmp_near => OpCode.oneByte(0xe9), .call_near => OpCode.oneByte(0xe8), .jo => if (is_one_byte) OpCode.oneByte(0x70) else OpCode.twoByte(0x0f, 0x80), .jno => if (is_one_byte) OpCode.oneByte(0x71) else OpCode.twoByte(0x0f, 0x81), .jb, .jc, .jnae => if (is_one_byte) OpCode.oneByte(0x72) else OpCode.twoByte(0x0f, 0x82), .jnb, .jnc, .jae => if (is_one_byte) OpCode.oneByte(0x73) else OpCode.twoByte(0x0f, 0x83), .je, .jz => if (is_one_byte) OpCode.oneByte(0x74) else OpCode.twoByte(0x0f, 0x84), .jne, .jnz => if (is_one_byte) OpCode.oneByte(0x75) else OpCode.twoByte(0x0f, 0x85), .jna, .jbe => if (is_one_byte) OpCode.oneByte(0x76) else OpCode.twoByte(0x0f, 0x86), .jnbe, .ja => if (is_one_byte) OpCode.oneByte(0x77) else OpCode.twoByte(0x0f, 0x87), .js => if (is_one_byte) OpCode.oneByte(0x78) else OpCode.twoByte(0x0f, 0x88), .jns => if (is_one_byte) OpCode.oneByte(0x79) else OpCode.twoByte(0x0f, 0x89), .jpe, .jp => if (is_one_byte) OpCode.oneByte(0x7a) else OpCode.twoByte(0x0f, 0x8a), .jpo, .jnp => if (is_one_byte) OpCode.oneByte(0x7b) else OpCode.twoByte(0x0f, 0x8b), .jnge, .jl => if (is_one_byte) OpCode.oneByte(0x7c) else OpCode.twoByte(0x0f, 0x8c), .jge, .jnl => if (is_one_byte) OpCode.oneByte(0x7d) else OpCode.twoByte(0x0f, 0x8d), .jle, .jng => if (is_one_byte) OpCode.oneByte(0x7e) else OpCode.twoByte(0x0f, 0x8e), .jg, .jnle => if (is_one_byte) OpCode.oneByte(0x7f) else OpCode.twoByte(0x0f, 0x8f), else => null, }, .m => return switch (tag) { .jmp_near, .call_near, .push => OpCode.oneByte(0xff), .pop => OpCode.oneByte(0x8f), .seto => OpCode.twoByte(0x0f, 0x90), .setno => OpCode.twoByte(0x0f, 0x91), .setb, .setc, .setnae => OpCode.twoByte(0x0f, 0x92), .setnb, .setnc, .setae => OpCode.twoByte(0x0f, 0x93), .sete, .setz => OpCode.twoByte(0x0f, 0x94), .setne, .setnz => OpCode.twoByte(0x0f, 0x95), .setbe, .setna => OpCode.twoByte(0x0f, 0x96), .seta, .setnbe => OpCode.twoByte(0x0f, 0x97), .sets => OpCode.twoByte(0x0f, 0x98), .setns => OpCode.twoByte(0x0f, 0x99), .setp, .setpe => OpCode.twoByte(0x0f, 0x9a), .setnp, .setop => OpCode.twoByte(0x0f, 0x9b), .setl, .setnge => OpCode.twoByte(0x0f, 0x9c), .setnl, .setge => OpCode.twoByte(0x0f, 0x9d), .setle, .setng => OpCode.twoByte(0x0f, 0x9e), .setnle, .setg => OpCode.twoByte(0x0f, 0x9f), .idiv, .div, .imul, .mul => OpCode.oneByte(if (is_one_byte) 0xf6 else 0xf7), .fisttp16 => OpCode.oneByte(0xdf), .fisttp32 => OpCode.oneByte(0xdb), .fisttp64 => OpCode.oneByte(0xdd), .fld32 => OpCode.oneByte(0xd9), .fld64 => OpCode.oneByte(0xdd), else => null, }, .o => return switch (tag) { .push => OpCode.oneByte(0x50), .pop => OpCode.oneByte(0x58), else => null, }, .i => return switch (tag) { .push => OpCode.oneByte(if (is_one_byte) 0x6a else 0x68), .@"test" => OpCode.oneByte(if (is_one_byte) 0xa8 else 0xa9), .ret_near => OpCode.oneByte(0xc2), .ret_far => OpCode.oneByte(0xca), else => null, }, .m1 => return switch (tag) { .shl, .sal, .shr, .sar => OpCode.oneByte(if (is_one_byte) 0xd0 else 0xd1), else => null, }, .mc => return switch (tag) { .shl, .sal, .shr, .sar => OpCode.oneByte(if (is_one_byte) 0xd2 else 0xd3), else => null, }, .mi => return switch (tag) { .adc, .add, .sub, .xor, .@"and", .@"or", .sbb, .cmp => OpCode.oneByte(if (is_one_byte) 0x80 else 0x81), .mov => OpCode.oneByte(if (is_one_byte) 0xc6 else 0xc7), .@"test" => OpCode.oneByte(if (is_one_byte) 0xf6 else 0xf7), else => null, }, .mi8 => return switch (tag) { .adc, .add, .sub, .xor, .@"and", .@"or", .sbb, .cmp => OpCode.oneByte(0x83), .shl, .sal, .shr, .sar => OpCode.oneByte(if (is_one_byte) 0xc0 else 0xc1), else => null, }, .mr => return switch (tag) { .adc => OpCode.oneByte(if (is_one_byte) 0x10 else 0x11), .add => OpCode.oneByte(if (is_one_byte) 0x00 else 0x01), .sub => OpCode.oneByte(if (is_one_byte) 0x28 else 0x29), .xor => OpCode.oneByte(if (is_one_byte) 0x30 else 0x31), .@"and" => OpCode.oneByte(if (is_one_byte) 0x20 else 0x21), .@"or" => OpCode.oneByte(if (is_one_byte) 0x08 else 0x09), .sbb => OpCode.oneByte(if (is_one_byte) 0x18 else 0x19), .cmp => OpCode.oneByte(if (is_one_byte) 0x38 else 0x39), .mov => OpCode.oneByte(if (is_one_byte) 0x88 else 0x89), .@"test" => OpCode.oneByte(if (is_one_byte) 0x84 else 0x85), else => null, }, .rm => return switch (tag) { .adc => OpCode.oneByte(if (is_one_byte) 0x12 else 0x13), .add => OpCode.oneByte(if (is_one_byte) 0x02 else 0x03), .sub => OpCode.oneByte(if (is_one_byte) 0x2a else 0x2b), .xor => OpCode.oneByte(if (is_one_byte) 0x32 else 0x33), .@"and" => OpCode.oneByte(if (is_one_byte) 0x22 else 0x23), .@"or" => OpCode.oneByte(if (is_one_byte) 0x0a else 0x0b), .sbb => OpCode.oneByte(if (is_one_byte) 0x1a else 0x1b), .cmp => OpCode.oneByte(if (is_one_byte) 0x3a else 0x3b), .mov => OpCode.oneByte(if (is_one_byte) 0x8a else 0x8b), .movsx => OpCode.twoByte(0x0f, if (is_one_byte) 0xbe else 0xbf), .movsxd => OpCode.oneByte(0x63), .movzx => OpCode.twoByte(0x0f, if (is_one_byte) 0xb6 else 0xb7), .lea => OpCode.oneByte(if (is_one_byte) 0x8c else 0x8d), .imul => OpCode.twoByte(0x0f, 0xaf), .cmove, .cmovz => OpCode.twoByte(0x0f, 0x44), .cmovb, .cmovnae => OpCode.twoByte(0x0f, 0x42), .cmovl, .cmovng => OpCode.twoByte(0x0f, 0x4c), else => null, }, .oi => return switch (tag) { .mov => OpCode.oneByte(if (is_one_byte) 0xb0 else 0xb8), else => null, }, .fd => return switch (tag) { .mov => OpCode.oneByte(if (is_one_byte) 0xa0 else 0xa1), else => null, }, .td => return switch (tag) { .mov => OpCode.oneByte(if (is_one_byte) 0xa2 else 0xa3), else => null, }, .rmi => return switch (tag) { .imul => OpCode.oneByte(if (is_one_byte) 0x6b else 0x69), else => null, }, } } inline fn getModRmExt(tag: Tag) ?u3 { return switch (tag) { .adc => 0x2, .add => 0x0, .sub => 0x5, .xor => 0x6, .@"and" => 0x4, .@"or" => 0x1, .sbb => 0x3, .cmp => 0x7, .mov => 0x0, .jmp_near => 0x4, .call_near => 0x2, .push => 0x6, .pop => 0x0, .@"test" => 0x0, .seto, .setno, .setb, .setc, .setnae, .setnb, .setnc, .setae, .sete, .setz, .setne, .setnz, .setbe, .setna, .seta, .setnbe, .sets, .setns, .setp, .setpe, .setnp, .setop, .setl, .setnge, .setnl, .setge, .setle, .setng, .setnle, .setg, => 0x0, .shl, .sal, => 0x4, .shr => 0x5, .sar => 0x7, .mul => 0x4, .imul => 0x5, .div => 0x6, .idiv => 0x7, .fisttp16 => 0x1, .fisttp32 => 0x1, .fisttp64 => 0x1, .fld32 => 0x0, .fld64 => 0x0, else => null, }; } const ScaleIndex = struct { scale: u2, index: Register, }; const Memory = struct { base: ?Register, rip: bool = false, disp: u32, ptr_size: PtrSize, scale_index: ?ScaleIndex = null, const PtrSize = enum { byte_ptr, word_ptr, dword_ptr, qword_ptr, fn fromBits(in_bits: u64) PtrSize { return switch (in_bits) { 8 => .byte_ptr, 16 => .word_ptr, 32 => .dword_ptr, 64 => .qword_ptr, else => unreachable, }; } /// Returns size in bits. fn size(ptr_size: PtrSize) u64 { return switch (ptr_size) { .byte_ptr => 8, .word_ptr => 16, .dword_ptr => 32, .qword_ptr => 64, }; } }; fn encode(mem_op: Memory, encoder: Encoder, operand: u3) void { if (mem_op.base) |base| { const dst = base.lowId(); const src = operand; if (dst == 4 or mem_op.scale_index != null) { if (mem_op.disp == 0 and dst != 5) { encoder.modRm_SIBDisp0(src); if (mem_op.scale_index) |si| { encoder.sib_scaleIndexBase(si.scale, si.index.lowId(), dst); } else { encoder.sib_base(dst); } } else if (immOpSize(mem_op.disp) == 8) { encoder.modRm_SIBDisp8(src); if (mem_op.scale_index) |si| { encoder.sib_scaleIndexBaseDisp8(si.scale, si.index.lowId(), dst); } else { encoder.sib_baseDisp8(dst); } encoder.disp8(@bitCast(i8, @truncate(u8, mem_op.disp))); } else { encoder.modRm_SIBDisp32(src); if (mem_op.scale_index) |si| { encoder.sib_scaleIndexBaseDisp32(si.scale, si.index.lowId(), dst); } else { encoder.sib_baseDisp32(dst); } encoder.disp32(@bitCast(i32, mem_op.disp)); } } else { if (mem_op.disp == 0 and dst != 5) { encoder.modRm_indirectDisp0(src, dst); } else if (immOpSize(mem_op.disp) == 8) { encoder.modRm_indirectDisp8(src, dst); encoder.disp8(@bitCast(i8, @truncate(u8, mem_op.disp))); } else { encoder.modRm_indirectDisp32(src, dst); encoder.disp32(@bitCast(i32, mem_op.disp)); } } } else { if (mem_op.rip) { encoder.modRm_RIPDisp32(operand); } else { encoder.modRm_SIBDisp0(operand); if (mem_op.scale_index) |si| { encoder.sib_scaleIndexDisp32(si.scale, si.index.lowId()); } else { encoder.sib_disp32(); } } encoder.disp32(@bitCast(i32, mem_op.disp)); } } fn size(memory: Memory) u64 { return memory.ptr_size.size(); } }; fn encodeImm(encoder: Encoder, imm: u32, size: u64) void { switch (size) { 8 => encoder.imm8(@bitCast(i8, @truncate(u8, imm))), 16 => encoder.imm16(@bitCast(i16, @truncate(u16, imm))), 32, 64 => encoder.imm32(@bitCast(i32, imm)), else => unreachable, } } const RegisterOrMemory = union(enum) { register: Register, memory: Memory, fn reg(register: Register) RegisterOrMemory { return .{ .register = register }; } fn mem(ptr_size: Memory.PtrSize, args: struct { disp: u32, base: ?Register = null, scale_index: ?ScaleIndex = null, }) RegisterOrMemory { return .{ .memory = .{ .base = args.base, .disp = args.disp, .ptr_size = ptr_size, .scale_index = args.scale_index, }, }; } fn rip(ptr_size: Memory.PtrSize, disp: u32) RegisterOrMemory { return .{ .memory = .{ .base = null, .rip = true, .disp = disp, .ptr_size = ptr_size, }, }; } fn size(reg_or_mem: RegisterOrMemory) u64 { return switch (reg_or_mem) { .register => |reg| reg.size(), .memory => |memory| memory.size(), }; } }; fn lowerToZoEnc(tag: Tag, code: *std.ArrayList(u8)) InnerError!void { const opc = getOpCode(tag, .zo, false).?; const encoder = try Encoder.init(code, 2); switch (tag) { .cqo => { encoder.rex(.{ .w = true, }); }, else => {}, } opc.encode(encoder); } fn lowerToIEnc(tag: Tag, imm: u32, code: *std.ArrayList(u8)) InnerError!void { if (tag == .ret_far or tag == .ret_near) { const encoder = try Encoder.init(code, 3); const opc = getOpCode(tag, .i, false).?; opc.encode(encoder); encoder.imm16(@bitCast(i16, @truncate(u16, imm))); return; } const opc = getOpCode(tag, .i, immOpSize(imm) == 8).?; const encoder = try Encoder.init(code, 5); if (immOpSize(imm) == 16) { encoder.prefix16BitMode(); } opc.encode(encoder); encodeImm(encoder, imm, immOpSize(imm)); } fn lowerToOEnc(tag: Tag, reg: Register, code: *std.ArrayList(u8)) InnerError!void { const opc = getOpCode(tag, .o, false).?; const encoder = try Encoder.init(code, 3); if (reg.size() == 16) { encoder.prefix16BitMode(); } encoder.rex(.{ .w = false, .b = reg.isExtended(), }); opc.encodeWithReg(encoder, reg); } fn lowerToDEnc(tag: Tag, imm: u32, code: *std.ArrayList(u8)) InnerError!void { const opc = getOpCode(tag, .d, false).?; const encoder = try Encoder.init(code, 6); opc.encode(encoder); encoder.imm32(@bitCast(i32, imm)); } fn lowerToMxEnc(tag: Tag, reg_or_mem: RegisterOrMemory, enc: Encoding, code: *std.ArrayList(u8)) InnerError!void { const opc = getOpCode(tag, enc, reg_or_mem.size() == 8).?; const modrm_ext = getModRmExt(tag).?; switch (reg_or_mem) { .register => |reg| { const encoder = try Encoder.init(code, 4); if (reg.size() == 16) { encoder.prefix16BitMode(); } const wide = if (tag == .jmp_near) false else setRexWRegister(reg); encoder.rex(.{ .w = wide, .b = reg.isExtended(), }); opc.encode(encoder); encoder.modRm_direct(modrm_ext, reg.lowId()); }, .memory => |mem_op| { const encoder = try Encoder.init(code, 8); if (mem_op.ptr_size == .word_ptr) { encoder.prefix16BitMode(); } if (mem_op.base) |base| { const wide = if (tag == .jmp_near) false else mem_op.ptr_size == .qword_ptr; encoder.rex(.{ .w = wide, .b = base.isExtended(), }); } opc.encode(encoder); mem_op.encode(encoder, modrm_ext); }, } } fn lowerToMEnc(tag: Tag, reg_or_mem: RegisterOrMemory, code: *std.ArrayList(u8)) InnerError!void { return lowerToMxEnc(tag, reg_or_mem, .m, code); } fn lowerToM1Enc(tag: Tag, reg_or_mem: RegisterOrMemory, code: *std.ArrayList(u8)) InnerError!void { return lowerToMxEnc(tag, reg_or_mem, .m1, code); } fn lowerToMcEnc(tag: Tag, reg_or_mem: RegisterOrMemory, code: *std.ArrayList(u8)) InnerError!void { return lowerToMxEnc(tag, reg_or_mem, .mc, code); } fn lowerToTdEnc(tag: Tag, moffs: u64, reg: Register, code: *std.ArrayList(u8)) InnerError!void { return lowerToTdFdEnc(tag, reg, moffs, code, true); } fn lowerToFdEnc(tag: Tag, reg: Register, moffs: u64, code: *std.ArrayList(u8)) InnerError!void { return lowerToTdFdEnc(tag, reg, moffs, code, false); } fn lowerToTdFdEnc(tag: Tag, reg: Register, moffs: u64, code: *std.ArrayList(u8), td: bool) InnerError!void { const opc = if (td) getOpCode(tag, .td, reg.size() == 8).? else getOpCode(tag, .fd, reg.size() == 8).?; const encoder = try Encoder.init(code, 10); if (reg.size() == 16) { encoder.prefix16BitMode(); } encoder.rex(.{ .w = setRexWRegister(reg), }); opc.encode(encoder); switch (reg.size()) { 8 => encoder.imm8(@bitCast(i8, @truncate(u8, moffs))), 16 => encoder.imm16(@bitCast(i16, @truncate(u16, moffs))), 32 => encoder.imm32(@bitCast(i32, @truncate(u32, moffs))), 64 => encoder.imm64(moffs), else => unreachable, } } fn lowerToOiEnc(tag: Tag, reg: Register, imm: u64, code: *std.ArrayList(u8)) InnerError!void { const opc = getOpCode(tag, .oi, reg.size() == 8).?; const encoder = try Encoder.init(code, 10); if (reg.size() == 16) { encoder.prefix16BitMode(); } encoder.rex(.{ .w = setRexWRegister(reg), .b = reg.isExtended(), }); opc.encodeWithReg(encoder, reg); switch (reg.size()) { 8 => encoder.imm8(@bitCast(i8, @truncate(u8, imm))), 16 => encoder.imm16(@bitCast(i16, @truncate(u16, imm))), 32 => encoder.imm32(@bitCast(i32, @truncate(u32, imm))), 64 => encoder.imm64(imm), else => unreachable, } } fn lowerToMiXEnc( tag: Tag, reg_or_mem: RegisterOrMemory, imm: u32, enc: Encoding, code: *std.ArrayList(u8), ) InnerError!void { const modrm_ext = getModRmExt(tag).?; const opc = getOpCode(tag, enc, reg_or_mem.size() == 8).?; switch (reg_or_mem) { .register => |dst_reg| { const encoder = try Encoder.init(code, 7); if (dst_reg.size() == 16) { // 0x66 prefix switches to the non-default size; here we assume a switch from // the default 32bits to 16bits operand-size. // More info: https://www.cs.uni-potsdam.de/desn/lehre/ss15/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf#page=32&zoom=auto,-159,773 encoder.prefix16BitMode(); } encoder.rex(.{ .w = setRexWRegister(dst_reg), .b = dst_reg.isExtended(), }); opc.encode(encoder); encoder.modRm_direct(modrm_ext, dst_reg.lowId()); encodeImm(encoder, imm, if (enc == .mi8) 8 else dst_reg.size()); }, .memory => |dst_mem| { const encoder = try Encoder.init(code, 12); if (dst_mem.ptr_size == .word_ptr) { encoder.prefix16BitMode(); } if (dst_mem.base) |base| { encoder.rex(.{ .w = dst_mem.ptr_size == .qword_ptr, .b = base.isExtended(), }); } else { encoder.rex(.{ .w = dst_mem.ptr_size == .qword_ptr, }); } opc.encode(encoder); dst_mem.encode(encoder, modrm_ext); encodeImm(encoder, imm, if (enc == .mi8) 8 else dst_mem.ptr_size.size()); }, } } fn lowerToMiImm8Enc(tag: Tag, reg_or_mem: RegisterOrMemory, imm: u8, code: *std.ArrayList(u8)) InnerError!void { return lowerToMiXEnc(tag, reg_or_mem, imm, .mi8, code); } fn lowerToMiEnc(tag: Tag, reg_or_mem: RegisterOrMemory, imm: u32, code: *std.ArrayList(u8)) InnerError!void { return lowerToMiXEnc(tag, reg_or_mem, imm, .mi, code); } fn lowerToRmEnc( tag: Tag, reg: Register, reg_or_mem: RegisterOrMemory, code: *std.ArrayList(u8), ) InnerError!void { const opc = getOpCode(tag, .rm, reg.size() == 8 or reg_or_mem.size() == 8).?; switch (reg_or_mem) { .register => |src_reg| { const encoder = try Encoder.init(code, 4); if (reg.size() == 16) { encoder.prefix16BitMode(); } encoder.rex(.{ .w = setRexWRegister(reg) or setRexWRegister(src_reg), .r = reg.isExtended(), .b = src_reg.isExtended(), }); opc.encode(encoder); encoder.modRm_direct(reg.lowId(), src_reg.lowId()); }, .memory => |src_mem| { const encoder = try Encoder.init(code, 9); if (reg.size() == 16) { encoder.prefix16BitMode(); } if (src_mem.base) |base| { // TODO handle 32-bit base register - requires prefix 0x67 // Intel Manual, Vol 1, chapter 3.6 and 3.6.1 encoder.rex(.{ .w = setRexWRegister(reg), .r = reg.isExtended(), .b = base.isExtended(), }); } else { encoder.rex(.{ .w = setRexWRegister(reg), .r = reg.isExtended(), }); } opc.encode(encoder); src_mem.encode(encoder, reg.lowId()); }, } } fn lowerToMrEnc( tag: Tag, reg_or_mem: RegisterOrMemory, reg: Register, code: *std.ArrayList(u8), ) InnerError!void { const opc = getOpCode(tag, .mr, reg.size() == 8 or reg_or_mem.size() == 8).?; switch (reg_or_mem) { .register => |dst_reg| { const encoder = try Encoder.init(code, 3); if (dst_reg.size() == 16) { encoder.prefix16BitMode(); } encoder.rex(.{ .w = setRexWRegister(dst_reg) or setRexWRegister(reg), .r = reg.isExtended(), .b = dst_reg.isExtended(), }); opc.encode(encoder); encoder.modRm_direct(reg.lowId(), dst_reg.lowId()); }, .memory => |dst_mem| { const encoder = try Encoder.init(code, 9); if (reg.size() == 16) { encoder.prefix16BitMode(); } if (dst_mem.base) |base| { encoder.rex(.{ .w = dst_mem.ptr_size == .qword_ptr or setRexWRegister(reg), .r = reg.isExtended(), .b = base.isExtended(), }); } else { encoder.rex(.{ .w = dst_mem.ptr_size == .qword_ptr or setRexWRegister(reg), .r = reg.isExtended(), }); } opc.encode(encoder); dst_mem.encode(encoder, reg.lowId()); }, } } fn lowerToRmiEnc( tag: Tag, reg: Register, reg_or_mem: RegisterOrMemory, imm: u32, code: *std.ArrayList(u8), ) InnerError!void { const opc = getOpCode(tag, .rmi, false).?; const encoder = try Encoder.init(code, 13); if (reg.size() == 16) { encoder.prefix16BitMode(); } switch (reg_or_mem) { .register => |src_reg| { encoder.rex(.{ .w = setRexWRegister(reg) or setRexWRegister(src_reg), .r = reg.isExtended(), .b = src_reg.isExtended(), }); opc.encode(encoder); encoder.modRm_direct(reg.lowId(), src_reg.lowId()); }, .memory => |src_mem| { if (src_mem.base) |base| { // TODO handle 32-bit base register - requires prefix 0x67 // Intel Manual, Vol 1, chapter 3.6 and 3.6.1 encoder.rex(.{ .w = setRexWRegister(reg), .r = reg.isExtended(), .b = base.isExtended(), }); } else { encoder.rex(.{ .w = setRexWRegister(reg), .r = reg.isExtended(), }); } opc.encode(encoder); src_mem.encode(encoder, reg.lowId()); }, } encodeImm(encoder, imm, reg.size()); } fn expectEqualHexStrings(expected: []const u8, given: []const u8, assembly: []const u8) !void { assert(expected.len > 0); if (mem.eql(u8, expected, given)) return; const expected_fmt = try std.fmt.allocPrint(testing.allocator, "{x}", .{std.fmt.fmtSliceHexLower(expected)}); defer testing.allocator.free(expected_fmt); const given_fmt = try std.fmt.allocPrint(testing.allocator, "{x}", .{std.fmt.fmtSliceHexLower(given)}); defer testing.allocator.free(given_fmt); const idx = mem.indexOfDiff(u8, expected_fmt, given_fmt).?; var padding = try testing.allocator.alloc(u8, idx + 5); defer testing.allocator.free(padding); mem.set(u8, padding, ' '); std.debug.print("\nASM: {s}\nEXP: {s}\nGIV: {s}\n{s}^ -- first differing byte\n", .{ assembly, expected_fmt, given_fmt, padding, }); return error.TestFailed; } const TestEmit = struct { code_buffer: std.ArrayList(u8), next: usize = 0, fn init() TestEmit { return .{ .code_buffer = std.ArrayList(u8).init(testing.allocator), }; } fn deinit(emit: *TestEmit) void { emit.code_buffer.deinit(); emit.next = undefined; } fn code(emit: *TestEmit) *std.ArrayList(u8) { emit.next = emit.code_buffer.items.len; return &emit.code_buffer; } fn lowered(emit: TestEmit) []const u8 { return emit.code_buffer.items[emit.next..]; } }; test "lower MI encoding" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToMiEnc(.mov, RegisterOrMemory.reg(.rax), 0x10, emit.code()); try expectEqualHexStrings("\x48\xc7\xc0\x10\x00\x00\x00", emit.lowered(), "mov rax, 0x10"); try lowerToMiEnc(.mov, RegisterOrMemory.mem(.dword_ptr, .{ .disp = 0, .base = .r11 }), 0x10, emit.code()); try expectEqualHexStrings("\x41\xc7\x03\x10\x00\x00\x00", emit.lowered(), "mov dword ptr [r11 + 0], 0x10"); try lowerToMiEnc(.add, RegisterOrMemory.mem(.dword_ptr, .{ .disp = @bitCast(u32, @as(i32, -8)), .base = .rdx, }), 0x10, emit.code()); try expectEqualHexStrings("\x81\x42\xF8\x10\x00\x00\x00", emit.lowered(), "add dword ptr [rdx - 8], 0x10"); try lowerToMiEnc(.sub, RegisterOrMemory.mem(.dword_ptr, .{ .disp = 0x10000000, .base = .r11, }), 0x10, emit.code()); try expectEqualHexStrings( "\x41\x81\xab\x00\x00\x00\x10\x10\x00\x00\x00", emit.lowered(), "sub dword ptr [r11 + 0x10000000], 0x10", ); try lowerToMiEnc(.@"and", RegisterOrMemory.mem(.dword_ptr, .{ .disp = 0x10000000 }), 0x10, emit.code()); try expectEqualHexStrings( "\x81\x24\x25\x00\x00\x00\x10\x10\x00\x00\x00", emit.lowered(), "and dword ptr [ds:0x10000000], 0x10", ); try lowerToMiEnc(.@"and", RegisterOrMemory.mem(.dword_ptr, .{ .disp = 0x10000000, .base = .r12, }), 0x10, emit.code()); try expectEqualHexStrings( "\x41\x81\xA4\x24\x00\x00\x00\x10\x10\x00\x00\x00", emit.lowered(), "and dword ptr [r12 + 0x10000000], 0x10", ); try lowerToMiEnc(.mov, RegisterOrMemory.rip(.qword_ptr, 0x10), 0x10, emit.code()); try expectEqualHexStrings( "\x48\xC7\x05\x10\x00\x00\x00\x10\x00\x00\x00", emit.lowered(), "mov qword ptr [rip + 0x10], 0x10", ); try lowerToMiEnc(.mov, RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, @as(i32, -8)), .base = .rbp, }), 0x10, emit.code()); try expectEqualHexStrings( "\x48\xc7\x45\xf8\x10\x00\x00\x00", emit.lowered(), "mov qword ptr [rbp - 8], 0x10", ); try lowerToMiEnc(.mov, RegisterOrMemory.mem(.word_ptr, .{ .disp = @bitCast(u32, @as(i32, -2)), .base = .rbp, }), 0x10, emit.code()); try expectEqualHexStrings("\x66\xC7\x45\xFE\x10\x00", emit.lowered(), "mov word ptr [rbp - 2], 0x10"); try lowerToMiEnc(.mov, RegisterOrMemory.mem(.byte_ptr, .{ .disp = @bitCast(u32, @as(i32, -1)), .base = .rbp, }), 0x10, emit.code()); try expectEqualHexStrings("\xC6\x45\xFF\x10", emit.lowered(), "mov byte ptr [rbp - 1], 0x10"); try lowerToMiEnc(.mov, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0x10000000, .scale_index = .{ .scale = 1, .index = .rcx, }, }), 0x10, emit.code()); try expectEqualHexStrings( "\x48\xC7\x04\x4D\x00\x00\x00\x10\x10\x00\x00\x00", emit.lowered(), "mov qword ptr [rcx*2 + 0x10000000], 0x10", ); try lowerToMiImm8Enc(.add, RegisterOrMemory.reg(.rax), 0x10, emit.code()); try expectEqualHexStrings("\x48\x83\xC0\x10", emit.lowered(), "add rax, 0x10"); } test "lower RM encoding" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToRmEnc(.mov, .rax, RegisterOrMemory.reg(.rbx), emit.code()); try expectEqualHexStrings("\x48\x8b\xc3", emit.lowered(), "mov rax, rbx"); try lowerToRmEnc(.mov, .rax, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0, .base = .r11 }), emit.code()); try expectEqualHexStrings("\x49\x8b\x03", emit.lowered(), "mov rax, qword ptr [r11 + 0]"); try lowerToRmEnc(.add, .r11, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0x10000000 }), emit.code()); try expectEqualHexStrings( "\x4C\x03\x1C\x25\x00\x00\x00\x10", emit.lowered(), "add r11, qword ptr [ds:0x10000000]", ); try lowerToRmEnc(.add, .r12b, RegisterOrMemory.mem(.byte_ptr, .{ .disp = 0x10000000 }), emit.code()); try expectEqualHexStrings( "\x44\x02\x24\x25\x00\x00\x00\x10", emit.lowered(), "add r11b, byte ptr [ds:0x10000000]", ); try lowerToRmEnc(.sub, .r11, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0x10000000, .base = .r13, }), emit.code()); try expectEqualHexStrings( "\x4D\x2B\x9D\x00\x00\x00\x10", emit.lowered(), "sub r11, qword ptr [r13 + 0x10000000]", ); try lowerToRmEnc(.sub, .r11, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0x10000000, .base = .r12, }), emit.code()); try expectEqualHexStrings( "\x4D\x2B\x9C\x24\x00\x00\x00\x10", emit.lowered(), "sub r11, qword ptr [r12 + 0x10000000]", ); try lowerToRmEnc(.mov, .rax, RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, @as(i32, -4)), .base = .rbp, }), emit.code()); try expectEqualHexStrings("\x48\x8B\x45\xFC", emit.lowered(), "mov rax, qword ptr [rbp - 4]"); try lowerToRmEnc(.lea, .rax, RegisterOrMemory.rip(.qword_ptr, 0x10), emit.code()); try expectEqualHexStrings("\x48\x8D\x05\x10\x00\x00\x00", emit.lowered(), "lea rax, [rip + 0x10]"); try lowerToRmEnc(.mov, .rax, RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, @as(i32, -8)), .base = .rbp, .scale_index = .{ .scale = 0, .index = .rcx, }, }), emit.code()); try expectEqualHexStrings("\x48\x8B\x44\x0D\xF8", emit.lowered(), "mov rax, qword ptr [rbp + rcx*1 - 8]"); try lowerToRmEnc(.mov, .eax, RegisterOrMemory.mem(.dword_ptr, .{ .disp = @bitCast(u32, @as(i32, -4)), .base = .rbp, .scale_index = .{ .scale = 2, .index = .rdx, }, }), emit.code()); try expectEqualHexStrings("\x8B\x44\x95\xFC", emit.lowered(), "mov eax, dword ptr [rbp + rdx*4 - 4]"); try lowerToRmEnc(.mov, .rax, RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, @as(i32, -8)), .base = .rbp, .scale_index = .{ .scale = 3, .index = .rcx, }, }), emit.code()); try expectEqualHexStrings("\x48\x8B\x44\xCD\xF8", emit.lowered(), "mov rax, qword ptr [rbp + rcx*8 - 8]"); try lowerToRmEnc(.mov, .r8b, RegisterOrMemory.mem(.byte_ptr, .{ .disp = @bitCast(u32, @as(i32, -24)), .base = .rsi, .scale_index = .{ .scale = 0, .index = .rcx, }, }), emit.code()); try expectEqualHexStrings("\x44\x8A\x44\x0E\xE8", emit.lowered(), "mov r8b, byte ptr [rsi + rcx*1 - 24]"); try lowerToRmEnc(.lea, .rsi, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0, .base = .rbp, .scale_index = .{ .scale = 0, .index = .rcx, }, }), emit.code()); try expectEqualHexStrings("\x48\x8D\x74\x0D\x00", emit.lowered(), "lea rsi, qword ptr [rbp + rcx*1 + 0]"); } test "lower MR encoding" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToMrEnc(.mov, RegisterOrMemory.reg(.rax), .rbx, emit.code()); try expectEqualHexStrings("\x48\x89\xd8", emit.lowered(), "mov rax, rbx"); try lowerToMrEnc(.mov, RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, @as(i32, -4)), .base = .rbp, }), .r11, emit.code()); try expectEqualHexStrings("\x4c\x89\x5d\xfc", emit.lowered(), "mov qword ptr [rbp - 4], r11"); try lowerToMrEnc(.add, RegisterOrMemory.mem(.byte_ptr, .{ .disp = 0x10000000 }), .r12b, emit.code()); try expectEqualHexStrings( "\x44\x00\x24\x25\x00\x00\x00\x10", emit.lowered(), "add byte ptr [ds:0x10000000], r12b", ); try lowerToMrEnc(.add, RegisterOrMemory.mem(.dword_ptr, .{ .disp = 0x10000000 }), .r12d, emit.code()); try expectEqualHexStrings( "\x44\x01\x24\x25\x00\x00\x00\x10", emit.lowered(), "add dword ptr [ds:0x10000000], r12d", ); try lowerToMrEnc(.sub, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0x10000000, .base = .r11, }), .r12, emit.code()); try expectEqualHexStrings( "\x4D\x29\xA3\x00\x00\x00\x10", emit.lowered(), "sub qword ptr [r11 + 0x10000000], r12", ); try lowerToMrEnc(.mov, RegisterOrMemory.rip(.qword_ptr, 0x10), .r12, emit.code()); try expectEqualHexStrings("\x4C\x89\x25\x10\x00\x00\x00", emit.lowered(), "mov qword ptr [rip + 0x10], r12"); } test "lower OI encoding" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToOiEnc(.mov, .rax, 0x1000000000000000, emit.code()); try expectEqualHexStrings( "\x48\xB8\x00\x00\x00\x00\x00\x00\x00\x10", emit.lowered(), "movabs rax, 0x1000000000000000", ); try lowerToOiEnc(.mov, .r11, 0x1000000000000000, emit.code()); try expectEqualHexStrings( "\x49\xBB\x00\x00\x00\x00\x00\x00\x00\x10", emit.lowered(), "movabs r11, 0x1000000000000000", ); try lowerToOiEnc(.mov, .r11d, 0x10000000, emit.code()); try expectEqualHexStrings("\x41\xBB\x00\x00\x00\x10", emit.lowered(), "mov r11d, 0x10000000"); try lowerToOiEnc(.mov, .r11w, 0x1000, emit.code()); try expectEqualHexStrings("\x66\x41\xBB\x00\x10", emit.lowered(), "mov r11w, 0x1000"); try lowerToOiEnc(.mov, .r11b, 0x10, emit.code()); try expectEqualHexStrings("\x41\xB3\x10", emit.lowered(), "mov r11b, 0x10"); } test "lower FD/TD encoding" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToFdEnc(.mov, .rax, 0x1000000000000000, emit.code()); try expectEqualHexStrings( "\x48\xa1\x00\x00\x00\x00\x00\x00\x00\x10", emit.lowered(), "mov rax, ds:0x1000000000000000", ); try lowerToFdEnc(.mov, .eax, 0x10000000, emit.code()); try expectEqualHexStrings("\xa1\x00\x00\x00\x10", emit.lowered(), "mov eax, ds:0x10000000"); try lowerToFdEnc(.mov, .ax, 0x1000, emit.code()); try expectEqualHexStrings("\x66\xa1\x00\x10", emit.lowered(), "mov ax, ds:0x1000"); try lowerToFdEnc(.mov, .al, 0x10, emit.code()); try expectEqualHexStrings("\xa0\x10", emit.lowered(), "mov al, ds:0x10"); } test "lower M encoding" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToMEnc(.jmp_near, RegisterOrMemory.reg(.r12), emit.code()); try expectEqualHexStrings("\x41\xFF\xE4", emit.lowered(), "jmp r12"); try lowerToMEnc(.jmp_near, RegisterOrMemory.reg(.r12w), emit.code()); try expectEqualHexStrings("\x66\x41\xFF\xE4", emit.lowered(), "jmp r12w"); try lowerToMEnc(.jmp_near, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0, .base = .r12 }), emit.code()); try expectEqualHexStrings("\x41\xFF\x24\x24", emit.lowered(), "jmp qword ptr [r12]"); try lowerToMEnc(.jmp_near, RegisterOrMemory.mem(.word_ptr, .{ .disp = 0, .base = .r12 }), emit.code()); try expectEqualHexStrings("\x66\x41\xFF\x24\x24", emit.lowered(), "jmp word ptr [r12]"); try lowerToMEnc(.jmp_near, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0x10, .base = .r12 }), emit.code()); try expectEqualHexStrings("\x41\xFF\x64\x24\x10", emit.lowered(), "jmp qword ptr [r12 + 0x10]"); try lowerToMEnc(.jmp_near, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0x1000, .base = .r12, }), emit.code()); try expectEqualHexStrings( "\x41\xFF\xA4\x24\x00\x10\x00\x00", emit.lowered(), "jmp qword ptr [r12 + 0x1000]", ); try lowerToMEnc(.jmp_near, RegisterOrMemory.rip(.qword_ptr, 0x10), emit.code()); try expectEqualHexStrings("\xFF\x25\x10\x00\x00\x00", emit.lowered(), "jmp qword ptr [rip + 0x10]"); try lowerToMEnc(.jmp_near, RegisterOrMemory.mem(.qword_ptr, .{ .disp = 0x10 }), emit.code()); try expectEqualHexStrings("\xFF\x24\x25\x10\x00\x00\x00", emit.lowered(), "jmp qword ptr [ds:0x10]"); try lowerToMEnc(.seta, RegisterOrMemory.reg(.r11b), emit.code()); try expectEqualHexStrings("\x41\x0F\x97\xC3", emit.lowered(), "seta r11b"); try lowerToMEnc(.idiv, RegisterOrMemory.reg(.rax), emit.code()); try expectEqualHexStrings("\x48\xF7\xF8", emit.lowered(), "idiv rax"); try lowerToMEnc(.imul, RegisterOrMemory.reg(.al), emit.code()); try expectEqualHexStrings("\xF6\xE8", emit.lowered(), "imul al"); } test "lower M1 and MC encodings" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToM1Enc(.sal, RegisterOrMemory.reg(.r12), emit.code()); try expectEqualHexStrings("\x49\xD1\xE4", emit.lowered(), "sal r12, 1"); try lowerToM1Enc(.sal, RegisterOrMemory.reg(.r12d), emit.code()); try expectEqualHexStrings("\x41\xD1\xE4", emit.lowered(), "sal r12d, 1"); try lowerToM1Enc(.sal, RegisterOrMemory.reg(.r12w), emit.code()); try expectEqualHexStrings("\x66\x41\xD1\xE4", emit.lowered(), "sal r12w, 1"); try lowerToM1Enc(.sal, RegisterOrMemory.reg(.r12b), emit.code()); try expectEqualHexStrings("\x41\xD0\xE4", emit.lowered(), "sal r12b, 1"); try lowerToM1Enc(.sal, RegisterOrMemory.reg(.rax), emit.code()); try expectEqualHexStrings("\x48\xD1\xE0", emit.lowered(), "sal rax, 1"); try lowerToM1Enc(.sal, RegisterOrMemory.reg(.eax), emit.code()); try expectEqualHexStrings("\xD1\xE0", emit.lowered(), "sal eax, 1"); try lowerToM1Enc(.sal, RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, @as(i32, -0x10)), .base = .rbp, }), emit.code()); try expectEqualHexStrings("\x48\xD1\x65\xF0", emit.lowered(), "sal qword ptr [rbp - 0x10], 1"); try lowerToM1Enc(.sal, RegisterOrMemory.mem(.dword_ptr, .{ .disp = @bitCast(u32, @as(i32, -0x10)), .base = .rbp, }), emit.code()); try expectEqualHexStrings("\xD1\x65\xF0", emit.lowered(), "sal dword ptr [rbp - 0x10], 1"); try lowerToMcEnc(.shr, RegisterOrMemory.reg(.r12), emit.code()); try expectEqualHexStrings("\x49\xD3\xEC", emit.lowered(), "shr r12, cl"); try lowerToMcEnc(.shr, RegisterOrMemory.reg(.rax), emit.code()); try expectEqualHexStrings("\x48\xD3\xE8", emit.lowered(), "shr rax, cl"); try lowerToMcEnc(.sar, RegisterOrMemory.reg(.rsi), emit.code()); try expectEqualHexStrings("\x48\xD3\xFE", emit.lowered(), "sar rsi, cl"); } test "lower O encoding" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToOEnc(.pop, .r12, emit.code()); try expectEqualHexStrings("\x41\x5c", emit.lowered(), "pop r12"); try lowerToOEnc(.push, .r12w, emit.code()); try expectEqualHexStrings("\x66\x41\x54", emit.lowered(), "push r12w"); } test "lower RMI encoding" { var emit = TestEmit.init(); defer emit.deinit(); try lowerToRmiEnc(.imul, .rax, RegisterOrMemory.mem(.qword_ptr, .{ .disp = @bitCast(u32, @as(i32, -8)), .base = .rbp, }), 0x10, emit.code()); try expectEqualHexStrings( "\x48\x69\x45\xF8\x10\x00\x00\x00", emit.lowered(), "imul rax, qword ptr [rbp - 8], 0x10", ); try lowerToRmiEnc(.imul, .eax, RegisterOrMemory.mem(.dword_ptr, .{ .disp = @bitCast(u32, @as(i32, -4)), .base = .rbp, }), 0x10, emit.code()); try expectEqualHexStrings("\x69\x45\xFC\x10\x00\x00\x00", emit.lowered(), "imul eax, dword ptr [rbp - 4], 0x10"); try lowerToRmiEnc(.imul, .ax, RegisterOrMemory.mem(.word_ptr, .{ .disp = @bitCast(u32, @as(i32, -2)), .base = .rbp, }), 0x10, emit.code()); try expectEqualHexStrings("\x66\x69\x45\xFE\x10\x00", emit.lowered(), "imul ax, word ptr [rbp - 2], 0x10"); try lowerToRmiEnc(.imul, .r12, RegisterOrMemory.reg(.r12), 0x10, emit.code()); try expectEqualHexStrings("\x4D\x69\xE4\x10\x00\x00\x00", emit.lowered(), "imul r12, r12, 0x10"); try lowerToRmiEnc(.imul, .r12w, RegisterOrMemory.reg(.r12w), 0x10, emit.code()); try expectEqualHexStrings("\x66\x45\x69\xE4\x10\x00", emit.lowered(), "imul r12w, r12w, 0x10"); }
src/arch/x86_64/Emit.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const root = @import("root"); const mem = std.mem; pub const default_stack_size = 1 * 1024 * 1024; pub const stack_size: usize = if (@hasDecl(root, "stack_size_std_io_OutStream")) root.stack_size_std_io_OutStream else default_stack_size; /// TODO this is not integrated with evented I/O yet. /// https://github.com/ziglang/zig/issues/3557 pub fn OutStream(comptime WriteError: type) type { return struct { const Self = @This(); pub const Error = WriteError; // TODO https://github.com/ziglang/zig/issues/3557 pub const WriteFn = if (std.io.is_async and false) async fn (self: *Self, bytes: []const u8) Error!void else fn (self: *Self, bytes: []const u8) Error!void; writeFn: WriteFn, pub fn write(self: *Self, bytes: []const u8) Error!void { // TODO https://github.com/ziglang/zig/issues/3557 if (std.io.is_async and false) { // Let's not be writing 0xaa in safe modes for upwards of 4 MiB for every stream write. @setRuntimeSafety(false); var stack_frame: [stack_size]u8 align(std.Target.stack_align) = undefined; return await @asyncCall(&stack_frame, {}, self.writeFn, self, bytes); } else { return self.writeFn(self, bytes); } } pub fn print(self: *Self, comptime format: []const u8, args: var) Error!void { return std.fmt.format(self, Error, self.writeFn, format, args); } pub fn writeByte(self: *Self, byte: u8) Error!void { const slice = @as(*const [1]u8, &byte)[0..]; return self.writeFn(self, slice); } pub fn writeByteNTimes(self: *Self, byte: u8, n: usize) Error!void { var bytes: [256]u8 = undefined; mem.set(u8, bytes[0..], byte); var remaining: usize = n; while (remaining > 0) { const to_write = std.math.min(remaining, bytes.len); try self.writeFn(self, bytes[0..to_write]); remaining -= to_write; } } /// Write a native-endian integer. pub fn writeIntNative(self: *Self, comptime T: type, value: T) Error!void { var bytes: [(T.bit_count + 7) / 8]u8 = undefined; mem.writeIntNative(T, &bytes, value); return self.writeFn(self, &bytes); } /// Write a foreign-endian integer. pub fn writeIntForeign(self: *Self, comptime T: type, value: T) Error!void { var bytes: [(T.bit_count + 7) / 8]u8 = undefined; mem.writeIntForeign(T, &bytes, value); return self.writeFn(self, &bytes); } pub fn writeIntLittle(self: *Self, comptime T: type, value: T) Error!void { var bytes: [(T.bit_count + 7) / 8]u8 = undefined; mem.writeIntLittle(T, &bytes, value); return self.writeFn(self, &bytes); } pub fn writeIntBig(self: *Self, comptime T: type, value: T) Error!void { var bytes: [(T.bit_count + 7) / 8]u8 = undefined; mem.writeIntBig(T, &bytes, value); return self.writeFn(self, &bytes); } pub fn writeInt(self: *Self, comptime T: type, value: T, endian: builtin.Endian) Error!void { var bytes: [(T.bit_count + 7) / 8]u8 = undefined; mem.writeInt(T, &bytes, value, endian); return self.writeFn(self, &bytes); } }; }
lib/std/io/out_stream.zig
usingnamespace @import("bits.zig"); pub const SOCKET = *@OpaqueType(); pub const INVALID_SOCKET = @intToPtr(SOCKET, ~@as(usize, 0)); pub const SOCKET_ERROR = -1; pub const WSADESCRIPTION_LEN = 256; pub const WSASYS_STATUS_LEN = 128; pub const WSADATA = if (usize.bit_count == u64.bit_count) extern struct { wVersion: WORD, wHighVersion: WORD, iMaxSockets: u16, iMaxUdpDg: u16, lpVendorInfo: *u8, szDescription: [WSADESCRIPTION_LEN + 1]u8, szSystemStatus: [WSASYS_STATUS_LEN + 1]u8, } else extern struct { wVersion: WORD, wHighVersion: WORD, szDescription: [WSADESCRIPTION_LEN + 1]u8, szSystemStatus: [WSASYS_STATUS_LEN + 1]u8, iMaxSockets: u16, iMaxUdpDg: u16, lpVendorInfo: *u8, }; pub const MAX_PROTOCOL_CHAIN = 7; pub const WSAPROTOCOLCHAIN = extern struct { ChainLen: c_int, ChainEntries: [MAX_PROTOCOL_CHAIN]DWORD, }; pub const WSAPROTOCOL_LEN = 255; pub const WSAPROTOCOL_INFOA = extern struct { dwServiceFlags1: DWORD, dwServiceFlags2: DWORD, dwServiceFlags3: DWORD, dwServiceFlags4: DWORD, dwProviderFlags: DWORD, ProviderId: GUID, dwCatalogEntryId: DWORD, ProtocolChain: WSAPROTOCOLCHAIN, iVersion: c_int, iAddressFamily: c_int, iMaxSockAddr: c_int, iMinSockAddr: c_int, iSocketType: c_int, iProtocol: c_int, iProtocolMaxOffset: c_int, iNetworkByteOrder: c_int, iSecurityScheme: c_int, dwMessageSize: DWORD, dwProviderReserved: DWORD, szProtocol: [WSAPROTOCOL_LEN + 1]CHAR, }; pub const WSAPROTOCOL_INFOW = extern struct { dwServiceFlags1: DWORD, dwServiceFlags2: DWORD, dwServiceFlags3: DWORD, dwServiceFlags4: DWORD, dwProviderFlags: DWORD, ProviderId: GUID, dwCatalogEntryId: DWORD, ProtocolChain: WSAPROTOCOLCHAIN, iVersion: c_int, iAddressFamily: c_int, iMaxSockAddr: c_int, iMinSockAddr: c_int, iSocketType: c_int, iProtocol: c_int, iProtocolMaxOffset: c_int, iNetworkByteOrder: c_int, iSecurityScheme: c_int, dwMessageSize: DWORD, dwProviderReserved: DWORD, szProtocol: [WSAPROTOCOL_LEN + 1]WCHAR, }; pub const GROUP = u32; pub const SG_UNCONSTRAINED_GROUP = 0x1; pub const SG_CONSTRAINED_GROUP = 0x2; pub const WSA_FLAG_OVERLAPPED = 0x01; pub const WSA_FLAG_MULTIPOINT_C_ROOT = 0x02; pub const WSA_FLAG_MULTIPOINT_C_LEAF = 0x04; pub const WSA_FLAG_MULTIPOINT_D_ROOT = 0x08; pub const WSA_FLAG_MULTIPOINT_D_LEAF = 0x10; pub const WSA_FLAG_ACCESS_SYSTEM_SECURITY = 0x40; pub const WSA_FLAG_NO_HANDLE_INHERIT = 0x80; pub const WSAEVENT = HANDLE; pub const WSAOVERLAPPED = extern struct { Internal: DWORD, InternalHigh: DWORD, Offset: DWORD, OffsetHigh: DWORD, hEvent: ?WSAEVENT, }; pub const WSAOVERLAPPED_COMPLETION_ROUTINE = extern fn (dwError: DWORD, cbTransferred: DWORD, lpOverlapped: *WSAOVERLAPPED, dwFlags: DWORD) void; pub const ADDRESS_FAMILY = u16; // Microsoft use the signed c_int for this, but it should never be negative const socklen_t = u32; pub const AF_UNSPEC = 0; pub const AF_UNIX = 1; pub const AF_INET = 2; pub const AF_IMPLINK = 3; pub const AF_PUP = 4; pub const AF_CHAOS = 5; pub const AF_NS = 6; pub const AF_IPX = AF_NS; pub const AF_ISO = 7; pub const AF_OSI = AF_ISO; pub const AF_ECMA = 8; pub const AF_DATAKIT = 9; pub const AF_CCITT = 10; pub const AF_SNA = 11; pub const AF_DECnet = 12; pub const AF_DLI = 13; pub const AF_LAT = 14; pub const AF_HYLINK = 15; pub const AF_APPLETALK = 16; pub const AF_NETBIOS = 17; pub const AF_VOICEVIEW = 18; pub const AF_FIREFOX = 19; pub const AF_UNKNOWN1 = 20; pub const AF_BAN = 21; pub const AF_ATM = 22; pub const AF_INET6 = 23; pub const AF_CLUSTER = 24; pub const AF_12844 = 25; pub const AF_IRDA = 26; pub const AF_NETDES = 28; pub const AF_TCNPROCESS = 29; pub const AF_TCNMESSAGE = 30; pub const AF_ICLFXBM = 31; pub const AF_BTH = 32; pub const AF_MAX = 33; 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 IPPROTO_ICMP = 1; pub const IPPROTO_IGMP = 2; pub const BTHPROTO_RFCOMM = 3; pub const IPPROTO_TCP = 6; pub const IPPROTO_UDP = 17; pub const IPPROTO_ICMPV6 = 58; pub const IPPROTO_RM = 113; pub const sockaddr = extern struct { family: ADDRESS_FAMILY, data: [14]u8, }; /// IPv4 socket address pub const sockaddr_in = extern struct { family: ADDRESS_FAMILY = AF_INET, port: USHORT, addr: u32, zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }, }; /// IPv6 socket address pub const sockaddr_in6 = extern struct { family: ADDRESS_FAMILY = AF_INET6, port: USHORT, flowinfo: u32, addr: [16]u8, scope_id: u32, }; /// UNIX domain socket address pub const sockaddr_un = extern struct { family: ADDRESS_FAMILY = AF_UNIX, path: [108]u8, }; pub const WSABUF = extern struct { len: ULONG, buf: [*]u8, }; pub const WSAMSG = extern struct { name: *const sockaddr, namelen: INT, lpBuffers: [*]WSABUF, dwBufferCount: DWORD, Control: WSABUF, dwFlags: DWORD, }; pub const WSA_INVALID_HANDLE = 6; pub const WSA_NOT_ENOUGH_MEMORY = 8; pub const WSA_INVALID_PARAMETER = 87; pub const WSA_OPERATION_ABORTED = 995; pub const WSA_IO_INCOMPLETE = 996; pub const WSA_IO_PENDING = 997; pub const WSAEINTR = 10004; pub const WSAEBADF = 10009; pub const WSAEACCES = 10013; pub const WSAEFAULT = 10014; pub const WSAEINVAL = 10022; pub const WSAEMFILE = 10024; pub const WSAEWOULDBLOCK = 10035; pub const WSAEINPROGRESS = 10036; pub const WSAEALREADY = 10037; pub const WSAENOTSOCK = 10038; pub const WSAEDESTADDRREQ = 10039; pub const WSAEMSGSIZE = 10040; pub const WSAEPROTOTYPE = 10041; pub const WSAENOPROTOOPT = 10042; pub const WSAEPROTONOSUPPORT = 10043; pub const WSAESOCKTNOSUPPORT = 10044; pub const WSAEOPNOTSUPP = 10045; pub const WSAEPFNOSUPPORT = 10046; pub const WSAEAFNOSUPPORT = 10047; pub const WSAEADDRINUSE = 10048; pub const WSAEADDRNOTAVAIL = 10049; pub const WSAENETDOWN = 10050; pub const WSAENETUNREACH = 10051; pub const WSAENETRESET = 10052; pub const WSAECONNABORTED = 10053; pub const WSAECONNRESET = 10054; pub const WSAENOBUFS = 10055; pub const WSAEISCONN = 10056; pub const WSAENOTCONN = 10057; pub const WSAESHUTDOWN = 10058; pub const WSAETOOMANYREFS = 10059; pub const WSAETIMEDOUT = 10060; pub const WSAECONNREFUSED = 10061; pub const WSAELOOP = 10062; pub const WSAENAMETOOLONG = 10063; pub const WSAEHOSTDOWN = 10064; pub const WSAEHOSTUNREACH = 10065; pub const WSAENOTEMPTY = 10066; pub const WSAEPROCLIM = 10067; pub const WSAEUSERS = 10068; pub const WSAEDQUOT = 10069; pub const WSAESTALE = 10070; pub const WSAEREMOTE = 10071; pub const WSASYSNOTREADY = 10091; pub const WSAVERNOTSUPPORTED = 10092; pub const WSANOTINITIALISED = 10093; pub const WSAEDISCON = 10101; pub const WSAENOMORE = 10102; pub const WSAECANCELLED = 10103; pub const WSAEINVALIDPROCTABLE = 10104; pub const WSAEINVALIDPROVIDER = 10105; pub const WSAEPROVIDERFAILEDINIT = 10106; pub const WSASYSCALLFAILURE = 10107; pub const WSASERVICE_NOT_FOUND = 10108; pub const WSATYPE_NOT_FOUND = 10109; pub const WSA_E_NO_MORE = 10110; pub const WSA_E_CANCELLED = 10111; pub const WSAEREFUSED = 10112; pub const WSAHOST_NOT_FOUND = 11001; pub const WSATRY_AGAIN = 11002; pub const WSANO_RECOVERY = 11003; pub const WSANO_DATA = 11004; pub const WSA_QOS_RECEIVERS = 11005; pub const WSA_QOS_SENDERS = 11006; pub const WSA_QOS_NO_SENDERS = 11007; pub const WSA_QOS_NO_RECEIVERS = 11008; pub const WSA_QOS_REQUEST_CONFIRMED = 11009; pub const WSA_QOS_ADMISSION_FAILURE = 11010; pub const WSA_QOS_POLICY_FAILURE = 11011; pub const WSA_QOS_BAD_STYLE = 11012; pub const WSA_QOS_BAD_OBJECT = 11013; pub const WSA_QOS_TRAFFIC_CTRL_ERROR = 11014; pub const WSA_QOS_GENERIC_ERROR = 11015; pub const WSA_QOS_ESERVICETYPE = 11016; pub const WSA_QOS_EFLOWSPEC = 11017; pub const WSA_QOS_EPROVSPECBUF = 11018; pub const WSA_QOS_EFILTERSTYLE = 11019; pub const WSA_QOS_EFILTERTYPE = 11020; pub const WSA_QOS_EFILTERCOUNT = 11021; pub const WSA_QOS_EOBJLENGTH = 11022; pub const WSA_QOS_EFLOWCOUNT = 11023; pub const WSA_QOS_EUNKOWNPSOBJ = 11024; pub const WSA_QOS_EPOLICYOBJ = 11025; pub const WSA_QOS_EFLOWDESC = 11026; pub const WSA_QOS_EPSFLOWSPEC = 11027; pub const WSA_QOS_EPSFILTERSPEC = 11028; pub const WSA_QOS_ESDMODEOBJ = 11029; pub const WSA_QOS_ESHAPERATEOBJ = 11030; pub const WSA_QOS_RESERVED_PETYPE = 11031; /// no parameters const IOC_VOID = 0x80000000; /// copy out parameters const IOC_OUT = 0x40000000; /// copy in parameters const IOC_IN = 0x80000000; /// The IOCTL is a generic Windows Sockets 2 IOCTL code. New IOCTL codes defined for Windows Sockets 2 will have T == 1. const IOC_WS2 = 0x08000000; pub const SIO_BASE_HANDLE = IOC_OUT | IOC_WS2 | 34; pub extern "ws2_32" stdcallcc fn WSAStartup( wVersionRequired: WORD, lpWSAData: *WSADATA, ) c_int; pub extern "ws2_32" stdcallcc fn WSACleanup() c_int; pub extern "ws2_32" stdcallcc fn WSAGetLastError() c_int; pub extern "ws2_32" stdcallcc fn WSASocketA( af: c_int, type: c_int, protocol: c_int, lpProtocolInfo: ?*WSAPROTOCOL_INFOA, g: GROUP, dwFlags: DWORD, ) SOCKET; pub extern "ws2_32" stdcallcc fn WSASocketW( af: c_int, type: c_int, protocol: c_int, lpProtocolInfo: ?*WSAPROTOCOL_INFOW, g: GROUP, dwFlags: DWORD, ) SOCKET; pub extern "ws2_32" stdcallcc fn closesocket(s: SOCKET) c_int; pub extern "ws2_32" stdcallcc fn WSAIoctl( s: SOCKET, dwIoControlCode: DWORD, lpvInBuffer: ?*const c_void, cbInBuffer: DWORD, lpvOutBuffer: ?LPVOID, cbOutBuffer: DWORD, lpcbBytesReturned: LPDWORD, lpOverlapped: ?*WSAOVERLAPPED, lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE, ) c_int; pub extern "ws2_32" stdcallcc fn accept( s: SOCKET, addr: ?*sockaddr, addrlen: socklen_t, ) SOCKET; pub extern "ws2_32" stdcallcc fn connect( s: SOCKET, name: *const sockaddr, namelen: socklen_t, ) c_int; pub extern "ws2_32" stdcallcc fn WSARecv( s: SOCKET, lpBuffers: [*]const WSABUF, dwBufferCount: DWORD, lpNumberOfBytesRecvd: ?*DWORD, lpFlags: *DWORD, lpOverlapped: ?*WSAOVERLAPPED, lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE, ) c_int; pub extern "ws2_32" stdcallcc fn WSARecvFrom( s: SOCKET, lpBuffers: [*]const WSABUF, dwBufferCount: DWORD, lpNumberOfBytesRecvd: ?*DWORD, lpFlags: *DWORD, lpFrom: ?*sockaddr, lpFromlen: socklen_t, lpOverlapped: ?*WSAOVERLAPPED, lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE, ) c_int; pub extern "ws2_32" stdcallcc fn WSASend( s: SOCKET, lpBuffers: [*]WSABUF, dwBufferCount: DWORD, lpNumberOfBytesSent: ?*DWORD, dwFlags: DWORD, lpOverlapped: ?*WSAOVERLAPPED, lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE, ) c_int; pub extern "ws2_32" stdcallcc fn WSASendTo( s: SOCKET, lpBuffers: [*]WSABUF, dwBufferCount: DWORD, lpNumberOfBytesSent: ?*DWORD, dwFlags: DWORD, lpTo: ?*const sockaddr, iTolen: socklen_t, lpOverlapped: ?*WSAOVERLAPPED, lpCompletionRoutine: ?WSAOVERLAPPED_COMPLETION_ROUTINE, ) c_int;
lib/std/os/windows/ws2_32.zig
const std = @import("std"); const assert = std.debug.assert; const Sha256 = std.crypto.hash.sha2.Sha256; const zephyr = @import("zephyr.zig"); const sys = @import("src/sys.zig"); const FlashArea = sys.flash.FlashArea; // An open image. pub const Image = struct { const Self = @This(); id: u8, header: ImageHeader, fa: *const FlashArea, pub fn init(id: u8) !Image { const fa = try FlashArea.open(id); errdefer fa.close(); var header: ImageHeader = undefined; var bytes = std.mem.asBytes(&header); try fa.read(0, bytes); if (header.magic != IMAGE_MAGIC) return error.InvalidImage; return Self{ .id = id, .header = header, .fa = fa, }; } pub fn deinit(self: *Self) void { self.fa.close(); } // Read a structure from flash at the given offset. pub fn readStruct(self: *Self, comptime T: type, offset: u32) !T { var data: T = undefined; var bytes = std.mem.asBytes(&data); try self.fa.read(offset, bytes); return data; } }; // For testing on the LPC, with Debug enabled, this code is easily // larger than 32k. Rather than change the partition table, we will // just use slots 2 and 4 (and 5 as scratch). Scratch is kind of // silly, since there is no support for swap on this target yet. pub const Slot = enum(u8) { PrimarySecure = 1, PrimaryNS = 2, UpgradeSecure = 3, UpgradeNS = 4, }; // The image header. pub const ImageHeader = extern struct { const Self = @This(); magic: u32, load_addr: u32, hdr_size: u16, protect_tlv_size: u16, img_size: u32, flags: u32, ver: ImageVersion, pad1: u32, pub fn imageStart(self: *const Self) u32 { return self.hdr_size; } pub fn tlvBase(self: *const Self) u32 { return @as(u32, self.hdr_size) + self.img_size; } pub fn protectedSize(self: *const Self) u32 { return @as(u32, self.hdr_size) + self.img_size + self.protect_tlv_size; } }; comptime { assert(@sizeOf(ImageHeader) == 32); } // The version (non-semantic). pub const ImageVersion = extern struct { major: u8, minor: u8, revision: u16, build_num: u32, }; pub const IMAGE_MAGIC = 0x96f3b83d; // Load the header from the given slot. pub fn load_header(id: u8) !ImageHeader { var header: ImageHeader = undefined; var bytes = std.mem.asBytes(&header); const fa = try FlashArea.open(id); defer fa.close(); try fa.read(0, bytes); // std.log.info("Header: {any}", .{header}); if (header.magic != IMAGE_MAGIC) return error.InvalidImage; return header; } pub fn dump_layout() !void { // Show all of the flash areas. var id: u8 = 0; while (true) : (id += 1) { const p0 = FlashArea.open(id) catch |err| { if (err == error.ENOENT) break; return err; }; defer p0.close(); std.log.info("Partition {} 0x{x:8} (size 0x{x:8})", .{ p0.id, p0.off, p0.size }); } } // Hash the image. pub fn hash_image(fa: *const FlashArea, header: *const ImageHeader, hash: *[32]u8) !void { std.log.info("Hashing image, tlv: {x:>8}", .{header.tlvBase()}); var buf: [256]u8 = undefined; var h = Sha256.init(.{}); const len = header.protectedSize(); var pos: u32 = 0; while (pos < len) { var count = len - pos; if (count > buf.len) count = buf.len; try fa.read(0 + pos, buf[0..count]); h.update(buf[0..count]); pos += count; } h.final(hash[0..]); zephyr.print("Hash: ", .{}); for (hash) |ch| { zephyr.print("{x:>2}", .{ch}); } zephyr.print("\n", .{}); } // Hashing benchmark, with SHA256. pub fn hash_bench(fa: *const FlashArea, count: usize) !void { try hash_core(struct { const Self = @This(); pub const size = 32; state: Sha256, pub fn init() Self { return .{ .state = Sha256.init(.{}), }; } pub fn update(self: *Self, buf: []const u8) void { self.state.update(buf); } pub fn final(self: *Self, out: *[size]u8) void { self.state.final(out); } }, fa, count); } pub fn null_bench(fa: *const FlashArea, count: usize) !void { try hash_core(struct { const Self = @This(); pub const size = 4; state: u32, pub fn init() Self { return .{ .state = 42 }; } pub fn update(self: *Self, buf: []const u8) void { _ = self; _ = buf; } pub fn final(self: *Self, out: *[size]u8) void { _ = self; std.mem.copy(u8, out, std.mem.asBytes(&self.state)); } }, fa, count); } pub fn murmur_bench(fa: *const FlashArea, count: usize) !void { try hash_core(struct { const Self = @This(); pub const size = 4; state: ?u32, pub fn init() Self { return .{ .state = null }; } pub fn update(self: *Self, buf: []const u8) void { if (self.state) |state| { // This really isn't right, since it can't be chained // like this. self.state = std.hash.Murmur2_32.hashWithSeed(buf, state); } else { self.state = std.hash.Murmur2_32.hash(buf); } } pub fn final(self: *Self, out: *[size]u8) void { if (self.state) |state| { _ = out; _ = state; std.mem.copy(u8, out, std.mem.asBytes(&state)); } else { unreachable; } } }, fa, count); } pub fn sip_bench(fa: *const FlashArea, count: usize) !void { const Sip = std.crypto.hash.sip.SipHash64(2, 4); try hash_core(struct { const Self = @This(); pub const size = Sip.mac_length; state: Sip, pub fn init() Self { var key: [Sip.key_length]u8 = undefined; std.mem.set(u8, &key, 0); key[0] = 1; return .{ .state = Sip.init(&key) }; } pub fn update(self: *Self, buf: []const u8) void { self.state.update(buf); } pub fn final(self: *Self, out: *[size]u8) void { self.state.final(out); } }, fa, count); } fn hash_core(Core: anytype, fa: *const FlashArea, count: usize) !void { const BUFSIZE = 128; const PAGESIZE = 512; var buf: [BUFSIZE]u8 = undefined; var hash: [Core.size]u8 = undefined; var i: usize = 0; while (i < count) : (i += 1) { var h = Core.init(); var pos: u32 = 0; while (pos < PAGESIZE) { var todo = PAGESIZE - pos; if (todo > BUFSIZE) todo = BUFSIZE; _ = fa; // try fa.read(0 + pos, buf[0..todo]); h.update(buf[0..todo]); pos += todo; } h.final(&hash); std.mem.doNotOptimizeAway(&hash[0]); } } // A small hashing benchmarking. Hashes a single page 'n' times. fn hash_bench2(fa: *const FlashArea, count: usize) !void { const BUFSIZE = 128; const PAGESIZE = 512; var buf: [BUFSIZE]u8 = undefined; var hash: [32]u8 = undefined; var i: usize = 0; while (i < count) : (i += 1) { var h = Sha256.init(.{}); var pos: u32 = 0; while (pos < PAGESIZE) { var todo = PAGESIZE - pos; if (todo > BUFSIZE) todo = BUFSIZE; try fa.read(0 + pos, buf[0..todo]); h.update(buf[0..todo]); pos += todo; } h.final(hash[0..]); } }
image.zig
const Window = @This(); const std = @import("std"); const xcb = @import("bindings.zig"); const Core = @import("Core.zig"); const types = @import("../main.zig"); core: *Core, window: u32 = undefined, width: u16, height: u16, pub fn init(core: *Core, info: types.WindowInfo) !*Window { var self = try core.allocator.create(Window); errdefer core.allocator.destroy(self); self.core = core; self.window = xcb.generateId(core.connection); _ = xcb.createWindow( core.connection, 0, self.window, core.screen.root, 0, 0, info.width, info.height, 0, xcb.WindowClass.InputOutput, core.screen.root_visual, 0, null, ); var value = @enumToInt(xcb.EventMask.KeyPress); value |= @enumToInt(xcb.EventMask.KeyRelease); value |= @enumToInt(xcb.EventMask.ButtonPress); value |= @enumToInt(xcb.EventMask.ButtonRelease); value |= @enumToInt(xcb.EventMask.PointerMotion); value |= @enumToInt(xcb.EventMask.FocusChange); value |= @enumToInt(xcb.EventMask.EnterWindow); value |= @enumToInt(xcb.EventMask.LeaveWindow); value |= @enumToInt(xcb.EventMask.StructureNotify); _ = xcb.changeWindowAttributes( core.connection, self.window, @enumToInt(xcb.Cw.EventMask), &[_]u32{value}, ); _ = xcb.mapWindow(core.connection, self.window); if (info.title) |t| self.setTitle(t); return self; } pub fn deinit(window: *Window) void { xcb.destroyWindow(window.core.connection, window.window); window.core.allocator.destroy(window); } pub fn setTitle(window: *Window, title: []const u8) void { _ = xcb.changeProperty( window.core.connection, .Replace, window.window, @enumToInt(xcb.Defines.Atom.WmName), @enumToInt(xcb.Defines.Atom.String), @bitSizeOf(u8), @intCast(u32, title.len), @ptrCast(*const anyopaque, title), ); } pub fn setSize(window: *Window, width: u16, height: u16) void { const values: []u16 = &.{ width, height }; _ = xcb.configureWindow( window.core.connection, window.window, @enumToInt(xcb.Defines.Config.WindowWidth) | @enumToInt(xcb.Defines.Config.WindowHeight), @ptrCast(*anyopaque, values), ); window.width = width; window.height = height; } pub fn getSize(window: *Window) types.Dim { const cookie = xcb.getGeometry(window.core.connection, window.window); const reply = xcb.getGeometryReply(window.core.connection, cookie, null); defer std.c.free(reply); return .{ .width = reply.width, .height = reply.height }; }
src/xcb/Window.zig
const Buffer = @import("Buffer.zig"); const Sampler = @import("Sampler.zig"); const Texture = @import("Texture.zig"); const TextureView = @import("TextureView.zig"); const ShaderModule = @import("ShaderModule.zig"); const QuerySet = @import("QuerySet.zig"); const StencilFaceState = @import("data.zig").StencilFaceState; const Color = @import("data.zig").Color; const VertexBufferLayout = @import("data.zig").VertexBufferLayout; const BlendState = @import("data.zig").BlendState; const Origin3D = @import("data.zig").Origin3D; const PrimitiveTopology = @import("enums.zig").PrimitiveTopology; const IndexFormat = @import("enums.zig").IndexFormat; const FrontFace = @import("enums.zig").FrontFace; const CullMode = @import("enums.zig").CullMode; const StorageTextureAccess = @import("enums.zig").StorageTextureAccess; const CompareFunction = @import("enums.zig").CompareFunction; const ComputePassTimestampLocation = @import("enums.zig").ComputePassTimestampLocation; const RenderPassTimestampLocation = @import("enums.zig").RenderPassTimestampLocation; const LoadOp = @import("enums.zig").LoadOp; const StoreOp = @import("enums.zig").StoreOp; const ColorWriteMask = @import("enums.zig").ColorWriteMask; const ErrorType = @import("enums.zig").ErrorType; const LoggingType = @import("enums.zig").LoggingType; pub const MultisampleState = struct { count: u32, mask: u32, alpha_to_coverage_enabled: bool, }; pub const PrimitiveState = struct { topology: PrimitiveTopology, strip_index_format: IndexFormat, front_face: FrontFace, cull_mode: CullMode, }; pub const StorageTextureBindingLayout = extern struct { reserved: ?*anyopaque = null, access: StorageTextureAccess, format: Texture.Format, view_dimension: TextureView.Dimension, }; pub const DepthStencilState = struct { format: Texture.Format, depth_write_enabled: bool, depth_compare: CompareFunction, stencil_front: StencilFaceState, stencil_back: StencilFaceState, stencil_read_mask: u32, stencil_write_mask: u32, depth_bias: i32, depth_bias_slope_scale: f32, depth_bias_clamp: f32, }; // TODO: how does this map to browser API? pub const ConstantEntry = extern struct { reserved: ?*anyopaque = null, key: [*:0]const u8, value: f64, }; pub const ProgrammableStageDescriptor = struct { label: ?[*:0]const u8 = null, module: ShaderModule, entry_point: [*:0]const u8, constants: ?[]const ConstantEntry, }; pub const ComputePassTimestampWrite = struct { query_set: QuerySet, query_index: u32, location: ComputePassTimestampLocation, }; pub const RenderPassTimestampWrite = struct { query_set: QuerySet, query_index: u32, location: RenderPassTimestampLocation, }; pub const RenderPassDepthStencilAttachment = struct { view: TextureView, depth_load_op: LoadOp, depth_store_op: StoreOp, clear_depth: f32, depth_clear_value: f32, depth_read_only: bool, stencil_load_op: LoadOp, stencil_store_op: StoreOp, clear_stencil: u32, stencil_clear_value: u32, stencil_read_only: bool, }; pub const RenderPassColorAttachment = struct { view: TextureView, resolve_target: ?TextureView, load_op: LoadOp, store_op: StoreOp, clear_value: Color, }; pub const VertexState = struct { module: ShaderModule, entry_point: [*:0]const u8, constants: ?[]const ConstantEntry = null, buffers: ?[]const VertexBufferLayout = null, }; pub const FragmentState = struct { module: ShaderModule, entry_point: [*:0]const u8, constants: ?[]const ConstantEntry = null, targets: ?[]const ColorTargetState = null, }; pub const ColorTargetState = extern struct { reserved: ?*anyopaque = null, format: Texture.Format, blend: *const BlendState, write_mask: ColorWriteMask, }; pub const ImageCopyBuffer = struct { layout: Texture.DataLayout, buffer: Buffer, }; pub const ImageCopyTexture = struct { texture: Texture, mip_level: u32, origin: Origin3D, aspect: Texture.Aspect, }; pub const ErrorCallback = struct { type_erased_ctx: *anyopaque, type_erased_callback: fn (ctx: *anyopaque, typ: ErrorType, message: [*:0]const u8) callconv(.Inline) void, pub fn init( comptime Context: type, ctx: Context, comptime callback: fn (ctx: Context, typ: ErrorType, message: [*:0]const u8) void, ) ErrorCallback { const erased = (struct { pub inline fn erased(type_erased_ctx: *anyopaque, typ: ErrorType, message: [*:0]const u8) void { callback(if (Context == void) {} else @ptrCast(Context, @alignCast(@alignOf(Context), type_erased_ctx)), typ, message); } }).erased; return .{ .type_erased_ctx = if (Context == void) undefined else ctx, .type_erased_callback = erased, }; } }; pub const LoggingCallback = struct { type_erased_ctx: *anyopaque, type_erased_callback: fn (ctx: *anyopaque, typ: LoggingType, message: [*:0]const u8) callconv(.Inline) void, pub fn init( comptime Context: type, ctx: Context, comptime callback: fn (ctx: Context, typ: LoggingType, message: [*:0]const u8) void, ) LoggingCallback { const erased = (struct { pub inline fn erased(type_erased_ctx: *anyopaque, typ: LoggingType, message: [*:0]const u8) void { callback(if (Context == void) {} else @ptrCast(Context, @alignCast(@alignOf(Context), type_erased_ctx)), typ, message); } }).erased; return .{ .type_erased_ctx = if (Context == void) undefined else ctx, .type_erased_callback = erased, }; } }; test { _ = MultisampleState; _ = PrimitiveState; _ = StorageTextureBindingLayout; _ = DepthStencilState; _ = ConstantEntry; _ = ProgrammableStageDescriptor; _ = ComputePassTimestampWrite; _ = RenderPassTimestampWrite; _ = RenderPassDepthStencilAttachment; _ = RenderPassColorAttachment; _ = VertexState; _ = FragmentState; _ = ImageCopyBuffer; _ = ImageCopyTexture; _ = ErrorCallback; _ = LoggingCallback; }
gpu/src/structs.zig
const std = @import("std"); const mem = std.mem; const ChangesWhenUppercased = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 97, hi: u21 = 125251, pub fn init(allocator: *mem.Allocator) !ChangesWhenUppercased { var instance = ChangesWhenUppercased{ .allocator = allocator, .array = try allocator.alloc(bool, 125155), }; mem.set(bool, instance.array, false); var index: u21 = 0; index = 0; while (index <= 25) : (index += 1) { instance.array[index] = true; } instance.array[84] = true; index = 126; while (index <= 149) : (index += 1) { instance.array[index] = true; } index = 151; while (index <= 158) : (index += 1) { instance.array[index] = true; } instance.array[160] = true; instance.array[162] = true; instance.array[164] = true; instance.array[166] = true; instance.array[168] = true; instance.array[170] = true; instance.array[172] = true; instance.array[174] = true; instance.array[176] = true; instance.array[178] = true; instance.array[180] = true; instance.array[182] = true; instance.array[184] = true; instance.array[186] = true; instance.array[188] = true; instance.array[190] = true; instance.array[192] = true; instance.array[194] = true; instance.array[196] = true; instance.array[198] = true; instance.array[200] = true; instance.array[202] = true; instance.array[204] = true; instance.array[206] = true; instance.array[208] = true; instance.array[210] = true; instance.array[212] = true; instance.array[214] = true; instance.array[217] = true; instance.array[219] = true; instance.array[221] = true; instance.array[223] = true; instance.array[225] = true; instance.array[227] = true; instance.array[229] = true; index = 231; while (index <= 232) : (index += 1) { instance.array[index] = true; } instance.array[234] = true; instance.array[236] = true; instance.array[238] = true; instance.array[240] = true; instance.array[242] = true; instance.array[244] = true; instance.array[246] = true; instance.array[248] = true; instance.array[250] = true; instance.array[252] = true; instance.array[254] = true; instance.array[256] = true; instance.array[258] = true; instance.array[260] = true; instance.array[262] = true; instance.array[264] = true; instance.array[266] = true; instance.array[268] = true; instance.array[270] = true; instance.array[272] = true; instance.array[274] = true; instance.array[276] = true; instance.array[278] = true; instance.array[281] = true; instance.array[283] = true; index = 285; while (index <= 287) : (index += 1) { instance.array[index] = true; } instance.array[290] = true; instance.array[292] = true; instance.array[295] = true; instance.array[299] = true; instance.array[305] = true; instance.array[308] = true; index = 312; while (index <= 313) : (index += 1) { instance.array[index] = true; } instance.array[317] = true; instance.array[320] = true; instance.array[322] = true; instance.array[324] = true; instance.array[327] = true; instance.array[332] = true; instance.array[335] = true; instance.array[339] = true; instance.array[341] = true; instance.array[344] = true; instance.array[348] = true; instance.array[350] = true; index = 356; while (index <= 357) : (index += 1) { instance.array[index] = true; } index = 359; while (index <= 360) : (index += 1) { instance.array[index] = true; } index = 362; while (index <= 363) : (index += 1) { instance.array[index] = true; } instance.array[365] = true; instance.array[367] = true; instance.array[369] = true; instance.array[371] = true; instance.array[373] = true; instance.array[375] = true; instance.array[377] = true; index = 379; while (index <= 380) : (index += 1) { instance.array[index] = true; } instance.array[382] = true; instance.array[384] = true; instance.array[386] = true; instance.array[388] = true; instance.array[390] = true; instance.array[392] = true; instance.array[394] = true; instance.array[396] = true; index = 398; while (index <= 399) : (index += 1) { instance.array[index] = true; } index = 401; while (index <= 402) : (index += 1) { instance.array[index] = true; } instance.array[404] = true; instance.array[408] = true; instance.array[410] = true; instance.array[412] = true; instance.array[414] = true; instance.array[416] = true; instance.array[418] = true; instance.array[420] = true; instance.array[422] = true; instance.array[424] = true; instance.array[426] = true; instance.array[428] = true; instance.array[430] = true; instance.array[432] = true; instance.array[434] = true; instance.array[436] = true; instance.array[438] = true; instance.array[440] = true; instance.array[442] = true; instance.array[444] = true; instance.array[446] = true; instance.array[450] = true; instance.array[452] = true; instance.array[454] = true; instance.array[456] = true; instance.array[458] = true; instance.array[460] = true; instance.array[462] = true; instance.array[464] = true; instance.array[466] = true; instance.array[475] = true; index = 478; while (index <= 479) : (index += 1) { instance.array[index] = true; } instance.array[481] = true; instance.array[486] = true; instance.array[488] = true; instance.array[490] = true; instance.array[492] = true; index = 494; while (index <= 499) : (index += 1) { instance.array[index] = true; } index = 501; while (index <= 502) : (index += 1) { instance.array[index] = true; } instance.array[504] = true; index = 506; while (index <= 507) : (index += 1) { instance.array[index] = true; } index = 511; while (index <= 512) : (index += 1) { instance.array[index] = true; } instance.array[514] = true; index = 516; while (index <= 517) : (index += 1) { instance.array[index] = true; } index = 519; while (index <= 523) : (index += 1) { instance.array[index] = true; } instance.array[526] = true; index = 528; while (index <= 529) : (index += 1) { instance.array[index] = true; } instance.array[532] = true; instance.array[540] = true; instance.array[543] = true; index = 545; while (index <= 546) : (index += 1) { instance.array[index] = true; } index = 550; while (index <= 555) : (index += 1) { instance.array[index] = true; } instance.array[561] = true; index = 572; while (index <= 573) : (index += 1) { instance.array[index] = true; } instance.array[740] = true; instance.array[784] = true; instance.array[786] = true; instance.array[790] = true; index = 794; while (index <= 796) : (index += 1) { instance.array[index] = true; } instance.array[815] = true; index = 843; while (index <= 877) : (index += 1) { instance.array[index] = true; } index = 879; while (index <= 880) : (index += 1) { instance.array[index] = true; } index = 884; while (index <= 886) : (index += 1) { instance.array[index] = true; } instance.array[888] = true; instance.array[890] = true; instance.array[892] = true; instance.array[894] = true; instance.array[896] = true; instance.array[898] = true; instance.array[900] = true; instance.array[902] = true; instance.array[904] = true; instance.array[906] = true; instance.array[908] = true; index = 910; while (index <= 914) : (index += 1) { instance.array[index] = true; } instance.array[916] = true; instance.array[919] = true; instance.array[922] = true; index = 975; while (index <= 1022) : (index += 1) { instance.array[index] = true; } instance.array[1024] = true; instance.array[1026] = true; instance.array[1028] = true; instance.array[1030] = true; instance.array[1032] = true; instance.array[1034] = true; instance.array[1036] = true; instance.array[1038] = true; instance.array[1040] = true; instance.array[1042] = true; instance.array[1044] = true; instance.array[1046] = true; instance.array[1048] = true; instance.array[1050] = true; instance.array[1052] = true; instance.array[1054] = true; instance.array[1056] = true; instance.array[1066] = true; instance.array[1068] = true; instance.array[1070] = true; instance.array[1072] = true; instance.array[1074] = true; instance.array[1076] = true; instance.array[1078] = true; instance.array[1080] = true; instance.array[1082] = true; instance.array[1084] = true; instance.array[1086] = true; instance.array[1088] = true; instance.array[1090] = true; instance.array[1092] = true; instance.array[1094] = true; instance.array[1096] = true; instance.array[1098] = true; instance.array[1100] = true; instance.array[1102] = true; instance.array[1104] = true; instance.array[1106] = true; instance.array[1108] = true; instance.array[1110] = true; instance.array[1112] = true; instance.array[1114] = true; instance.array[1116] = true; instance.array[1118] = true; instance.array[1121] = true; instance.array[1123] = true; instance.array[1125] = true; instance.array[1127] = true; instance.array[1129] = true; instance.array[1131] = true; index = 1133; while (index <= 1134) : (index += 1) { instance.array[index] = true; } instance.array[1136] = true; instance.array[1138] = true; instance.array[1140] = true; instance.array[1142] = true; instance.array[1144] = true; instance.array[1146] = true; instance.array[1148] = true; instance.array[1150] = true; instance.array[1152] = true; instance.array[1154] = true; instance.array[1156] = true; instance.array[1158] = true; instance.array[1160] = true; instance.array[1162] = true; instance.array[1164] = true; instance.array[1166] = true; instance.array[1168] = true; instance.array[1170] = true; instance.array[1172] = true; instance.array[1174] = true; instance.array[1176] = true; instance.array[1178] = true; instance.array[1180] = true; instance.array[1182] = true; instance.array[1184] = true; instance.array[1186] = true; instance.array[1188] = true; instance.array[1190] = true; instance.array[1192] = true; instance.array[1194] = true; instance.array[1196] = true; instance.array[1198] = true; instance.array[1200] = true; instance.array[1202] = true; instance.array[1204] = true; instance.array[1206] = true; instance.array[1208] = true; instance.array[1210] = true; instance.array[1212] = true; instance.array[1214] = true; instance.array[1216] = true; instance.array[1218] = true; instance.array[1220] = true; instance.array[1222] = true; instance.array[1224] = true; instance.array[1226] = true; instance.array[1228] = true; instance.array[1230] = true; index = 1280; while (index <= 1318) : (index += 1) { instance.array[index] = true; } index = 4207; while (index <= 4249) : (index += 1) { instance.array[index] = true; } index = 4252; while (index <= 4254) : (index += 1) { instance.array[index] = true; } index = 5015; while (index <= 5020) : (index += 1) { instance.array[index] = true; } index = 7199; while (index <= 7207) : (index += 1) { instance.array[index] = true; } instance.array[7448] = true; instance.array[7452] = true; instance.array[7469] = true; instance.array[7584] = true; instance.array[7586] = true; instance.array[7588] = true; instance.array[7590] = true; instance.array[7592] = true; instance.array[7594] = true; instance.array[7596] = true; instance.array[7598] = true; instance.array[7600] = true; instance.array[7602] = true; instance.array[7604] = true; instance.array[7606] = true; instance.array[7608] = true; instance.array[7610] = true; instance.array[7612] = true; instance.array[7614] = true; instance.array[7616] = true; instance.array[7618] = true; instance.array[7620] = true; instance.array[7622] = true; instance.array[7624] = true; instance.array[7626] = true; instance.array[7628] = true; instance.array[7630] = true; instance.array[7632] = true; instance.array[7634] = true; instance.array[7636] = true; instance.array[7638] = true; instance.array[7640] = true; instance.array[7642] = true; instance.array[7644] = true; instance.array[7646] = true; instance.array[7648] = true; instance.array[7650] = true; instance.array[7652] = true; instance.array[7654] = true; instance.array[7656] = true; instance.array[7658] = true; instance.array[7660] = true; instance.array[7662] = true; instance.array[7664] = true; instance.array[7666] = true; instance.array[7668] = true; instance.array[7670] = true; instance.array[7672] = true; instance.array[7674] = true; instance.array[7676] = true; instance.array[7678] = true; instance.array[7680] = true; instance.array[7682] = true; instance.array[7684] = true; instance.array[7686] = true; instance.array[7688] = true; instance.array[7690] = true; instance.array[7692] = true; instance.array[7694] = true; instance.array[7696] = true; instance.array[7698] = true; instance.array[7700] = true; instance.array[7702] = true; instance.array[7704] = true; instance.array[7706] = true; instance.array[7708] = true; instance.array[7710] = true; instance.array[7712] = true; instance.array[7714] = true; instance.array[7716] = true; instance.array[7718] = true; instance.array[7720] = true; instance.array[7722] = true; instance.array[7724] = true; instance.array[7726] = true; instance.array[7728] = true; instance.array[7730] = true; index = 7732; while (index <= 7738) : (index += 1) { instance.array[index] = true; } instance.array[7744] = true; instance.array[7746] = true; instance.array[7748] = true; instance.array[7750] = true; instance.array[7752] = true; instance.array[7754] = true; instance.array[7756] = true; instance.array[7758] = true; instance.array[7760] = true; instance.array[7762] = true; instance.array[7764] = true; instance.array[7766] = true; instance.array[7768] = true; instance.array[7770] = true; instance.array[7772] = true; instance.array[7774] = true; instance.array[7776] = true; instance.array[7778] = true; instance.array[7780] = true; instance.array[7782] = true; instance.array[7784] = true; instance.array[7786] = true; instance.array[7788] = true; instance.array[7790] = true; instance.array[7792] = true; instance.array[7794] = true; instance.array[7796] = true; instance.array[7798] = true; instance.array[7800] = true; instance.array[7802] = true; instance.array[7804] = true; instance.array[7806] = true; instance.array[7808] = true; instance.array[7810] = true; instance.array[7812] = true; instance.array[7814] = true; instance.array[7816] = true; instance.array[7818] = true; instance.array[7820] = true; instance.array[7822] = true; instance.array[7824] = true; instance.array[7826] = true; instance.array[7828] = true; instance.array[7830] = true; instance.array[7832] = true; instance.array[7834] = true; instance.array[7836] = true; index = 7838; while (index <= 7846) : (index += 1) { instance.array[index] = true; } index = 7855; while (index <= 7860) : (index += 1) { instance.array[index] = true; } index = 7871; while (index <= 7878) : (index += 1) { instance.array[index] = true; } index = 7887; while (index <= 7894) : (index += 1) { instance.array[index] = true; } index = 7903; while (index <= 7908) : (index += 1) { instance.array[index] = true; } index = 7919; while (index <= 7926) : (index += 1) { instance.array[index] = true; } index = 7935; while (index <= 7942) : (index += 1) { instance.array[index] = true; } index = 7951; while (index <= 7964) : (index += 1) { instance.array[index] = true; } index = 7967; while (index <= 8019) : (index += 1) { instance.array[index] = true; } index = 8021; while (index <= 8022) : (index += 1) { instance.array[index] = true; } instance.array[8027] = true; instance.array[8029] = true; index = 8033; while (index <= 8035) : (index += 1) { instance.array[index] = true; } index = 8037; while (index <= 8038) : (index += 1) { instance.array[index] = true; } instance.array[8043] = true; index = 8047; while (index <= 8050) : (index += 1) { instance.array[index] = true; } index = 8053; while (index <= 8054) : (index += 1) { instance.array[index] = true; } index = 8063; while (index <= 8070) : (index += 1) { instance.array[index] = true; } index = 8081; while (index <= 8083) : (index += 1) { instance.array[index] = true; } index = 8085; while (index <= 8086) : (index += 1) { instance.array[index] = true; } instance.array[8091] = true; instance.array[8429] = true; index = 8463; while (index <= 8478) : (index += 1) { instance.array[index] = true; } instance.array[8483] = true; index = 9327; while (index <= 9352) : (index += 1) { instance.array[index] = true; } index = 11215; while (index <= 11261) : (index += 1) { instance.array[index] = true; } instance.array[11264] = true; index = 11268; while (index <= 11269) : (index += 1) { instance.array[index] = true; } instance.array[11271] = true; instance.array[11273] = true; instance.array[11275] = true; instance.array[11282] = true; instance.array[11285] = true; instance.array[11296] = true; instance.array[11298] = true; instance.array[11300] = true; instance.array[11302] = true; instance.array[11304] = true; instance.array[11306] = true; instance.array[11308] = true; instance.array[11310] = true; instance.array[11312] = true; instance.array[11314] = true; instance.array[11316] = true; instance.array[11318] = true; instance.array[11320] = true; instance.array[11322] = true; instance.array[11324] = true; instance.array[11326] = true; instance.array[11328] = true; instance.array[11330] = true; instance.array[11332] = true; instance.array[11334] = true; instance.array[11336] = true; instance.array[11338] = true; instance.array[11340] = true; instance.array[11342] = true; instance.array[11344] = true; instance.array[11346] = true; instance.array[11348] = true; instance.array[11350] = true; instance.array[11352] = true; instance.array[11354] = true; instance.array[11356] = true; instance.array[11358] = true; instance.array[11360] = true; instance.array[11362] = true; instance.array[11364] = true; instance.array[11366] = true; instance.array[11368] = true; instance.array[11370] = true; instance.array[11372] = true; instance.array[11374] = true; instance.array[11376] = true; instance.array[11378] = true; instance.array[11380] = true; instance.array[11382] = true; instance.array[11384] = true; instance.array[11386] = true; instance.array[11388] = true; instance.array[11390] = true; instance.array[11392] = true; instance.array[11394] = true; instance.array[11403] = true; instance.array[11405] = true; instance.array[11410] = true; index = 11423; while (index <= 11460) : (index += 1) { instance.array[index] = true; } instance.array[11462] = true; instance.array[11468] = true; instance.array[42464] = true; instance.array[42466] = true; instance.array[42468] = true; instance.array[42470] = true; instance.array[42472] = true; instance.array[42474] = true; instance.array[42476] = true; instance.array[42478] = true; instance.array[42480] = true; instance.array[42482] = true; instance.array[42484] = true; instance.array[42486] = true; instance.array[42488] = true; instance.array[42490] = true; instance.array[42492] = true; instance.array[42494] = true; instance.array[42496] = true; instance.array[42498] = true; instance.array[42500] = true; instance.array[42502] = true; instance.array[42504] = true; instance.array[42506] = true; instance.array[42508] = true; instance.array[42528] = true; instance.array[42530] = true; instance.array[42532] = true; instance.array[42534] = true; instance.array[42536] = true; instance.array[42538] = true; instance.array[42540] = true; instance.array[42542] = true; instance.array[42544] = true; instance.array[42546] = true; instance.array[42548] = true; instance.array[42550] = true; instance.array[42552] = true; instance.array[42554] = true; instance.array[42690] = true; instance.array[42692] = true; instance.array[42694] = true; instance.array[42696] = true; instance.array[42698] = true; instance.array[42700] = true; instance.array[42702] = true; instance.array[42706] = true; instance.array[42708] = true; instance.array[42710] = true; instance.array[42712] = true; instance.array[42714] = true; instance.array[42716] = true; instance.array[42718] = true; instance.array[42720] = true; instance.array[42722] = true; instance.array[42724] = true; instance.array[42726] = true; instance.array[42728] = true; instance.array[42730] = true; instance.array[42732] = true; instance.array[42734] = true; instance.array[42736] = true; instance.array[42738] = true; instance.array[42740] = true; instance.array[42742] = true; instance.array[42744] = true; instance.array[42746] = true; instance.array[42748] = true; instance.array[42750] = true; instance.array[42752] = true; instance.array[42754] = true; instance.array[42756] = true; instance.array[42758] = true; instance.array[42760] = true; instance.array[42762] = true; instance.array[42764] = true; instance.array[42766] = true; instance.array[42777] = true; instance.array[42779] = true; instance.array[42782] = true; instance.array[42784] = true; instance.array[42786] = true; instance.array[42788] = true; instance.array[42790] = true; instance.array[42795] = true; instance.array[42800] = true; index = 42802; while (index <= 42803) : (index += 1) { instance.array[index] = true; } instance.array[42806] = true; instance.array[42808] = true; instance.array[42810] = true; instance.array[42812] = true; instance.array[42814] = true; instance.array[42816] = true; instance.array[42818] = true; instance.array[42820] = true; instance.array[42822] = true; instance.array[42824] = true; instance.array[42836] = true; instance.array[42838] = true; instance.array[42840] = true; instance.array[42842] = true; instance.array[42844] = true; instance.array[42846] = true; instance.array[42850] = true; instance.array[42855] = true; instance.array[42857] = true; instance.array[42901] = true; instance.array[43762] = true; index = 43791; while (index <= 43870) : (index += 1) { instance.array[index] = true; } index = 64159; while (index <= 64165) : (index += 1) { instance.array[index] = true; } index = 64178; while (index <= 64182) : (index += 1) { instance.array[index] = true; } index = 65248; while (index <= 65273) : (index += 1) { instance.array[index] = true; } index = 66503; while (index <= 66542) : (index += 1) { instance.array[index] = true; } index = 66679; while (index <= 66714) : (index += 1) { instance.array[index] = true; } index = 68703; while (index <= 68753) : (index += 1) { instance.array[index] = true; } index = 71775; while (index <= 71806) : (index += 1) { instance.array[index] = true; } index = 93695; while (index <= 93726) : (index += 1) { instance.array[index] = true; } index = 125121; while (index <= 125154) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *ChangesWhenUppercased) void { self.allocator.free(self.array); } // isChangesWhenUppercased checks if cp is of the kind Changes_When_Uppercased. pub fn isChangesWhenUppercased(self: ChangesWhenUppercased, 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/DerivedCoreProperties/ChangesWhenUppercased.zig
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 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 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); //-------------------------------------------------------------------------------- // Section: Types (101) //-------------------------------------------------------------------------------- pub const CFM_MASK = enum(u32) { SUBSCRIPT = 196608, // SUPERSCRIPT = 196608, this enum value conflicts with SUBSCRIPT 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, 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_SUPERSCRIPT = 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_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 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 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 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 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 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 ENDCOMPOSITIONNOTIFY_CODE = enum(u32) { ENDCOMPOSITION = 1, NEWTEXT = 2, }; pub const ECN_ENDCOMPOSITION = ENDCOMPOSITIONNOTIFY_CODE.ENDCOMPOSITION; pub const ECN_NEWTEXT = ENDCOMPOSITIONNOTIFY_CODE.NEWTEXT; pub const IMECOMPTEXT_FLAGS = enum(u32) { R = 1, }; pub const ICT_RESULTREADSTR = IMECOMPTEXT_FLAGS.R; 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 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 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 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 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 RICHEDIT_IMAGE_PARAMETERS = 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, }; pub const ENDCOMPOSITIONNOTIFY = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, dwCode: ENDCOMPOSITIONNOTIFY_CODE, }; 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 TEXTRANGEA = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug chrg: CHARRANGE, lpstrText: ?PSTR, }; pub const TEXTRANGEW = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug chrg: CHARRANGE, lpstrText: ?PWSTR, }; pub const EDITSTREAMCALLBACK = fn( dwCookie: usize, pbBuff: ?*u8, cb: i32, pcb: ?*i32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const EDITSTREAM = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug dwCookie: usize, dwError: u32, pfnCallback: ?EDITSTREAMCALLBACK, }; pub const FINDTEXTA = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug chrg: CHARRANGE, lpstrText: ?[*:0]const u8, }; pub const FINDTEXTW = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug chrg: CHARRANGE, lpstrText: ?[*:0]const u16, }; pub const FINDTEXTEXA = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug chrg: CHARRANGE, lpstrText: ?[*:0]const u8, chrgText: CHARRANGE, }; pub const FINDTEXTEXW = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug chrg: CHARRANGE, lpstrText: ?[*:0]const u16, chrgText: CHARRANGE, }; pub const FORMATRANGE = 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, }; 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 MSGFILTER = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, msg: u32, wParam: WPARAM, lParam: LPARAM, }; pub const REQRESIZE = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, rc: RECT, }; pub const SELCHANGE = 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, }; pub const _grouptypingchange = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, fGroupTyping: BOOL, }; pub const CLIPBOARDFORMAT = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, cf: u16, }; pub const GETCONTEXTMENUEX = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug chrg: CHARRANGE, dwFlags: u32, pt: POINT, pvReserved: ?*anyopaque, }; pub const ENDROPFILES = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, hDrop: ?HANDLE, cp: i32, fProtected: BOOL, }; pub const ENPROTECTED = 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, }; pub const ENSAVECLIPBOARD = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, cObjectCount: i32, cch: i32, }; pub const ENOLEOPFAILED = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, iob: i32, lOper: i32, hr: HRESULT, }; pub const OBJECTPOSITIONS = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, cObjectCount: i32, pcpPositions: ?*i32, }; pub const ENLINK = 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, }; pub const ENLOWFIRTF = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug nmhdr: NMHDR, szControl: ?PSTR, }; pub const ENCORRECTTEXT = 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, }; pub const PUNCTUATION = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug iSize: u32, szPunctuation: ?PSTR, }; pub const COMPCOLOR = extern struct { crText: u32, crBackground: u32, dwEffects: u32, }; pub const REPASTESPECIAL = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug dwAspect: DVASPECT, dwParam: usize, }; 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 GETTEXTEX = 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, }; 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 HYPHENATEINFO = extern struct { // WARNING: unable to add field alignment because it's causing a compiler bug cbSize: i16, dxHyphenateZone: i16, pfnHyphenate: isize, }; 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: ?*anyopaque, }; 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: ?*anyopaque, 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: ?*anyopaque, 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: ?*anyopaque, 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: ?*anyopaque, 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: ?*anyopaque, 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: ?*anyopaque, 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: ?*anyopaque, ) 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: ?*anyopaque) 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 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 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 = 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 = 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 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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()); }; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (5) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { pub const CHARFORMAT = thismodule.CHARFORMATA; pub const CHARFORMAT2 = thismodule.CHARFORMAT2A; pub const TEXTRANGE = thismodule.TEXTRANGEA; pub const FINDTEXT = thismodule.FINDTEXTA; pub const FINDTEXTEX = thismodule.FINDTEXTEXA; }, .wide => struct { pub const CHARFORMAT = thismodule.CHARFORMATW; pub const CHARFORMAT2 = thismodule.CHARFORMAT2W; pub const TEXTRANGE = thismodule.TEXTRANGEW; pub const FINDTEXT = thismodule.FINDTEXTW; pub const FINDTEXTEX = thismodule.FINDTEXTEXW; }, .unspecified => if (@import("builtin").is_test) struct { pub const CHARFORMAT = *opaque{}; pub const CHARFORMAT2 = *opaque{}; pub const TEXTRANGE = *opaque{}; pub const FINDTEXT = *opaque{}; pub const FINDTEXTEX = *opaque{}; } else struct { 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 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"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (43) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOL = @import("../../foundation.zig").BOOL; const BSTR = @import("../../foundation.zig").BSTR; const CHAR = @import("../../foundation.zig").CHAR; const DVASPECT = @import("../../system/com.zig").DVASPECT; const DVTARGETDEVICE = @import("../../system/com.zig").DVTARGETDEVICE; const ENABLE_SCROLL_BAR_ARROWS = @import("../../ui/controls.zig").ENABLE_SCROLL_BAR_ARROWS; const HANDLE = @import("../../foundation.zig").HANDLE; const HBITMAP = @import("../../graphics/gdi.zig").HBITMAP; const HCURSOR = @import("../../ui/windows_and_messaging.zig").HCURSOR; const HDC = @import("../../graphics/gdi.zig").HDC; const HIMC = @import("../../globalization.zig").HIMC; const HMENU = @import("../../ui/windows_and_messaging.zig").HMENU; const HPALETTE = @import("../../graphics/gdi.zig").HPALETTE; 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/com.zig").IDispatch; const IDropTarget = @import("../../system/ole.zig").IDropTarget; const IOleClientSite = @import("../../system/ole.zig").IOleClientSite; const IOleInPlaceFrame = @import("../../system/ole.zig").IOleInPlaceFrame; const IOleInPlaceUIWindow = @import("../../system/ole.zig").IOleInPlaceUIWindow; const IOleObject = @import("../../system/ole.zig").IOleObject; const IStorage = @import("../../system/com/structured_storage.zig").IStorage; const IStream = @import("../../system/com.zig").IStream; const IUnknown = @import("../../system/com.zig").IUnknown; const LPARAM = @import("../../foundation.zig").LPARAM; const LRESULT = @import("../../foundation.zig").LRESULT; const NMHDR = @import("../../ui/controls.zig").NMHDR; const OIFI = @import("../../system/ole.zig").OIFI; const POINT = @import("../../foundation.zig").POINT; 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 SCROLLBAR_CONSTANTS = @import("../../ui/windows_and_messaging.zig").SCROLLBAR_CONSTANTS; const SHOW_WINDOW_CMD = @import("../../ui/windows_and_messaging.zig").SHOW_WINDOW_CMD; const SIZE = @import("../../foundation.zig").SIZE; const TEXT_ALIGN_OPTIONS = @import("../../graphics/gdi.zig").TEXT_ALIGN_OPTIONS; const VARIANT = @import("../../system/com.zig").VARIANT; 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(), "AutoCorrectProc")) { _ = AutoCorrectProc; } if (@hasDecl(@This(), "EDITWORDBREAKPROCEX")) { _ = EDITWORDBREAKPROCEX; } if (@hasDecl(@This(), "EDITSTREAMCALLBACK")) { _ = EDITSTREAMCALLBACK; } if (@hasDecl(@This(), "PCreateTextServices")) { _ = PCreateTextServices; } if (@hasDecl(@This(), "PShutdownTextServices")) { _ = PShutdownTextServices; } @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/ui/controls/rich_edit.zig
pub const WTS_DOMAIN_LENGTH = @as(u32, 255); pub const WTS_USERNAME_LENGTH = @as(u32, 255); pub const WTS_PASSWORD_LENGTH = @as(u32, 255); pub const WTS_DIRECTORY_LENGTH = @as(u32, 256); pub const WTS_INITIALPROGRAM_LENGTH = @as(u32, 256); pub const WTS_PROTOCOL_NAME_LENGTH = @as(u32, 8); pub const WTS_DRIVER_NAME_LENGTH = @as(u32, 8); pub const WTS_DEVICE_NAME_LENGTH = @as(u32, 19); pub const WTS_IMEFILENAME_LENGTH = @as(u32, 32); pub const WTS_CLIENTNAME_LENGTH = @as(u32, 20); pub const WTS_CLIENTADDRESS_LENGTH = @as(u32, 30); pub const WTS_CLIENT_PRODUCT_ID_LENGTH = @as(u32, 32); pub const WTS_MAX_PROTOCOL_CACHE = @as(u32, 4); pub const WTS_MAX_CACHE_RESERVED = @as(u32, 20); pub const WTS_MAX_RESERVED = @as(u32, 100); pub const WTS_MAX_COUNTERS = @as(u32, 100); pub const WTS_MAX_DISPLAY_IOCTL_DATA = @as(u32, 256); pub const WTS_PERF_DISABLE_NOTHING = @as(u32, 0); pub const WTS_PERF_DISABLE_WALLPAPER = @as(u32, 1); pub const WTS_PERF_DISABLE_FULLWINDOWDRAG = @as(u32, 2); pub const WTS_PERF_DISABLE_MENUANIMATIONS = @as(u32, 4); pub const WTS_PERF_DISABLE_THEMING = @as(u32, 8); pub const WTS_PERF_ENABLE_ENHANCED_GRAPHICS = @as(u32, 16); pub const WTS_PERF_DISABLE_CURSOR_SHADOW = @as(u32, 32); pub const WTS_PERF_DISABLE_CURSORSETTINGS = @as(u32, 64); pub const WTS_PERF_ENABLE_FONT_SMOOTHING = @as(u32, 128); pub const WTS_PERF_ENABLE_DESKTOP_COMPOSITION = @as(u32, 256); pub const WTS_VALUE_TYPE_ULONG = @as(u32, 1); pub const WTS_VALUE_TYPE_STRING = @as(u32, 2); pub const WTS_VALUE_TYPE_BINARY = @as(u32, 3); pub const WTS_VALUE_TYPE_GUID = @as(u32, 4); pub const WTS_KEY_EXCHANGE_ALG_RSA = @as(u32, 1); pub const WTS_KEY_EXCHANGE_ALG_DH = @as(u32, 2); pub const WTS_LICENSE_PROTOCOL_VERSION = @as(u32, 65536); pub const WTS_LICENSE_PREAMBLE_VERSION = @as(u32, 3); pub const WRDS_DOMAIN_LENGTH = @as(u32, 255); pub const WRDS_USERNAME_LENGTH = @as(u32, 255); pub const WRDS_PASSWORD_LENGTH = @as(u32, 255); pub const WRDS_DIRECTORY_LENGTH = @as(u32, 256); pub const WRDS_INITIALPROGRAM_LENGTH = @as(u32, 256); pub const WRDS_PROTOCOL_NAME_LENGTH = @as(u32, 8); pub const WRDS_DRIVER_NAME_LENGTH = @as(u32, 8); pub const WRDS_DEVICE_NAME_LENGTH = @as(u32, 19); pub const WRDS_IMEFILENAME_LENGTH = @as(u32, 32); pub const WRDS_CLIENTNAME_LENGTH = @as(u32, 20); pub const WRDS_CLIENTADDRESS_LENGTH = @as(u32, 30); pub const WRDS_CLIENT_PRODUCT_ID_LENGTH = @as(u32, 32); pub const WRDS_MAX_PROTOCOL_CACHE = @as(u32, 4); pub const WRDS_MAX_CACHE_RESERVED = @as(u32, 20); pub const WRDS_MAX_RESERVED = @as(u32, 100); pub const WRDS_MAX_COUNTERS = @as(u32, 100); pub const WRDS_MAX_DISPLAY_IOCTL_DATA = @as(u32, 256); pub const WRDS_PERF_DISABLE_NOTHING = @as(u32, 0); pub const WRDS_PERF_DISABLE_WALLPAPER = @as(u32, 1); pub const WRDS_PERF_DISABLE_FULLWINDOWDRAG = @as(u32, 2); pub const WRDS_PERF_DISABLE_MENUANIMATIONS = @as(u32, 4); pub const WRDS_PERF_DISABLE_THEMING = @as(u32, 8); pub const WRDS_PERF_ENABLE_ENHANCED_GRAPHICS = @as(u32, 16); pub const WRDS_PERF_DISABLE_CURSOR_SHADOW = @as(u32, 32); pub const WRDS_PERF_DISABLE_CURSORSETTINGS = @as(u32, 64); pub const WRDS_PERF_ENABLE_FONT_SMOOTHING = @as(u32, 128); pub const WRDS_PERF_ENABLE_DESKTOP_COMPOSITION = @as(u32, 256); pub const WRDS_VALUE_TYPE_ULONG = @as(u32, 1); pub const WRDS_VALUE_TYPE_STRING = @as(u32, 2); pub const WRDS_VALUE_TYPE_BINARY = @as(u32, 3); pub const WRDS_VALUE_TYPE_GUID = @as(u32, 4); pub const WRDS_KEY_EXCHANGE_ALG_RSA = @as(u32, 1); pub const WRDS_KEY_EXCHANGE_ALG_DH = @as(u32, 2); pub const WRDS_LICENSE_PROTOCOL_VERSION = @as(u32, 65536); pub const WRDS_LICENSE_PREAMBLE_VERSION = @as(u32, 3); pub const SINGLE_SESSION = @as(u32, 1); pub const FORCE_REJOIN = @as(u32, 2); pub const FORCE_REJOIN_IN_CLUSTERMODE = @as(u32, 3); pub const RESERVED_FOR_LEGACY = @as(u32, 4); pub const KEEP_EXISTING_SESSIONS = @as(u32, 8); pub const CHANNEL_EVENT_INITIALIZED = @as(u32, 0); pub const CHANNEL_EVENT_CONNECTED = @as(u32, 1); pub const CHANNEL_EVENT_V1_CONNECTED = @as(u32, 2); pub const CHANNEL_EVENT_DISCONNECTED = @as(u32, 3); pub const CHANNEL_EVENT_TERMINATED = @as(u32, 4); pub const CHANNEL_EVENT_DATA_RECEIVED = @as(u32, 10); pub const CHANNEL_EVENT_WRITE_COMPLETE = @as(u32, 11); pub const CHANNEL_EVENT_WRITE_CANCELLED = @as(u32, 12); pub const CHANNEL_RC_OK = @as(u32, 0); pub const CHANNEL_RC_ALREADY_INITIALIZED = @as(u32, 1); pub const CHANNEL_RC_NOT_INITIALIZED = @as(u32, 2); pub const CHANNEL_RC_ALREADY_CONNECTED = @as(u32, 3); pub const CHANNEL_RC_NOT_CONNECTED = @as(u32, 4); pub const CHANNEL_RC_TOO_MANY_CHANNELS = @as(u32, 5); pub const CHANNEL_RC_BAD_CHANNEL = @as(u32, 6); pub const CHANNEL_RC_BAD_CHANNEL_HANDLE = @as(u32, 7); pub const CHANNEL_RC_NO_BUFFER = @as(u32, 8); pub const CHANNEL_RC_BAD_INIT_HANDLE = @as(u32, 9); pub const CHANNEL_RC_NOT_OPEN = @as(u32, 10); pub const CHANNEL_RC_BAD_PROC = @as(u32, 11); pub const CHANNEL_RC_NO_MEMORY = @as(u32, 12); pub const CHANNEL_RC_UNKNOWN_CHANNEL_NAME = @as(u32, 13); pub const CHANNEL_RC_ALREADY_OPEN = @as(u32, 14); pub const CHANNEL_RC_NOT_IN_VIRTUALCHANNELENTRY = @as(u32, 15); pub const CHANNEL_RC_NULL_DATA = @as(u32, 16); pub const CHANNEL_RC_ZERO_LENGTH = @as(u32, 17); pub const CHANNEL_RC_INVALID_INSTANCE = @as(u32, 18); pub const CHANNEL_RC_UNSUPPORTED_VERSION = @as(u32, 19); pub const CHANNEL_RC_INITIALIZATION_ERROR = @as(u32, 20); pub const VIRTUAL_CHANNEL_VERSION_WIN2000 = @as(u32, 1); pub const CHANNEL_CHUNK_LENGTH = @as(u32, 1600); pub const CHANNEL_BUFFER_SIZE = @as(u32, 65535); pub const CHANNEL_FLAG_FIRST = @as(u32, 1); pub const CHANNEL_FLAG_LAST = @as(u32, 2); pub const CHANNEL_FLAG_MIDDLE = @as(u32, 0); pub const CHANNEL_FLAG_FAIL = @as(u32, 256); pub const CHANNEL_OPTION_INITIALIZED = @as(u32, 2147483648); pub const CHANNEL_OPTION_ENCRYPT_RDP = @as(u32, 1073741824); pub const CHANNEL_OPTION_ENCRYPT_SC = @as(u32, 536870912); pub const CHANNEL_OPTION_ENCRYPT_CS = @as(u32, 268435456); pub const CHANNEL_OPTION_PRI_HIGH = @as(u32, 134217728); pub const CHANNEL_OPTION_PRI_MED = @as(u32, 67108864); pub const CHANNEL_OPTION_PRI_LOW = @as(u32, 33554432); pub const CHANNEL_OPTION_COMPRESS_RDP = @as(u32, 8388608); pub const CHANNEL_OPTION_COMPRESS = @as(u32, 4194304); pub const CHANNEL_OPTION_SHOW_PROTOCOL = @as(u32, 2097152); pub const CHANNEL_OPTION_REMOTE_CONTROL_PERSISTENT = @as(u32, 1048576); pub const CHANNEL_MAX_COUNT = @as(u32, 30); pub const CHANNEL_NAME_LEN = @as(u32, 7); pub const MAX_POLICY_ATTRIBUTES = @as(u32, 20); pub const WTS_CURRENT_SESSION = @as(u32, 4294967295); pub const USERNAME_LENGTH = @as(u32, 20); pub const CLIENTNAME_LENGTH = @as(u32, 20); pub const CLIENTADDRESS_LENGTH = @as(u32, 30); pub const WTS_WSD_LOGOFF = @as(u32, 1); pub const WTS_WSD_SHUTDOWN = @as(u32, 2); pub const WTS_WSD_REBOOT = @as(u32, 4); pub const WTS_WSD_POWEROFF = @as(u32, 8); pub const WTS_WSD_FASTREBOOT = @as(u32, 16); pub const MAX_ELAPSED_TIME_LENGTH = @as(u32, 15); pub const MAX_DATE_TIME_LENGTH = @as(u32, 56); pub const WINSTATIONNAME_LENGTH = @as(u32, 32); pub const DOMAIN_LENGTH = @as(u32, 17); pub const WTS_DRIVE_LENGTH = @as(u32, 3); pub const WTS_LISTENER_NAME_LENGTH = @as(u32, 32); pub const WTS_COMMENT_LENGTH = @as(u32, 60); pub const WTS_LISTENER_CREATE = @as(u32, 1); pub const WTS_LISTENER_UPDATE = @as(u32, 16); pub const WTS_SECURITY_QUERY_INFORMATION = @as(u32, 1); pub const WTS_SECURITY_SET_INFORMATION = @as(u32, 2); pub const WTS_SECURITY_RESET = @as(u32, 4); pub const WTS_SECURITY_VIRTUAL_CHANNELS = @as(u32, 8); pub const WTS_SECURITY_REMOTE_CONTROL = @as(u32, 16); pub const WTS_SECURITY_LOGON = @as(u32, 32); pub const WTS_SECURITY_LOGOFF = @as(u32, 64); pub const WTS_SECURITY_MESSAGE = @as(u32, 128); pub const WTS_SECURITY_CONNECT = @as(u32, 256); pub const WTS_SECURITY_DISCONNECT = @as(u32, 512); pub const WTS_SECURITY_GUEST_ACCESS = @as(u32, 32); pub const WTS_PROTOCOL_TYPE_CONSOLE = @as(u32, 0); pub const WTS_PROTOCOL_TYPE_ICA = @as(u32, 1); pub const WTS_PROTOCOL_TYPE_RDP = @as(u32, 2); pub const WTS_SESSIONSTATE_UNKNOWN = @as(u32, 4294967295); pub const WTS_SESSIONSTATE_LOCK = @as(u32, 0); pub const WTS_SESSIONSTATE_UNLOCK = @as(u32, 1); pub const PRODUCTINFO_COMPANYNAME_LENGTH = @as(u32, 256); pub const PRODUCTINFO_PRODUCTID_LENGTH = @as(u32, 4); pub const VALIDATIONINFORMATION_LICENSE_LENGTH = @as(u32, 16384); pub const VALIDATIONINFORMATION_HARDWAREID_LENGTH = @as(u32, 20); pub const WTS_EVENT_NONE = @as(u32, 0); pub const WTS_EVENT_CREATE = @as(u32, 1); pub const WTS_EVENT_DELETE = @as(u32, 2); pub const WTS_EVENT_RENAME = @as(u32, 4); pub const WTS_EVENT_CONNECT = @as(u32, 8); pub const WTS_EVENT_DISCONNECT = @as(u32, 16); pub const WTS_EVENT_LOGON = @as(u32, 32); pub const WTS_EVENT_LOGOFF = @as(u32, 64); pub const WTS_EVENT_STATECHANGE = @as(u32, 128); pub const WTS_EVENT_LICENSE = @as(u32, 256); pub const WTS_EVENT_ALL = @as(u32, 2147483647); pub const WTS_EVENT_FLUSH = @as(u32, 2147483648); pub const REMOTECONTROL_KBDSHIFT_HOTKEY = @as(u32, 1); pub const REMOTECONTROL_KBDCTRL_HOTKEY = @as(u32, 2); pub const REMOTECONTROL_KBDALT_HOTKEY = @as(u32, 4); pub const WTS_CHANNEL_OPTION_DYNAMIC = @as(u32, 1); pub const WTS_CHANNEL_OPTION_DYNAMIC_PRI_LOW = @as(u32, 0); pub const WTS_CHANNEL_OPTION_DYNAMIC_PRI_MED = @as(u32, 2); pub const WTS_CHANNEL_OPTION_DYNAMIC_PRI_HIGH = @as(u32, 4); pub const WTS_CHANNEL_OPTION_DYNAMIC_PRI_REAL = @as(u32, 6); pub const WTS_CHANNEL_OPTION_DYNAMIC_NO_COMPRESS = @as(u32, 8); pub const NOTIFY_FOR_ALL_SESSIONS = @as(u32, 1); pub const NOTIFY_FOR_THIS_SESSION = @as(u32, 0); pub const WTS_PROCESS_INFO_LEVEL_0 = @as(u32, 0); pub const WTS_PROCESS_INFO_LEVEL_1 = @as(u32, 1); pub const PLUGIN_CAPABILITY_EXTERNAL_REDIRECTION = @as(u32, 1); pub const MaxFQDN_Len = @as(u32, 256); pub const MaxNetBiosName_Len = @as(u32, 16); pub const MaxNumOfExposed_IPs = @as(u32, 12); pub const MaxUserName_Len = @as(u32, 104); pub const MaxDomainName_Len = @as(u32, 256); pub const MaxFarm_Len = @as(u32, 256); pub const MaxAppName_Len = @as(u32, 256); pub const WKS_FLAG_CLEAR_CREDS_ON_LAST_RESOURCE = @as(u32, 1); pub const WKS_FLAG_PASSWORD_ENCRYPTED = @as(u32, 2); pub const WKS_FLAG_CREDS_AUTHENTICATED = @as(u32, 4); pub const SB_SYNCH_CONFLICT_MAX_WRITE_ATTEMPTS = @as(u32, 100); pub const ACQUIRE_TARGET_LOCK_TIMEOUT = @as(u32, 300000); pub const RENDER_HINT_CLEAR = @as(u32, 0); pub const RENDER_HINT_VIDEO = @as(u32, 1); pub const RENDER_HINT_MAPPEDWINDOW = @as(u32, 2); pub const TS_VC_LISTENER_STATIC_CHANNEL = @as(u32, 1); pub const WRdsGraphicsChannels_LossyChannelMaxMessageSize = @as(u32, 988); pub const RFX_RDP_MSG_PREFIX = @as(u32, 0); pub const RFX_GFX_MSG_PREFIX = @as(u32, 48); pub const RFX_GFX_MSG_PREFIX_MASK = @as(u32, 48); pub const RFX_GFX_MAX_SUPPORTED_MONITORS = @as(u32, 16); pub const RFX_CLIENT_ID_LENGTH = @as(u32, 32); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_CONNECT = @as(u32, 701); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_DISCONNECT = @as(u32, 702); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_RECONNECT = @as(u32, 703); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_DELETE_SAVED_CREDENTIALS = @as(u32, 704); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_UPDATE_SESSION_DISPLAYSETTINGS = @as(u32, 705); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_ATTACH_EVENT = @as(u32, 706); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_DETACH_EVENT = @as(u32, 707); pub const DISPID_PROP_REMOTEDESKTOPCLIENT_SETTINGS = @as(u32, 710); pub const DISPID_PROP_REMOTEDESKTOPCLIENT_ACTIONS = @as(u32, 711); pub const DISPID_PROP_REMOTEDESKTOPCLIENT_TOUCH_POINTER = @as(u32, 712); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_SET_RDPPROPERTY = @as(u32, 720); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_GET_RDPPROPERTY = @as(u32, 721); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_APPLY_SETTINGS = @as(u32, 722); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_RETRIEVE_SETTINGS = @as(u32, 723); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_SUSPEND_SCREEN_UPDATES = @as(u32, 730); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_RESUME_SCREEN_UPDATES = @as(u32, 731); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_EXECUTE_REMOTE_ACTION = @as(u32, 732); pub const DISPID_METHOD_REMOTEDESKTOPCLIENT_GET_SNAPSHOT = @as(u32, 733); pub const DISPID_PROP_REMOTEDESKTOPCLIENT_TOUCHPOINTER_ENABLED = @as(u32, 740); pub const DISPID_PROP_REMOTEDESKTOPCLIENT_TOUCHPOINTER_EVENTSENABLED = @as(u32, 741); pub const DISPID_PROP_REMOTEDESKTOPCLIENT_TOUCHPOINTER_POINTERSPEED = @as(u32, 742); pub const DISPID_AX_CONNECTING = @as(u32, 750); pub const DISPID_AX_CONNECTED = @as(u32, 751); pub const DISPID_AX_LOGINCOMPLETED = @as(u32, 752); pub const DISPID_AX_DISCONNECTED = @as(u32, 753); pub const DISPID_AX_STATUSCHANGED = @as(u32, 754); pub const DISPID_AX_AUTORECONNECTING = @as(u32, 755); pub const DISPID_AX_AUTORECONNECTED = @as(u32, 756); pub const DISPID_AX_DIALOGDISPLAYING = @as(u32, 757); pub const DISPID_AX_DIALOGDISMISSED = @as(u32, 758); pub const DISPID_AX_NETWORKSTATUSCHANGED = @as(u32, 759); pub const DISPID_AX_ADMINMESSAGERECEIVED = @as(u32, 760); pub const DISPID_AX_KEYCOMBINATIONPRESSED = @as(u32, 761); pub const DISPID_AX_REMOTEDESKTOPSIZECHANGED = @as(u32, 762); pub const DISPID_AX_TOUCHPOINTERCURSORMOVED = @as(u32, 800); pub const RDCLIENT_BITMAP_RENDER_SERVICE = Guid.initString("e4cc08cb-942e-4b19-8504-bd5a89a747f5"); pub const WTS_QUERY_ALLOWED_INITIAL_APP = Guid.initString("c77d1b30-5be1-4c6b-a0e1-bd6d2e5c9fcc"); pub const WTS_QUERY_LOGON_SCREEN_SIZE = Guid.initString("8b8e0fe7-0804-4a0e-b279-8660b1df0049"); pub const WTS_QUERY_AUDIOENUM_DLL = Guid.initString("9bf4fa97-c883-4c2a-80ab-5a39c9af00db"); pub const WTS_QUERY_MF_FORMAT_SUPPORT = Guid.initString("41869ad0-6332-4dc8-95d5-db749e2f1d94"); pub const WRDS_SERVICE_ID_GRAPHICS_GUID = Guid.initString("d2993f4d-02cf-4280-8c48-1624b44f8706"); pub const PROPERTY_DYNAMIC_TIME_ZONE_INFORMATION = Guid.initString("0cdfd28e-d0b9-4c1f-a5eb-6d1f6c6535b9"); pub const PROPERTY_TYPE_GET_FAST_RECONNECT = Guid.initString("6212d757-0043-4862-99c3-9f3059ac2a3b"); pub const PROPERTY_TYPE_GET_FAST_RECONNECT_USER_SID = Guid.initString("197c427a-0135-4b6d-9c5e-e6579a0ab625"); pub const PROPERTY_TYPE_ENABLE_UNIVERSAL_APPS_FOR_CUSTOM_SHELL = Guid.initString("ed2c3fda-338d-4d3f-81a3-e767310d908e"); pub const CONNECTION_PROPERTY_IDLE_TIME_WARNING = Guid.initString("693f7ff5-0c4e-4d17-b8e0-1f70325e5d58"); pub const CONNECTION_PROPERTY_CURSOR_BLINK_DISABLED = Guid.initString("4b150580-fea4-4d3c-9de4-7433a66618f7"); //-------------------------------------------------------------------------------- // Section: Types (254) //-------------------------------------------------------------------------------- pub const AE_POSITION_FLAGS = enum(i32) { INVALID = 0, DISCONTINUOUS = 1, CONTINUOUS = 2, QPC_ERROR = 4, }; pub const POSITION_INVALID = AE_POSITION_FLAGS.INVALID; pub const POSITION_DISCONTINUOUS = AE_POSITION_FLAGS.DISCONTINUOUS; pub const POSITION_CONTINUOUS = AE_POSITION_FLAGS.CONTINUOUS; pub const POSITION_QPC_ERROR = AE_POSITION_FLAGS.QPC_ERROR; pub const AE_CURRENT_POSITION = extern struct { u64DevicePosition: u64, u64StreamPosition: u64, u64PaddingFrames: u64, hnsQPCPosition: i64, f32FramesPerSecond: f32, Flag: AE_POSITION_FLAGS, }; // TODO: this type is limited to platform 'windows6.1' const IID_IAudioEndpoint_Value = Guid.initString("30a99515-1527-4451-af9f-00c5f0234daf"); pub const IID_IAudioEndpoint = &IID_IAudioEndpoint_Value; pub const IAudioEndpoint = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetFrameFormat: fn( self: *const IAudioEndpoint, ppFormat: ?*?*WAVEFORMATEX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFramesPerPacket: fn( self: *const IAudioEndpoint, pFramesPerPacket: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLatency: fn( self: *const IAudioEndpoint, pLatency: ?*i64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetStreamFlags: fn( self: *const IAudioEndpoint, streamFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEventHandle: fn( self: *const IAudioEndpoint, eventHandle: ?HANDLE, ) 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 IAudioEndpoint_GetFrameFormat(self: *const T, ppFormat: ?*?*WAVEFORMATEX) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpoint.VTable, self.vtable).GetFrameFormat(@ptrCast(*const IAudioEndpoint, self), ppFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpoint_GetFramesPerPacket(self: *const T, pFramesPerPacket: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpoint.VTable, self.vtable).GetFramesPerPacket(@ptrCast(*const IAudioEndpoint, self), pFramesPerPacket); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpoint_GetLatency(self: *const T, pLatency: ?*i64) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpoint.VTable, self.vtable).GetLatency(@ptrCast(*const IAudioEndpoint, self), pLatency); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpoint_SetStreamFlags(self: *const T, streamFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpoint.VTable, self.vtable).SetStreamFlags(@ptrCast(*const IAudioEndpoint, self), streamFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpoint_SetEventHandle(self: *const T, eventHandle: ?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpoint.VTable, self.vtable).SetEventHandle(@ptrCast(*const IAudioEndpoint, self), eventHandle); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IAudioEndpointRT_Value = Guid.initString("dfd2005f-a6e5-4d39-a265-939ada9fbb4d"); pub const IID_IAudioEndpointRT = &IID_IAudioEndpointRT_Value; pub const IAudioEndpointRT = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCurrentPadding: fn( self: *const IAudioEndpointRT, pPadding: ?*i64, pAeCurrentPosition: ?*AE_CURRENT_POSITION, ) callconv(@import("std").os.windows.WINAPI) void, ProcessingComplete: fn( self: *const IAudioEndpointRT, ) callconv(@import("std").os.windows.WINAPI) void, SetPinInactive: fn( self: *const IAudioEndpointRT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPinActive: fn( self: *const IAudioEndpointRT, ) 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 IAudioEndpointRT_GetCurrentPadding(self: *const T, pPadding: ?*i64, pAeCurrentPosition: ?*AE_CURRENT_POSITION) callconv(.Inline) void { return @ptrCast(*const IAudioEndpointRT.VTable, self.vtable).GetCurrentPadding(@ptrCast(*const IAudioEndpointRT, self), pPadding, pAeCurrentPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpointRT_ProcessingComplete(self: *const T) callconv(.Inline) void { return @ptrCast(*const IAudioEndpointRT.VTable, self.vtable).ProcessingComplete(@ptrCast(*const IAudioEndpointRT, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpointRT_SetPinInactive(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpointRT.VTable, self.vtable).SetPinInactive(@ptrCast(*const IAudioEndpointRT, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpointRT_SetPinActive(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpointRT.VTable, self.vtable).SetPinActive(@ptrCast(*const IAudioEndpointRT, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IAudioInputEndpointRT_Value = Guid.initString("8026ab61-92b2-43c1-a1df-5c37ebd08d82"); pub const IID_IAudioInputEndpointRT = &IID_IAudioInputEndpointRT_Value; pub const IAudioInputEndpointRT = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetInputDataPointer: fn( self: *const IAudioInputEndpointRT, pConnectionProperty: ?*APO_CONNECTION_PROPERTY, pAeTimeStamp: ?*AE_CURRENT_POSITION, ) callconv(@import("std").os.windows.WINAPI) void, ReleaseInputDataPointer: fn( self: *const IAudioInputEndpointRT, u32FrameCount: u32, pDataPointer: usize, ) callconv(@import("std").os.windows.WINAPI) void, PulseEndpoint: fn( self: *const IAudioInputEndpointRT, ) 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 IAudioInputEndpointRT_GetInputDataPointer(self: *const T, pConnectionProperty: ?*APO_CONNECTION_PROPERTY, pAeTimeStamp: ?*AE_CURRENT_POSITION) callconv(.Inline) void { return @ptrCast(*const IAudioInputEndpointRT.VTable, self.vtable).GetInputDataPointer(@ptrCast(*const IAudioInputEndpointRT, self), pConnectionProperty, pAeTimeStamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioInputEndpointRT_ReleaseInputDataPointer(self: *const T, u32FrameCount: u32, pDataPointer: usize) callconv(.Inline) void { return @ptrCast(*const IAudioInputEndpointRT.VTable, self.vtable).ReleaseInputDataPointer(@ptrCast(*const IAudioInputEndpointRT, self), u32FrameCount, pDataPointer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioInputEndpointRT_PulseEndpoint(self: *const T) callconv(.Inline) void { return @ptrCast(*const IAudioInputEndpointRT.VTable, self.vtable).PulseEndpoint(@ptrCast(*const IAudioInputEndpointRT, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IAudioOutputEndpointRT_Value = Guid.initString("8fa906e4-c31c-4e31-932e-19a66385e9aa"); pub const IID_IAudioOutputEndpointRT = &IID_IAudioOutputEndpointRT_Value; pub const IAudioOutputEndpointRT = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOutputDataPointer: fn( self: *const IAudioOutputEndpointRT, u32FrameCount: u32, pAeTimeStamp: ?*AE_CURRENT_POSITION, ) callconv(@import("std").os.windows.WINAPI) usize, ReleaseOutputDataPointer: fn( self: *const IAudioOutputEndpointRT, pConnectionProperty: ?*const APO_CONNECTION_PROPERTY, ) callconv(@import("std").os.windows.WINAPI) void, PulseEndpoint: fn( self: *const IAudioOutputEndpointRT, ) 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 IAudioOutputEndpointRT_GetOutputDataPointer(self: *const T, u32FrameCount: u32, pAeTimeStamp: ?*AE_CURRENT_POSITION) callconv(.Inline) usize { return @ptrCast(*const IAudioOutputEndpointRT.VTable, self.vtable).GetOutputDataPointer(@ptrCast(*const IAudioOutputEndpointRT, self), u32FrameCount, pAeTimeStamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioOutputEndpointRT_ReleaseOutputDataPointer(self: *const T, pConnectionProperty: ?*const APO_CONNECTION_PROPERTY) callconv(.Inline) void { return @ptrCast(*const IAudioOutputEndpointRT.VTable, self.vtable).ReleaseOutputDataPointer(@ptrCast(*const IAudioOutputEndpointRT, self), pConnectionProperty); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioOutputEndpointRT_PulseEndpoint(self: *const T) callconv(.Inline) void { return @ptrCast(*const IAudioOutputEndpointRT.VTable, self.vtable).PulseEndpoint(@ptrCast(*const IAudioOutputEndpointRT, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IAudioDeviceEndpoint_Value = Guid.initString("d4952f5a-a0b2-4cc4-8b82-9358488dd8ac"); pub const IID_IAudioDeviceEndpoint = &IID_IAudioDeviceEndpoint_Value; pub const IAudioDeviceEndpoint = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetBuffer: fn( self: *const IAudioDeviceEndpoint, MaxPeriod: i64, u32LatencyCoefficient: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRTCaps: fn( self: *const IAudioDeviceEndpoint, pbIsRTCapable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEventDrivenCapable: fn( self: *const IAudioDeviceEndpoint, pbisEventCapable: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteExclusiveModeParametersToSharedMemory: fn( self: *const IAudioDeviceEndpoint, hTargetProcess: usize, hnsPeriod: i64, hnsBufferDuration: i64, u32LatencyCoefficient: u32, pu32SharedMemorySize: ?*u32, phSharedMemory: ?*usize, ) 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 IAudioDeviceEndpoint_SetBuffer(self: *const T, MaxPeriod: i64, u32LatencyCoefficient: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioDeviceEndpoint.VTable, self.vtable).SetBuffer(@ptrCast(*const IAudioDeviceEndpoint, self), MaxPeriod, u32LatencyCoefficient); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioDeviceEndpoint_GetRTCaps(self: *const T, pbIsRTCapable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioDeviceEndpoint.VTable, self.vtable).GetRTCaps(@ptrCast(*const IAudioDeviceEndpoint, self), pbIsRTCapable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioDeviceEndpoint_GetEventDrivenCapable(self: *const T, pbisEventCapable: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioDeviceEndpoint.VTable, self.vtable).GetEventDrivenCapable(@ptrCast(*const IAudioDeviceEndpoint, self), pbisEventCapable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioDeviceEndpoint_WriteExclusiveModeParametersToSharedMemory(self: *const T, hTargetProcess: usize, hnsPeriod: i64, hnsBufferDuration: i64, u32LatencyCoefficient: u32, pu32SharedMemorySize: ?*u32, phSharedMemory: ?*usize) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioDeviceEndpoint.VTable, self.vtable).WriteExclusiveModeParametersToSharedMemory(@ptrCast(*const IAudioDeviceEndpoint, self), hTargetProcess, hnsPeriod, hnsBufferDuration, u32LatencyCoefficient, pu32SharedMemorySize, phSharedMemory); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IAudioEndpointControl_Value = Guid.initString("c684b72a-6df4-4774-bdf9-76b77509b653"); pub const IID_IAudioEndpointControl = &IID_IAudioEndpointControl_Value; pub const IAudioEndpointControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Start: fn( self: *const IAudioEndpointControl, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IAudioEndpointControl, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IAudioEndpointControl, ) 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 IAudioEndpointControl_Start(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpointControl.VTable, self.vtable).Start(@ptrCast(*const IAudioEndpointControl, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpointControl_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpointControl.VTable, self.vtable).Reset(@ptrCast(*const IAudioEndpointControl, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAudioEndpointControl_Stop(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IAudioEndpointControl.VTable, self.vtable).Stop(@ptrCast(*const IAudioEndpointControl, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type has a FreeFunc 'WTSVirtualChannelClose', what can Zig do with this information? pub const HwtsVirtualChannelHandle = isize; const CLSID_TSUserExInterfaces_Value = Guid.initString("0910dd01-df8c-11d1-ae27-00c04fa35813"); pub const CLSID_TSUserExInterfaces = &CLSID_TSUserExInterfaces_Value; const CLSID_ADsTSUserEx_Value = Guid.initString("e2e9cae6-1e7b-4b8e-babd-e9bf6292ac29"); pub const CLSID_ADsTSUserEx = &CLSID_ADsTSUserEx_Value; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsTSUserEx_Value = Guid.initString("c4930e79-2989-4462-8a60-2fcf2f2955ef"); pub const IID_IADsTSUserEx = &IID_IADsTSUserEx_Value; pub const IADsTSUserEx = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TerminalServicesProfilePath: fn( self: *const IADsTSUserEx, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TerminalServicesProfilePath: fn( self: *const IADsTSUserEx, pNewVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TerminalServicesHomeDirectory: fn( self: *const IADsTSUserEx, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TerminalServicesHomeDirectory: fn( self: *const IADsTSUserEx, pNewVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TerminalServicesHomeDrive: fn( self: *const IADsTSUserEx, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TerminalServicesHomeDrive: fn( self: *const IADsTSUserEx, pNewVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AllowLogon: fn( self: *const IADsTSUserEx, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AllowLogon: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EnableRemoteControl: fn( self: *const IADsTSUserEx, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EnableRemoteControl: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxDisconnectionTime: fn( self: *const IADsTSUserEx, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxDisconnectionTime: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxConnectionTime: fn( self: *const IADsTSUserEx, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxConnectionTime: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxIdleTime: fn( self: *const IADsTSUserEx, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxIdleTime: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReconnectionAction: fn( self: *const IADsTSUserEx, pNewVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReconnectionAction: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BrokenConnectionAction: fn( self: *const IADsTSUserEx, pNewVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BrokenConnectionAction: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ConnectClientDrivesAtLogon: fn( self: *const IADsTSUserEx, pNewVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ConnectClientDrivesAtLogon: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ConnectClientPrintersAtLogon: fn( self: *const IADsTSUserEx, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ConnectClientPrintersAtLogon: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DefaultToMainPrinter: fn( self: *const IADsTSUserEx, pVal: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DefaultToMainPrinter: fn( self: *const IADsTSUserEx, NewVal: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TerminalServicesWorkDirectory: fn( self: *const IADsTSUserEx, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TerminalServicesWorkDirectory: fn( self: *const IADsTSUserEx, pNewVal: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TerminalServicesInitialProgram: fn( self: *const IADsTSUserEx, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TerminalServicesInitialProgram: fn( self: *const IADsTSUserEx, pNewVal: ?BSTR, ) 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 IADsTSUserEx_get_TerminalServicesProfilePath(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_TerminalServicesProfilePath(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_TerminalServicesProfilePath(self: *const T, pNewVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_TerminalServicesProfilePath(@ptrCast(*const IADsTSUserEx, self), pNewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_TerminalServicesHomeDirectory(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_TerminalServicesHomeDirectory(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_TerminalServicesHomeDirectory(self: *const T, pNewVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_TerminalServicesHomeDirectory(@ptrCast(*const IADsTSUserEx, self), pNewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_TerminalServicesHomeDrive(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_TerminalServicesHomeDrive(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_TerminalServicesHomeDrive(self: *const T, pNewVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_TerminalServicesHomeDrive(@ptrCast(*const IADsTSUserEx, self), pNewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_AllowLogon(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_AllowLogon(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_AllowLogon(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_AllowLogon(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_EnableRemoteControl(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_EnableRemoteControl(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_EnableRemoteControl(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_EnableRemoteControl(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_MaxDisconnectionTime(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_MaxDisconnectionTime(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_MaxDisconnectionTime(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_MaxDisconnectionTime(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_MaxConnectionTime(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_MaxConnectionTime(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_MaxConnectionTime(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_MaxConnectionTime(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_MaxIdleTime(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_MaxIdleTime(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_MaxIdleTime(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_MaxIdleTime(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_ReconnectionAction(self: *const T, pNewVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_ReconnectionAction(@ptrCast(*const IADsTSUserEx, self), pNewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_ReconnectionAction(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_ReconnectionAction(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_BrokenConnectionAction(self: *const T, pNewVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_BrokenConnectionAction(@ptrCast(*const IADsTSUserEx, self), pNewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_BrokenConnectionAction(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_BrokenConnectionAction(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_ConnectClientDrivesAtLogon(self: *const T, pNewVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_ConnectClientDrivesAtLogon(@ptrCast(*const IADsTSUserEx, self), pNewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_ConnectClientDrivesAtLogon(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_ConnectClientDrivesAtLogon(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_ConnectClientPrintersAtLogon(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_ConnectClientPrintersAtLogon(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_ConnectClientPrintersAtLogon(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_ConnectClientPrintersAtLogon(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_DefaultToMainPrinter(self: *const T, pVal: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_DefaultToMainPrinter(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_DefaultToMainPrinter(self: *const T, NewVal: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_DefaultToMainPrinter(@ptrCast(*const IADsTSUserEx, self), NewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_TerminalServicesWorkDirectory(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_TerminalServicesWorkDirectory(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_TerminalServicesWorkDirectory(self: *const T, pNewVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_TerminalServicesWorkDirectory(@ptrCast(*const IADsTSUserEx, self), pNewVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_get_TerminalServicesInitialProgram(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).get_TerminalServicesInitialProgram(@ptrCast(*const IADsTSUserEx, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTSUserEx_put_TerminalServicesInitialProgram(self: *const T, pNewVal: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTSUserEx.VTable, self.vtable).put_TerminalServicesInitialProgram(@ptrCast(*const IADsTSUserEx, self), pNewVal); } };} pub usingnamespace MethodMixin(@This()); }; pub const AAAuthSchemes = enum(i32) { MIN = 0, BASIC = 1, NTLM = 2, SC = 3, LOGGEDONCREDENTIALS = 4, NEGOTIATE = 5, ANY = 6, COOKIE = 7, DIGEST = 8, ORGID = 9, CONID = 10, SSPI_NTLM = 11, MAX = 12, }; pub const AA_AUTH_MIN = AAAuthSchemes.MIN; pub const AA_AUTH_BASIC = AAAuthSchemes.BASIC; pub const AA_AUTH_NTLM = AAAuthSchemes.NTLM; pub const AA_AUTH_SC = AAAuthSchemes.SC; pub const AA_AUTH_LOGGEDONCREDENTIALS = AAAuthSchemes.LOGGEDONCREDENTIALS; pub const AA_AUTH_NEGOTIATE = AAAuthSchemes.NEGOTIATE; pub const AA_AUTH_ANY = AAAuthSchemes.ANY; pub const AA_AUTH_COOKIE = AAAuthSchemes.COOKIE; pub const AA_AUTH_DIGEST = AAAuthSchemes.DIGEST; pub const AA_AUTH_ORGID = AAAuthSchemes.ORGID; pub const AA_AUTH_CONID = AAAuthSchemes.CONID; pub const AA_AUTH_SSPI_NTLM = AAAuthSchemes.SSPI_NTLM; pub const AA_AUTH_MAX = AAAuthSchemes.MAX; pub const AAAccountingDataType = enum(i32) { MAIN_SESSION_CREATION = 0, SUB_SESSION_CREATION = 1, SUB_SESSION_CLOSED = 2, MAIN_SESSION_CLOSED = 3, }; pub const AA_MAIN_SESSION_CREATION = AAAccountingDataType.MAIN_SESSION_CREATION; pub const AA_SUB_SESSION_CREATION = AAAccountingDataType.SUB_SESSION_CREATION; pub const AA_SUB_SESSION_CLOSED = AAAccountingDataType.SUB_SESSION_CLOSED; pub const AA_MAIN_SESSION_CLOSED = AAAccountingDataType.MAIN_SESSION_CLOSED; pub const AAAccountingData = extern struct { userName: ?BSTR, clientName: ?BSTR, authType: AAAuthSchemes, resourceName: ?BSTR, portNumber: i32, protocolName: ?BSTR, numberOfBytesReceived: i32, numberOfBytesTransfered: i32, reasonForDisconnect: ?BSTR, mainSessionId: Guid, subSessionId: i32, }; pub const SESSION_TIMEOUT_ACTION_TYPE = enum(i32) { DISCONNECT = 0, SILENT_REAUTH = 1, }; pub const SESSION_TIMEOUT_ACTION_DISCONNECT = SESSION_TIMEOUT_ACTION_TYPE.DISCONNECT; pub const SESSION_TIMEOUT_ACTION_SILENT_REAUTH = SESSION_TIMEOUT_ACTION_TYPE.SILENT_REAUTH; pub const PolicyAttributeType = enum(i32) { EnableAllRedirections = 0, DisableAllRedirections = 1, DriveRedirectionDisabled = 2, PrinterRedirectionDisabled = 3, PortRedirectionDisabled = 4, ClipboardRedirectionDisabled = 5, PnpRedirectionDisabled = 6, AllowOnlySDRServers = 7, }; pub const EnableAllRedirections = PolicyAttributeType.EnableAllRedirections; pub const DisableAllRedirections = PolicyAttributeType.DisableAllRedirections; pub const DriveRedirectionDisabled = PolicyAttributeType.DriveRedirectionDisabled; pub const PrinterRedirectionDisabled = PolicyAttributeType.PrinterRedirectionDisabled; pub const PortRedirectionDisabled = PolicyAttributeType.PortRedirectionDisabled; pub const ClipboardRedirectionDisabled = PolicyAttributeType.ClipboardRedirectionDisabled; pub const PnpRedirectionDisabled = PolicyAttributeType.PnpRedirectionDisabled; pub const AllowOnlySDRServers = PolicyAttributeType.AllowOnlySDRServers; pub const AATrustClassID = enum(i32) { UNTRUSTED = 0, TRUSTEDUSER_UNTRUSTEDCLIENT = 1, TRUSTEDUSER_TRUSTEDCLIENT = 2, }; pub const AA_UNTRUSTED = AATrustClassID.UNTRUSTED; pub const AA_TRUSTEDUSER_UNTRUSTEDCLIENT = AATrustClassID.TRUSTEDUSER_UNTRUSTEDCLIENT; pub const AA_TRUSTEDUSER_TRUSTEDCLIENT = AATrustClassID.TRUSTEDUSER_TRUSTEDCLIENT; // TODO: this type is limited to platform 'windows6.1' const IID_ITSGAuthorizeConnectionSink_Value = Guid.initString("c27ece33-7781-4318-98ef-1cf2da7b7005"); pub const IID_ITSGAuthorizeConnectionSink = &IID_ITSGAuthorizeConnectionSink_Value; pub const ITSGAuthorizeConnectionSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnConnectionAuthorized: fn( self: *const ITSGAuthorizeConnectionSink, hrIn: HRESULT, mainSessionId: Guid, cbSoHResponse: u32, pbSoHResponse: [*:0]u8, idleTimeout: u32, sessionTimeout: u32, sessionTimeoutAction: SESSION_TIMEOUT_ACTION_TYPE, trustClass: AATrustClassID, policyAttributes: ?*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 ITSGAuthorizeConnectionSink_OnConnectionAuthorized(self: *const T, hrIn: HRESULT, mainSessionId: Guid, cbSoHResponse: u32, pbSoHResponse: [*:0]u8, idleTimeout: u32, sessionTimeout: u32, sessionTimeoutAction: SESSION_TIMEOUT_ACTION_TYPE, trustClass: AATrustClassID, policyAttributes: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAuthorizeConnectionSink.VTable, self.vtable).OnConnectionAuthorized(@ptrCast(*const ITSGAuthorizeConnectionSink, self), hrIn, mainSessionId, cbSoHResponse, pbSoHResponse, idleTimeout, sessionTimeout, sessionTimeoutAction, trustClass, policyAttributes); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ITSGAuthorizeResourceSink_Value = Guid.initString("feddfcd4-fa12-4435-ae55-7ad1a9779af7"); pub const IID_ITSGAuthorizeResourceSink = &IID_ITSGAuthorizeResourceSink_Value; pub const ITSGAuthorizeResourceSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnChannelAuthorized: fn( self: *const ITSGAuthorizeResourceSink, hrIn: HRESULT, mainSessionId: Guid, subSessionId: i32, allowedResourceNames: [*]?BSTR, numAllowedResourceNames: u32, failedResourceNames: [*]?BSTR, numFailedResourceNames: 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 ITSGAuthorizeResourceSink_OnChannelAuthorized(self: *const T, hrIn: HRESULT, mainSessionId: Guid, subSessionId: i32, allowedResourceNames: [*]?BSTR, numAllowedResourceNames: u32, failedResourceNames: [*]?BSTR, numFailedResourceNames: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAuthorizeResourceSink.VTable, self.vtable).OnChannelAuthorized(@ptrCast(*const ITSGAuthorizeResourceSink, self), hrIn, mainSessionId, subSessionId, allowedResourceNames, numAllowedResourceNames, failedResourceNames, numFailedResourceNames); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ITSGPolicyEngine_Value = Guid.initString("8bc24f08-6223-42f4-a5b4-8e37cd135bbd"); pub const IID_ITSGPolicyEngine = &IID_ITSGPolicyEngine_Value; pub const ITSGPolicyEngine = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AuthorizeConnection: fn( self: *const ITSGPolicyEngine, mainSessionId: Guid, username: ?BSTR, authType: AAAuthSchemes, clientMachineIP: ?BSTR, clientMachineName: ?BSTR, sohData: [*:0]u8, numSOHBytes: u32, cookieData: [*:0]u8, numCookieBytes: u32, userToken: HANDLE_PTR, pSink: ?*ITSGAuthorizeConnectionSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AuthorizeResource: fn( self: *const ITSGPolicyEngine, mainSessionId: Guid, subSessionId: i32, username: ?BSTR, resourceNames: [*]?BSTR, numResources: u32, alternateResourceNames: [*]?BSTR, numAlternateResourceName: u32, portNumber: u32, operation: ?BSTR, cookie: [*:0]u8, numBytesInCookie: u32, pSink: ?*ITSGAuthorizeResourceSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Refresh: fn( self: *const ITSGPolicyEngine, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsQuarantineEnabled: fn( self: *const ITSGPolicyEngine, quarantineEnabled: ?*BOOL, ) 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 ITSGPolicyEngine_AuthorizeConnection(self: *const T, mainSessionId: Guid, username: ?BSTR, authType: AAAuthSchemes, clientMachineIP: ?BSTR, clientMachineName: ?BSTR, sohData: [*:0]u8, numSOHBytes: u32, cookieData: [*:0]u8, numCookieBytes: u32, userToken: HANDLE_PTR, pSink: ?*ITSGAuthorizeConnectionSink) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGPolicyEngine.VTable, self.vtable).AuthorizeConnection(@ptrCast(*const ITSGPolicyEngine, self), mainSessionId, username, authType, clientMachineIP, clientMachineName, sohData, numSOHBytes, cookieData, numCookieBytes, userToken, pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITSGPolicyEngine_AuthorizeResource(self: *const T, mainSessionId: Guid, subSessionId: i32, username: ?BSTR, resourceNames: [*]?BSTR, numResources: u32, alternateResourceNames: [*]?BSTR, numAlternateResourceName: u32, portNumber: u32, operation: ?BSTR, cookie: [*:0]u8, numBytesInCookie: u32, pSink: ?*ITSGAuthorizeResourceSink) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGPolicyEngine.VTable, self.vtable).AuthorizeResource(@ptrCast(*const ITSGPolicyEngine, self), mainSessionId, subSessionId, username, resourceNames, numResources, alternateResourceNames, numAlternateResourceName, portNumber, operation, cookie, numBytesInCookie, pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITSGPolicyEngine_Refresh(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGPolicyEngine.VTable, self.vtable).Refresh(@ptrCast(*const ITSGPolicyEngine, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITSGPolicyEngine_IsQuarantineEnabled(self: *const T, quarantineEnabled: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGPolicyEngine.VTable, self.vtable).IsQuarantineEnabled(@ptrCast(*const ITSGPolicyEngine, self), quarantineEnabled); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ITSGAccountingEngine_Value = Guid.initString("4ce2a0c9-e874-4f1a-86f4-06bbb9115338"); pub const IID_ITSGAccountingEngine = &IID_ITSGAccountingEngine_Value; pub const ITSGAccountingEngine = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, DoAccounting: fn( self: *const ITSGAccountingEngine, accountingDataType: AAAccountingDataType, accountingData: AAAccountingData, ) 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 ITSGAccountingEngine_DoAccounting(self: *const T, accountingDataType: AAAccountingDataType, accountingData: AAAccountingData) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAccountingEngine.VTable, self.vtable).DoAccounting(@ptrCast(*const ITSGAccountingEngine, self), accountingDataType, accountingData); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ITSGAuthenticateUserSink_Value = Guid.initString("2c3e2e73-a782-47f9-8dfb-77ee1ed27a03"); pub const IID_ITSGAuthenticateUserSink = &IID_ITSGAuthenticateUserSink_Value; pub const ITSGAuthenticateUserSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnUserAuthenticated: fn( self: *const ITSGAuthenticateUserSink, userName: ?BSTR, userDomain: ?BSTR, context: usize, userToken: HANDLE_PTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnUserAuthenticationFailed: fn( self: *const ITSGAuthenticateUserSink, context: usize, genericErrorCode: HRESULT, specificErrorCode: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReauthenticateUser: fn( self: *const ITSGAuthenticateUserSink, context: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisconnectUser: fn( self: *const ITSGAuthenticateUserSink, context: usize, ) 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 ITSGAuthenticateUserSink_OnUserAuthenticated(self: *const T, userName: ?BSTR, userDomain: ?BSTR, context: usize, userToken: HANDLE_PTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAuthenticateUserSink.VTable, self.vtable).OnUserAuthenticated(@ptrCast(*const ITSGAuthenticateUserSink, self), userName, userDomain, context, userToken); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITSGAuthenticateUserSink_OnUserAuthenticationFailed(self: *const T, context: usize, genericErrorCode: HRESULT, specificErrorCode: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAuthenticateUserSink.VTable, self.vtable).OnUserAuthenticationFailed(@ptrCast(*const ITSGAuthenticateUserSink, self), context, genericErrorCode, specificErrorCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITSGAuthenticateUserSink_ReauthenticateUser(self: *const T, context: usize) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAuthenticateUserSink.VTable, self.vtable).ReauthenticateUser(@ptrCast(*const ITSGAuthenticateUserSink, self), context); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITSGAuthenticateUserSink_DisconnectUser(self: *const T, context: usize) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAuthenticateUserSink.VTable, self.vtable).DisconnectUser(@ptrCast(*const ITSGAuthenticateUserSink, self), context); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ITSGAuthenticationEngine_Value = Guid.initString("9ee3e5bf-04ab-4691-998c-d7f622321a56"); pub const IID_ITSGAuthenticationEngine = &IID_ITSGAuthenticationEngine_Value; pub const ITSGAuthenticationEngine = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AuthenticateUser: fn( self: *const ITSGAuthenticationEngine, mainSessionId: Guid, cookieData: ?*u8, numCookieBytes: u32, context: usize, pSink: ?*ITSGAuthenticateUserSink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelAuthentication: fn( self: *const ITSGAuthenticationEngine, mainSessionId: Guid, context: usize, ) 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 ITSGAuthenticationEngine_AuthenticateUser(self: *const T, mainSessionId: Guid, cookieData: ?*u8, numCookieBytes: u32, context: usize, pSink: ?*ITSGAuthenticateUserSink) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAuthenticationEngine.VTable, self.vtable).AuthenticateUser(@ptrCast(*const ITSGAuthenticationEngine, self), mainSessionId, cookieData, numCookieBytes, context, pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITSGAuthenticationEngine_CancelAuthentication(self: *const T, mainSessionId: Guid, context: usize) callconv(.Inline) HRESULT { return @ptrCast(*const ITSGAuthenticationEngine.VTable, self.vtable).CancelAuthentication(@ptrCast(*const ITSGAuthenticationEngine, self), mainSessionId, context); } };} pub usingnamespace MethodMixin(@This()); }; pub const WTS_CONNECTSTATE_CLASS = enum(i32) { Active = 0, Connected = 1, ConnectQuery = 2, Shadow = 3, Disconnected = 4, Idle = 5, Listen = 6, Reset = 7, Down = 8, Init = 9, }; pub const WTSActive = WTS_CONNECTSTATE_CLASS.Active; pub const WTSConnected = WTS_CONNECTSTATE_CLASS.Connected; pub const WTSConnectQuery = WTS_CONNECTSTATE_CLASS.ConnectQuery; pub const WTSShadow = WTS_CONNECTSTATE_CLASS.Shadow; pub const WTSDisconnected = WTS_CONNECTSTATE_CLASS.Disconnected; pub const WTSIdle = WTS_CONNECTSTATE_CLASS.Idle; pub const WTSListen = WTS_CONNECTSTATE_CLASS.Listen; pub const WTSReset = WTS_CONNECTSTATE_CLASS.Reset; pub const WTSDown = WTS_CONNECTSTATE_CLASS.Down; pub const WTSInit = WTS_CONNECTSTATE_CLASS.Init; pub const WTS_SERVER_INFOW = extern struct { pServerName: ?PWSTR, }; pub const WTS_SERVER_INFOA = extern struct { pServerName: ?PSTR, }; pub const WTS_SESSION_INFOW = extern struct { SessionId: u32, pWinStationName: ?PWSTR, State: WTS_CONNECTSTATE_CLASS, }; pub const WTS_SESSION_INFOA = extern struct { SessionId: u32, pWinStationName: ?PSTR, State: WTS_CONNECTSTATE_CLASS, }; pub const WTS_SESSION_INFO_1W = extern struct { ExecEnvId: u32, State: WTS_CONNECTSTATE_CLASS, SessionId: u32, pSessionName: ?PWSTR, pHostName: ?PWSTR, pUserName: ?PWSTR, pDomainName: ?PWSTR, pFarmName: ?PWSTR, }; pub const WTS_SESSION_INFO_1A = extern struct { ExecEnvId: u32, State: WTS_CONNECTSTATE_CLASS, SessionId: u32, pSessionName: ?PSTR, pHostName: ?PSTR, pUserName: ?PSTR, pDomainName: ?PSTR, pFarmName: ?PSTR, }; pub const WTS_PROCESS_INFOW = extern struct { SessionId: u32, ProcessId: u32, pProcessName: ?PWSTR, pUserSid: ?PSID, }; pub const WTS_PROCESS_INFOA = extern struct { SessionId: u32, ProcessId: u32, pProcessName: ?PSTR, pUserSid: ?PSID, }; pub const WTS_INFO_CLASS = enum(i32) { InitialProgram = 0, ApplicationName = 1, WorkingDirectory = 2, OEMId = 3, SessionId = 4, UserName = 5, WinStationName = 6, DomainName = 7, ConnectState = 8, ClientBuildNumber = 9, ClientName = 10, ClientDirectory = 11, ClientProductId = 12, ClientHardwareId = 13, ClientAddress = 14, ClientDisplay = 15, ClientProtocolType = 16, IdleTime = 17, LogonTime = 18, IncomingBytes = 19, OutgoingBytes = 20, IncomingFrames = 21, OutgoingFrames = 22, ClientInfo = 23, SessionInfo = 24, SessionInfoEx = 25, ConfigInfo = 26, ValidationInfo = 27, SessionAddressV4 = 28, IsRemoteSession = 29, }; pub const WTSInitialProgram = WTS_INFO_CLASS.InitialProgram; pub const WTSApplicationName = WTS_INFO_CLASS.ApplicationName; pub const WTSWorkingDirectory = WTS_INFO_CLASS.WorkingDirectory; pub const WTSOEMId = WTS_INFO_CLASS.OEMId; pub const WTSSessionId = WTS_INFO_CLASS.SessionId; pub const WTSUserName = WTS_INFO_CLASS.UserName; pub const WTSWinStationName = WTS_INFO_CLASS.WinStationName; pub const WTSDomainName = WTS_INFO_CLASS.DomainName; pub const WTSConnectState = WTS_INFO_CLASS.ConnectState; pub const WTSClientBuildNumber = WTS_INFO_CLASS.ClientBuildNumber; pub const WTSClientName = WTS_INFO_CLASS.ClientName; pub const WTSClientDirectory = WTS_INFO_CLASS.ClientDirectory; pub const WTSClientProductId = WTS_INFO_CLASS.ClientProductId; pub const WTSClientHardwareId = WTS_INFO_CLASS.ClientHardwareId; pub const WTSClientAddress = WTS_INFO_CLASS.ClientAddress; pub const WTSClientDisplay = WTS_INFO_CLASS.ClientDisplay; pub const WTSClientProtocolType = WTS_INFO_CLASS.ClientProtocolType; pub const WTSIdleTime = WTS_INFO_CLASS.IdleTime; pub const WTSLogonTime = WTS_INFO_CLASS.LogonTime; pub const WTSIncomingBytes = WTS_INFO_CLASS.IncomingBytes; pub const WTSOutgoingBytes = WTS_INFO_CLASS.OutgoingBytes; pub const WTSIncomingFrames = WTS_INFO_CLASS.IncomingFrames; pub const WTSOutgoingFrames = WTS_INFO_CLASS.OutgoingFrames; pub const WTSClientInfo = WTS_INFO_CLASS.ClientInfo; pub const WTSSessionInfo = WTS_INFO_CLASS.SessionInfo; pub const WTSSessionInfoEx = WTS_INFO_CLASS.SessionInfoEx; pub const WTSConfigInfo = WTS_INFO_CLASS.ConfigInfo; pub const WTSValidationInfo = WTS_INFO_CLASS.ValidationInfo; pub const WTSSessionAddressV4 = WTS_INFO_CLASS.SessionAddressV4; pub const WTSIsRemoteSession = WTS_INFO_CLASS.IsRemoteSession; pub const WTSCONFIGINFOW = extern struct { version: u32, fConnectClientDrivesAtLogon: u32, fConnectPrinterAtLogon: u32, fDisablePrinterRedirection: u32, fDisableDefaultMainClientPrinter: u32, ShadowSettings: u32, LogonUserName: [21]u16, LogonDomain: [18]u16, WorkDirectory: [261]u16, InitialProgram: [261]u16, ApplicationName: [261]u16, }; pub const WTSCONFIGINFOA = extern struct { version: u32, fConnectClientDrivesAtLogon: u32, fConnectPrinterAtLogon: u32, fDisablePrinterRedirection: u32, fDisableDefaultMainClientPrinter: u32, ShadowSettings: u32, LogonUserName: [21]CHAR, LogonDomain: [18]CHAR, WorkDirectory: [261]CHAR, InitialProgram: [261]CHAR, ApplicationName: [261]CHAR, }; pub const WTSINFOW = extern struct { State: WTS_CONNECTSTATE_CLASS, SessionId: u32, IncomingBytes: u32, OutgoingBytes: u32, IncomingFrames: u32, OutgoingFrames: u32, IncomingCompressedBytes: u32, OutgoingCompressedBytes: u32, WinStationName: [32]u16, Domain: [17]u16, UserName: [21]u16, ConnectTime: LARGE_INTEGER, DisconnectTime: LARGE_INTEGER, LastInputTime: LARGE_INTEGER, LogonTime: LARGE_INTEGER, CurrentTime: LARGE_INTEGER, }; pub const WTSINFOA = extern struct { State: WTS_CONNECTSTATE_CLASS, SessionId: u32, IncomingBytes: u32, OutgoingBytes: u32, IncomingFrames: u32, OutgoingFrames: u32, IncomingCompressedBytes: u32, OutgoingCompressedBy: u32, WinStationName: [32]CHAR, Domain: [17]CHAR, UserName: [21]CHAR, ConnectTime: LARGE_INTEGER, DisconnectTime: LARGE_INTEGER, LastInputTime: LARGE_INTEGER, LogonTime: LARGE_INTEGER, CurrentTime: LARGE_INTEGER, }; pub const WTSINFOEX_LEVEL1_W = extern struct { SessionId: u32, SessionState: WTS_CONNECTSTATE_CLASS, SessionFlags: i32, WinStationName: [33]u16, UserName: [21]u16, DomainName: [18]u16, LogonTime: LARGE_INTEGER, ConnectTime: LARGE_INTEGER, DisconnectTime: LARGE_INTEGER, LastInputTime: LARGE_INTEGER, CurrentTime: LARGE_INTEGER, IncomingBytes: u32, OutgoingBytes: u32, IncomingFrames: u32, OutgoingFrames: u32, IncomingCompressedBytes: u32, OutgoingCompressedBytes: u32, }; pub const WTSINFOEX_LEVEL1_A = extern struct { SessionId: u32, SessionState: WTS_CONNECTSTATE_CLASS, SessionFlags: i32, WinStationName: [33]CHAR, UserName: [21]CHAR, DomainName: [18]CHAR, LogonTime: LARGE_INTEGER, ConnectTime: LARGE_INTEGER, DisconnectTime: LARGE_INTEGER, LastInputTime: LARGE_INTEGER, CurrentTime: LARGE_INTEGER, IncomingBytes: u32, OutgoingBytes: u32, IncomingFrames: u32, OutgoingFrames: u32, IncomingCompressedBytes: u32, OutgoingCompressedBytes: u32, }; pub const WTSINFOEX_LEVEL_W = extern union { WTSInfoExLevel1: WTSINFOEX_LEVEL1_W, }; pub const WTSINFOEX_LEVEL_A = extern union { WTSInfoExLevel1: WTSINFOEX_LEVEL1_A, }; pub const WTSINFOEXW = extern struct { Level: u32, Data: WTSINFOEX_LEVEL_W, }; pub const WTSINFOEXA = extern struct { Level: u32, Data: WTSINFOEX_LEVEL_A, }; pub const WTSCLIENTW = extern struct { ClientName: [21]u16, Domain: [18]u16, UserName: [21]u16, WorkDirectory: [261]u16, InitialProgram: [261]u16, EncryptionLevel: u8, ClientAddressFamily: u32, ClientAddress: [31]u16, HRes: u16, VRes: u16, ColorDepth: u16, ClientDirectory: [261]u16, ClientBuildNumber: u32, ClientHardwareId: u32, ClientProductId: u16, OutBufCountHost: u16, OutBufCountClient: u16, OutBufLength: u16, DeviceId: [261]u16, }; pub const WTSCLIENTA = extern struct { ClientName: [21]CHAR, Domain: [18]CHAR, UserName: [21]CHAR, WorkDirectory: [261]CHAR, InitialProgram: [261]CHAR, EncryptionLevel: u8, ClientAddressFamily: u32, ClientAddress: [31]u16, HRes: u16, VRes: u16, ColorDepth: u16, ClientDirectory: [261]CHAR, ClientBuildNumber: u32, ClientHardwareId: u32, ClientProductId: u16, OutBufCountHost: u16, OutBufCountClient: u16, OutBufLength: u16, DeviceId: [261]CHAR, }; pub const _WTS_PRODUCT_INFOA = extern struct { CompanyName: [256]CHAR, ProductID: [4]CHAR, }; pub const _WTS_PRODUCT_INFOW = extern struct { CompanyName: [256]u16, ProductID: [4]u16, }; pub const WTS_VALIDATION_INFORMATIONA = extern struct { ProductInfo: _WTS_PRODUCT_INFOA, License: [16384]u8, LicenseLength: u32, HardwareID: [20]u8, HardwareIDLength: u32, }; pub const WTS_VALIDATION_INFORMATIONW = extern struct { ProductInfo: _WTS_PRODUCT_INFOW, License: [16384]u8, LicenseLength: u32, HardwareID: [20]u8, HardwareIDLength: u32, }; pub const WTS_CLIENT_ADDRESS = extern struct { AddressFamily: u32, Address: [20]u8, }; pub const WTS_CLIENT_DISPLAY = extern struct { HorizontalResolution: u32, VerticalResolution: u32, ColorDepth: u32, }; pub const WTS_CONFIG_CLASS = enum(i32) { InitialProgram = 0, WorkingDirectory = 1, fInheritInitialProgram = 2, fAllowLogonTerminalServer = 3, TimeoutSettingsConnections = 4, TimeoutSettingsDisconnections = 5, TimeoutSettingsIdle = 6, fDeviceClientDrives = 7, fDeviceClientPrinters = 8, fDeviceClientDefaultPrinter = 9, BrokenTimeoutSettings = 10, ReconnectSettings = 11, ModemCallbackSettings = 12, ModemCallbackPhoneNumber = 13, ShadowingSettings = 14, TerminalServerProfilePath = 15, TerminalServerHomeDir = 16, TerminalServerHomeDirDrive = 17, fTerminalServerRemoteHomeDir = 18, User = 19, }; pub const WTSUserConfigInitialProgram = WTS_CONFIG_CLASS.InitialProgram; pub const WTSUserConfigWorkingDirectory = WTS_CONFIG_CLASS.WorkingDirectory; pub const WTSUserConfigfInheritInitialProgram = WTS_CONFIG_CLASS.fInheritInitialProgram; pub const WTSUserConfigfAllowLogonTerminalServer = WTS_CONFIG_CLASS.fAllowLogonTerminalServer; pub const WTSUserConfigTimeoutSettingsConnections = WTS_CONFIG_CLASS.TimeoutSettingsConnections; pub const WTSUserConfigTimeoutSettingsDisconnections = WTS_CONFIG_CLASS.TimeoutSettingsDisconnections; pub const WTSUserConfigTimeoutSettingsIdle = WTS_CONFIG_CLASS.TimeoutSettingsIdle; pub const WTSUserConfigfDeviceClientDrives = WTS_CONFIG_CLASS.fDeviceClientDrives; pub const WTSUserConfigfDeviceClientPrinters = WTS_CONFIG_CLASS.fDeviceClientPrinters; pub const WTSUserConfigfDeviceClientDefaultPrinter = WTS_CONFIG_CLASS.fDeviceClientDefaultPrinter; pub const WTSUserConfigBrokenTimeoutSettings = WTS_CONFIG_CLASS.BrokenTimeoutSettings; pub const WTSUserConfigReconnectSettings = WTS_CONFIG_CLASS.ReconnectSettings; pub const WTSUserConfigModemCallbackSettings = WTS_CONFIG_CLASS.ModemCallbackSettings; pub const WTSUserConfigModemCallbackPhoneNumber = WTS_CONFIG_CLASS.ModemCallbackPhoneNumber; pub const WTSUserConfigShadowingSettings = WTS_CONFIG_CLASS.ShadowingSettings; pub const WTSUserConfigTerminalServerProfilePath = WTS_CONFIG_CLASS.TerminalServerProfilePath; pub const WTSUserConfigTerminalServerHomeDir = WTS_CONFIG_CLASS.TerminalServerHomeDir; pub const WTSUserConfigTerminalServerHomeDirDrive = WTS_CONFIG_CLASS.TerminalServerHomeDirDrive; pub const WTSUserConfigfTerminalServerRemoteHomeDir = WTS_CONFIG_CLASS.fTerminalServerRemoteHomeDir; pub const WTSUserConfigUser = WTS_CONFIG_CLASS.User; pub const WTS_CONFIG_SOURCE = enum(i32) { M = 0, }; pub const WTSUserConfigSourceSAM = WTS_CONFIG_SOURCE.M; pub const WTSUSERCONFIGA = extern struct { Source: u32, InheritInitialProgram: u32, AllowLogonTerminalServer: u32, TimeoutSettingsConnections: u32, TimeoutSettingsDisconnections: u32, TimeoutSettingsIdle: u32, DeviceClientDrives: u32, DeviceClientPrinters: u32, ClientDefaultPrinter: u32, BrokenTimeoutSettings: u32, ReconnectSettings: u32, ShadowingSettings: u32, TerminalServerRemoteHomeDir: u32, InitialProgram: [261]CHAR, WorkDirectory: [261]CHAR, TerminalServerProfilePath: [261]CHAR, TerminalServerHomeDir: [261]CHAR, TerminalServerHomeDirDrive: [4]CHAR, }; pub const WTSUSERCONFIGW = extern struct { Source: u32, InheritInitialProgram: u32, AllowLogonTerminalServer: u32, TimeoutSettingsConnections: u32, TimeoutSettingsDisconnections: u32, TimeoutSettingsIdle: u32, DeviceClientDrives: u32, DeviceClientPrinters: u32, ClientDefaultPrinter: u32, BrokenTimeoutSettings: u32, ReconnectSettings: u32, ShadowingSettings: u32, TerminalServerRemoteHomeDir: u32, InitialProgram: [261]u16, WorkDirectory: [261]u16, TerminalServerProfilePath: [261]u16, TerminalServerHomeDir: [261]u16, TerminalServerHomeDirDrive: [4]u16, }; pub const WTS_VIRTUAL_CLASS = enum(i32) { ClientData = 0, FileHandle = 1, }; pub const WTSVirtualClientData = WTS_VIRTUAL_CLASS.ClientData; pub const WTSVirtualFileHandle = WTS_VIRTUAL_CLASS.FileHandle; pub const WTS_SESSION_ADDRESS = extern struct { AddressFamily: u32, Address: [20]u8, }; pub const WTS_PROCESS_INFO_EXW = extern struct { SessionId: u32, ProcessId: u32, pProcessName: ?PWSTR, pUserSid: ?PSID, NumberOfThreads: u32, HandleCount: u32, PagefileUsage: u32, PeakPagefileUsage: u32, WorkingSetSize: u32, PeakWorkingSetSize: u32, UserTime: LARGE_INTEGER, KernelTime: LARGE_INTEGER, }; pub const WTS_PROCESS_INFO_EXA = extern struct { SessionId: u32, ProcessId: u32, pProcessName: ?PSTR, pUserSid: ?PSID, NumberOfThreads: u32, HandleCount: u32, PagefileUsage: u32, PeakPagefileUsage: u32, WorkingSetSize: u32, PeakWorkingSetSize: u32, UserTime: LARGE_INTEGER, KernelTime: LARGE_INTEGER, }; pub const WTS_TYPE_CLASS = enum(i32) { ProcessInfoLevel0 = 0, ProcessInfoLevel1 = 1, SessionInfoLevel1 = 2, }; pub const WTSTypeProcessInfoLevel0 = WTS_TYPE_CLASS.ProcessInfoLevel0; pub const WTSTypeProcessInfoLevel1 = WTS_TYPE_CLASS.ProcessInfoLevel1; pub const WTSTypeSessionInfoLevel1 = WTS_TYPE_CLASS.SessionInfoLevel1; pub const WTSLISTENERCONFIGW = extern struct { version: u32, fEnableListener: u32, MaxConnectionCount: u32, fPromptForPassword: u32, fInheritColorDepth: u32, ColorDepth: u32, fInheritBrokenTimeoutSettings: u32, BrokenTimeoutSettings: u32, fDisablePrinterRedirection: u32, fDisableDriveRedirection: u32, fDisableComPortRedirection: u32, fDisableLPTPortRedirection: u32, fDisableClipboardRedirection: u32, fDisableAudioRedirection: u32, fDisablePNPRedirection: u32, fDisableDefaultMainClientPrinter: u32, LanAdapter: u32, PortNumber: u32, fInheritShadowSettings: u32, ShadowSettings: u32, TimeoutSettingsConnection: u32, TimeoutSettingsDisconnection: u32, TimeoutSettingsIdle: u32, SecurityLayer: u32, MinEncryptionLevel: u32, UserAuthentication: u32, Comment: [61]u16, LogonUserName: [21]u16, LogonDomain: [18]u16, WorkDirectory: [261]u16, InitialProgram: [261]u16, }; pub const WTSLISTENERCONFIGA = extern struct { version: u32, fEnableListener: u32, MaxConnectionCount: u32, fPromptForPassword: u32, fInheritColorDepth: u32, ColorDepth: u32, fInheritBrokenTimeoutSettings: u32, BrokenTimeoutSettings: u32, fDisablePrinterRedirection: u32, fDisableDriveRedirection: u32, fDisableComPortRedirection: u32, fDisableLPTPortRedirection: u32, fDisableClipboardRedirection: u32, fDisableAudioRedirection: u32, fDisablePNPRedirection: u32, fDisableDefaultMainClientPrinter: u32, LanAdapter: u32, PortNumber: u32, fInheritShadowSettings: u32, ShadowSettings: u32, TimeoutSettingsConnection: u32, TimeoutSettingsDisconnection: u32, TimeoutSettingsIdle: u32, SecurityLayer: u32, MinEncryptionLevel: u32, UserAuthentication: u32, Comment: [61]CHAR, LogonUserName: [21]CHAR, LogonDomain: [18]CHAR, WorkDirectory: [261]CHAR, InitialProgram: [261]CHAR, }; pub const WTSSBX_MACHINE_DRAIN = enum(i32) { UNSPEC = 0, OFF = 1, ON = 2, }; pub const WTSSBX_MACHINE_DRAIN_UNSPEC = WTSSBX_MACHINE_DRAIN.UNSPEC; pub const WTSSBX_MACHINE_DRAIN_OFF = WTSSBX_MACHINE_DRAIN.OFF; pub const WTSSBX_MACHINE_DRAIN_ON = WTSSBX_MACHINE_DRAIN.ON; pub const WTSSBX_MACHINE_SESSION_MODE = enum(i32) { UNSPEC = 0, SINGLE = 1, MULTIPLE = 2, }; pub const WTSSBX_MACHINE_SESSION_MODE_UNSPEC = WTSSBX_MACHINE_SESSION_MODE.UNSPEC; pub const WTSSBX_MACHINE_SESSION_MODE_SINGLE = WTSSBX_MACHINE_SESSION_MODE.SINGLE; pub const WTSSBX_MACHINE_SESSION_MODE_MULTIPLE = WTSSBX_MACHINE_SESSION_MODE.MULTIPLE; pub const WTSSBX_ADDRESS_FAMILY = enum(i32) { UNSPEC = 0, INET = 1, INET6 = 2, IPX = 3, NETBIOS = 4, }; pub const WTSSBX_ADDRESS_FAMILY_AF_UNSPEC = WTSSBX_ADDRESS_FAMILY.UNSPEC; pub const WTSSBX_ADDRESS_FAMILY_AF_INET = WTSSBX_ADDRESS_FAMILY.INET; pub const WTSSBX_ADDRESS_FAMILY_AF_INET6 = WTSSBX_ADDRESS_FAMILY.INET6; pub const WTSSBX_ADDRESS_FAMILY_AF_IPX = WTSSBX_ADDRESS_FAMILY.IPX; pub const WTSSBX_ADDRESS_FAMILY_AF_NETBIOS = WTSSBX_ADDRESS_FAMILY.NETBIOS; pub const WTSSBX_IP_ADDRESS = extern struct { AddressFamily: WTSSBX_ADDRESS_FAMILY, Address: [16]u8, PortNumber: u16, dwScope: u32, }; pub const WTSSBX_MACHINE_STATE = enum(i32) { UNSPEC = 0, READY = 1, SYNCHRONIZING = 2, }; pub const WTSSBX_MACHINE_STATE_UNSPEC = WTSSBX_MACHINE_STATE.UNSPEC; pub const WTSSBX_MACHINE_STATE_READY = WTSSBX_MACHINE_STATE.READY; pub const WTSSBX_MACHINE_STATE_SYNCHRONIZING = WTSSBX_MACHINE_STATE.SYNCHRONIZING; pub const WTSSBX_MACHINE_CONNECT_INFO = extern struct { wczMachineFQDN: [257]u16, wczMachineNetBiosName: [17]u16, dwNumOfIPAddr: u32, IPaddr: [12]WTSSBX_IP_ADDRESS, }; pub const WTSSBX_MACHINE_INFO = extern struct { ClientConnectInfo: WTSSBX_MACHINE_CONNECT_INFO, wczFarmName: [257]u16, InternalIPAddress: WTSSBX_IP_ADDRESS, dwMaxSessionsLimit: u32, ServerWeight: u32, SingleSessionMode: WTSSBX_MACHINE_SESSION_MODE, InDrain: WTSSBX_MACHINE_DRAIN, MachineState: WTSSBX_MACHINE_STATE, }; pub const WTSSBX_SESSION_STATE = enum(i32) { UNSPEC = 0, ACTIVE = 1, DISCONNECTED = 2, }; pub const WTSSBX_SESSION_STATE_UNSPEC = WTSSBX_SESSION_STATE.UNSPEC; pub const WTSSBX_SESSION_STATE_ACTIVE = WTSSBX_SESSION_STATE.ACTIVE; pub const WTSSBX_SESSION_STATE_DISCONNECTED = WTSSBX_SESSION_STATE.DISCONNECTED; pub const WTSSBX_SESSION_INFO = extern struct { wszUserName: [105]u16, wszDomainName: [257]u16, ApplicationType: [257]u16, dwSessionId: u32, CreateTime: FILETIME, DisconnectTime: FILETIME, SessionState: WTSSBX_SESSION_STATE, }; pub const WTSSBX_NOTIFICATION_TYPE = enum(i32) { REMOVED = 1, CHANGED = 2, ADDED = 4, RESYNC = 8, }; pub const WTSSBX_NOTIFICATION_REMOVED = WTSSBX_NOTIFICATION_TYPE.REMOVED; pub const WTSSBX_NOTIFICATION_CHANGED = WTSSBX_NOTIFICATION_TYPE.CHANGED; pub const WTSSBX_NOTIFICATION_ADDED = WTSSBX_NOTIFICATION_TYPE.ADDED; pub const WTSSBX_NOTIFICATION_RESYNC = WTSSBX_NOTIFICATION_TYPE.RESYNC; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSSBPlugin_Value = Guid.initString("dc44be78-b18d-4399-b210-641bf67a002c"); pub const IID_IWTSSBPlugin = &IID_IWTSSBPlugin_Value; pub const IWTSSBPlugin = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWTSSBPlugin, PluginCapabilities: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WTSSBX_MachineChangeNotification: fn( self: *const IWTSSBPlugin, NotificationType: WTSSBX_NOTIFICATION_TYPE, MachineId: i32, pMachineInfo: ?*WTSSBX_MACHINE_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WTSSBX_SessionChangeNotification: fn( self: *const IWTSSBPlugin, NotificationType: WTSSBX_NOTIFICATION_TYPE, MachineId: i32, NumOfSessions: u32, SessionInfo: [*]WTSSBX_SESSION_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WTSSBX_GetMostSuitableServer: fn( self: *const IWTSSBPlugin, UserName: ?PWSTR, DomainName: ?PWSTR, ApplicationType: ?PWSTR, FarmName: ?PWSTR, pMachineId: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Terminated: fn( self: *const IWTSSBPlugin, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WTSSBX_GetUserExternalSession: fn( self: *const IWTSSBPlugin, UserName: ?PWSTR, DomainName: ?PWSTR, ApplicationType: ?PWSTR, RedirectorInternalIP: ?*WTSSBX_IP_ADDRESS, pSessionId: ?*u32, pMachineConnectInfo: ?*WTSSBX_MACHINE_CONNECT_INFO, ) 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 IWTSSBPlugin_Initialize(self: *const T, PluginCapabilities: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSSBPlugin.VTable, self.vtable).Initialize(@ptrCast(*const IWTSSBPlugin, self), PluginCapabilities); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSSBPlugin_WTSSBX_MachineChangeNotification(self: *const T, NotificationType: WTSSBX_NOTIFICATION_TYPE, MachineId: i32, pMachineInfo: ?*WTSSBX_MACHINE_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSSBPlugin.VTable, self.vtable).WTSSBX_MachineChangeNotification(@ptrCast(*const IWTSSBPlugin, self), NotificationType, MachineId, pMachineInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSSBPlugin_WTSSBX_SessionChangeNotification(self: *const T, NotificationType: WTSSBX_NOTIFICATION_TYPE, MachineId: i32, NumOfSessions: u32, SessionInfo: [*]WTSSBX_SESSION_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSSBPlugin.VTable, self.vtable).WTSSBX_SessionChangeNotification(@ptrCast(*const IWTSSBPlugin, self), NotificationType, MachineId, NumOfSessions, SessionInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSSBPlugin_WTSSBX_GetMostSuitableServer(self: *const T, UserName: ?PWSTR, DomainName: ?PWSTR, ApplicationType: ?PWSTR, FarmName: ?PWSTR, pMachineId: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSSBPlugin.VTable, self.vtable).WTSSBX_GetMostSuitableServer(@ptrCast(*const IWTSSBPlugin, self), UserName, DomainName, ApplicationType, FarmName, pMachineId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSSBPlugin_Terminated(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSSBPlugin.VTable, self.vtable).Terminated(@ptrCast(*const IWTSSBPlugin, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSSBPlugin_WTSSBX_GetUserExternalSession(self: *const T, UserName: ?PWSTR, DomainName: ?PWSTR, ApplicationType: ?PWSTR, RedirectorInternalIP: ?*WTSSBX_IP_ADDRESS, pSessionId: ?*u32, pMachineConnectInfo: ?*WTSSBX_MACHINE_CONNECT_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSSBPlugin.VTable, self.vtable).WTSSBX_GetUserExternalSession(@ptrCast(*const IWTSSBPlugin, self), UserName, DomainName, ApplicationType, RedirectorInternalIP, pSessionId, pMachineConnectInfo); } };} pub usingnamespace MethodMixin(@This()); }; pub const CHANNEL_DEF = packed struct { name: [8]CHAR, options: u32, }; pub const CHANNEL_PDU_HEADER = extern struct { length: u32, flags: u32, }; pub const PCHANNEL_INIT_EVENT_FN = fn( pInitHandle: ?*anyopaque, event: u32, pData: ?*anyopaque, dataLength: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const PCHANNEL_OPEN_EVENT_FN = fn( openHandle: u32, event: u32, pData: ?*anyopaque, dataLength: u32, totalLength: u32, dataFlags: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const PVIRTUALCHANNELINIT = fn( ppInitHandle: ?*?*anyopaque, pChannel: ?*CHANNEL_DEF, channelCount: i32, versionRequested: u32, pChannelInitEventProc: ?PCHANNEL_INIT_EVENT_FN, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PVIRTUALCHANNELOPEN = fn( pInitHandle: ?*anyopaque, pOpenHandle: ?*u32, pChannelName: ?[*]u8, pChannelOpenEventProc: ?PCHANNEL_OPEN_EVENT_FN, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PVIRTUALCHANNELCLOSE = fn( openHandle: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PVIRTUALCHANNELWRITE = fn( openHandle: u32, pData: ?*anyopaque, dataLength: u32, pUserData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const CHANNEL_ENTRY_POINTS = extern struct { cbSize: u32, protocolVersion: u32, pVirtualChannelInit: ?PVIRTUALCHANNELINIT, pVirtualChannelOpen: ?PVIRTUALCHANNELOPEN, pVirtualChannelClose: ?PVIRTUALCHANNELCLOSE, pVirtualChannelWrite: ?PVIRTUALCHANNELWRITE, }; pub const PVIRTUALCHANNELENTRY = fn( pEntryPoints: ?*CHANNEL_ENTRY_POINTS, ) callconv(@import("std").os.windows.WINAPI) BOOL; const CLSID_Workspace_Value = Guid.initString("4f1dfca6-3aad-48e1-8406-4bc21a501d7c"); pub const CLSID_Workspace = &CLSID_Workspace_Value; // TODO: this type is limited to platform 'windows6.1' const IID_IWorkspaceClientExt_Value = Guid.initString("12b952f4-41ca-4f21-a829-a6d07d9a16e5"); pub const IID_IWorkspaceClientExt = &IID_IWorkspaceClientExt_Value; pub const IWorkspaceClientExt = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetResourceId: fn( self: *const IWorkspaceClientExt, bstrWorkspaceId: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetResourceDisplayName: fn( self: *const IWorkspaceClientExt, bstrWorkspaceDisplayName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IssueDisconnect: fn( self: *const IWorkspaceClientExt, ) 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 IWorkspaceClientExt_GetResourceId(self: *const T, bstrWorkspaceId: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceClientExt.VTable, self.vtable).GetResourceId(@ptrCast(*const IWorkspaceClientExt, self), bstrWorkspaceId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceClientExt_GetResourceDisplayName(self: *const T, bstrWorkspaceDisplayName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceClientExt.VTable, self.vtable).GetResourceDisplayName(@ptrCast(*const IWorkspaceClientExt, self), bstrWorkspaceDisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceClientExt_IssueDisconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceClientExt.VTable, self.vtable).IssueDisconnect(@ptrCast(*const IWorkspaceClientExt, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWorkspace_Value = Guid.initString("b922bbb8-4c55-4fea-8496-beb0b44285e5"); pub const IID_IWorkspace = &IID_IWorkspace_Value; pub const IWorkspace = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetWorkspaceNames: fn( self: *const IWorkspace, psaWkspNames: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StartRemoteApplication: fn( self: *const IWorkspace, bstrWorkspaceId: ?BSTR, psaParams: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProcessId: fn( self: *const IWorkspace, pulProcessId: ?*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 IWorkspace_GetWorkspaceNames(self: *const T, psaWkspNames: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspace.VTable, self.vtable).GetWorkspaceNames(@ptrCast(*const IWorkspace, self), psaWkspNames); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspace_StartRemoteApplication(self: *const T, bstrWorkspaceId: ?BSTR, psaParams: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspace.VTable, self.vtable).StartRemoteApplication(@ptrCast(*const IWorkspace, self), bstrWorkspaceId, psaParams); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspace_GetProcessId(self: *const T, pulProcessId: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspace.VTable, self.vtable).GetProcessId(@ptrCast(*const IWorkspace, self), pulProcessId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWorkspace2_Value = Guid.initString("96d8d7cf-783e-4286-834c-ebc0e95f783c"); pub const IID_IWorkspace2 = &IID_IWorkspace2_Value; pub const IWorkspace2 = extern struct { pub const VTable = extern struct { base: IWorkspace.VTable, StartRemoteApplicationEx: fn( self: *const IWorkspace2, bstrWorkspaceId: ?BSTR, bstrRequestingAppId: ?BSTR, bstrRequestingAppFamilyName: ?BSTR, bLaunchIntoImmersiveClient: i16, bstrImmersiveClientActivationContext: ?BSTR, psaParams: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWorkspace.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspace2_StartRemoteApplicationEx(self: *const T, bstrWorkspaceId: ?BSTR, bstrRequestingAppId: ?BSTR, bstrRequestingAppFamilyName: ?BSTR, bLaunchIntoImmersiveClient: i16, bstrImmersiveClientActivationContext: ?BSTR, psaParams: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspace2.VTable, self.vtable).StartRemoteApplicationEx(@ptrCast(*const IWorkspace2, self), bstrWorkspaceId, bstrRequestingAppId, bstrRequestingAppFamilyName, bLaunchIntoImmersiveClient, bstrImmersiveClientActivationContext, psaParams); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows10.0.10240' const IID_IWorkspace3_Value = Guid.initString("1becbe4a-d654-423b-afeb-be8d532c13c6"); pub const IID_IWorkspace3 = &IID_IWorkspace3_Value; pub const IWorkspace3 = extern struct { pub const VTable = extern struct { base: IWorkspace2.VTable, GetClaimsToken2: fn( self: *const IWorkspace3, bstrClaimsHint: ?BSTR, bstrUserHint: ?BSTR, claimCookie: u32, hwndCredUiParent: u32, rectCredUiParent: RECT, pbstrAccessToken: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetClaimsToken: fn( self: *const IWorkspace3, bstrAccessToken: ?BSTR, ullAccessTokenExpiration: u64, bstrRefreshToken: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWorkspace2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspace3_GetClaimsToken2(self: *const T, bstrClaimsHint: ?BSTR, bstrUserHint: ?BSTR, claimCookie: u32, hwndCredUiParent: u32, rectCredUiParent: RECT, pbstrAccessToken: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspace3.VTable, self.vtable).GetClaimsToken2(@ptrCast(*const IWorkspace3, self), bstrClaimsHint, bstrUserHint, claimCookie, hwndCredUiParent, rectCredUiParent, pbstrAccessToken); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspace3_SetClaimsToken(self: *const T, bstrAccessToken: ?BSTR, ullAccessTokenExpiration: u64, bstrRefreshToken: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspace3.VTable, self.vtable).SetClaimsToken(@ptrCast(*const IWorkspace3, self), bstrAccessToken, ullAccessTokenExpiration, bstrRefreshToken); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWorkspaceRegistration_Value = Guid.initString("b922bbb8-4c55-4fea-8496-beb0b44285e6"); pub const IID_IWorkspaceRegistration = &IID_IWorkspaceRegistration_Value; pub const IWorkspaceRegistration = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddResource: fn( self: *const IWorkspaceRegistration, pUnk: ?*IWorkspaceClientExt, pdwCookie: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveResource: fn( self: *const IWorkspaceRegistration, dwCookieConnection: 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 IWorkspaceRegistration_AddResource(self: *const T, pUnk: ?*IWorkspaceClientExt, pdwCookie: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceRegistration.VTable, self.vtable).AddResource(@ptrCast(*const IWorkspaceRegistration, self), pUnk, pdwCookie); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceRegistration_RemoveResource(self: *const T, dwCookieConnection: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceRegistration.VTable, self.vtable).RemoveResource(@ptrCast(*const IWorkspaceRegistration, self), dwCookieConnection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IWorkspaceRegistration2_Value = Guid.initString("cf59f654-39bb-44d8-94d0-4635728957e9"); pub const IID_IWorkspaceRegistration2 = &IID_IWorkspaceRegistration2_Value; pub const IWorkspaceRegistration2 = extern struct { pub const VTable = extern struct { base: IWorkspaceRegistration.VTable, AddResourceEx: fn( self: *const IWorkspaceRegistration2, pUnk: ?*IWorkspaceClientExt, bstrEventLogUploadAddress: ?BSTR, pdwCookie: ?*u32, correlationId: Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveResourceEx: fn( self: *const IWorkspaceRegistration2, dwCookieConnection: u32, correlationId: Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWorkspaceRegistration.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceRegistration2_AddResourceEx(self: *const T, pUnk: ?*IWorkspaceClientExt, bstrEventLogUploadAddress: ?BSTR, pdwCookie: ?*u32, correlationId: Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceRegistration2.VTable, self.vtable).AddResourceEx(@ptrCast(*const IWorkspaceRegistration2, self), pUnk, bstrEventLogUploadAddress, pdwCookie, correlationId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceRegistration2_RemoveResourceEx(self: *const T, dwCookieConnection: u32, correlationId: Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceRegistration2.VTable, self.vtable).RemoveResourceEx(@ptrCast(*const IWorkspaceRegistration2, self), dwCookieConnection, correlationId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWorkspaceScriptable_Value = Guid.initString("efea49a2-dda5-429d-8f42-b23b92c4c347"); pub const IID_IWorkspaceScriptable = &IID_IWorkspaceScriptable_Value; pub const IWorkspaceScriptable = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, DisconnectWorkspace: fn( self: *const IWorkspaceScriptable, bstrWorkspaceId: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StartWorkspace: fn( self: *const IWorkspaceScriptable, bstrWorkspaceId: ?BSTR, bstrUserName: ?BSTR, bstrPassword: ?BSTR, bstrWorkspaceParams: ?BSTR, lTimeout: i32, lFlags: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsWorkspaceCredentialSpecified: fn( self: *const IWorkspaceScriptable, bstrWorkspaceId: ?BSTR, bCountUnauthenticatedCredentials: i16, pbCredExist: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsWorkspaceSSOEnabled: fn( self: *const IWorkspaceScriptable, pbSSOEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearWorkspaceCredential: fn( self: *const IWorkspaceScriptable, bstrWorkspaceId: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnAuthenticated: fn( self: *const IWorkspaceScriptable, bstrWorkspaceId: ?BSTR, bstrUserName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisconnectWorkspaceByFriendlyName: fn( self: *const IWorkspaceScriptable, bstrWorkspaceFriendlyName: ?BSTR, ) 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 IWorkspaceScriptable_DisconnectWorkspace(self: *const T, bstrWorkspaceId: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable.VTable, self.vtable).DisconnectWorkspace(@ptrCast(*const IWorkspaceScriptable, self), bstrWorkspaceId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable_StartWorkspace(self: *const T, bstrWorkspaceId: ?BSTR, bstrUserName: ?BSTR, bstrPassword: ?BSTR, bstrWorkspaceParams: ?BSTR, lTimeout: i32, lFlags: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable.VTable, self.vtable).StartWorkspace(@ptrCast(*const IWorkspaceScriptable, self), bstrWorkspaceId, bstrUserName, bstrPassword, bstrWorkspaceParams, lTimeout, lFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable_IsWorkspaceCredentialSpecified(self: *const T, bstrWorkspaceId: ?BSTR, bCountUnauthenticatedCredentials: i16, pbCredExist: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable.VTable, self.vtable).IsWorkspaceCredentialSpecified(@ptrCast(*const IWorkspaceScriptable, self), bstrWorkspaceId, bCountUnauthenticatedCredentials, pbCredExist); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable_IsWorkspaceSSOEnabled(self: *const T, pbSSOEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable.VTable, self.vtable).IsWorkspaceSSOEnabled(@ptrCast(*const IWorkspaceScriptable, self), pbSSOEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable_ClearWorkspaceCredential(self: *const T, bstrWorkspaceId: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable.VTable, self.vtable).ClearWorkspaceCredential(@ptrCast(*const IWorkspaceScriptable, self), bstrWorkspaceId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable_OnAuthenticated(self: *const T, bstrWorkspaceId: ?BSTR, bstrUserName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable.VTable, self.vtable).OnAuthenticated(@ptrCast(*const IWorkspaceScriptable, self), bstrWorkspaceId, bstrUserName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable_DisconnectWorkspaceByFriendlyName(self: *const T, bstrWorkspaceFriendlyName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable.VTable, self.vtable).DisconnectWorkspaceByFriendlyName(@ptrCast(*const IWorkspaceScriptable, self), bstrWorkspaceFriendlyName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWorkspaceScriptable2_Value = Guid.initString("efea49a2-dda5-429d-8f42-b33ba2c4c348"); pub const IID_IWorkspaceScriptable2 = &IID_IWorkspaceScriptable2_Value; pub const IWorkspaceScriptable2 = extern struct { pub const VTable = extern struct { base: IWorkspaceScriptable.VTable, StartWorkspaceEx: fn( self: *const IWorkspaceScriptable2, bstrWorkspaceId: ?BSTR, bstrWorkspaceFriendlyName: ?BSTR, bstrRedirectorName: ?BSTR, bstrUserName: ?BSTR, bstrPassword: ?BSTR, bstrAppContainer: ?BSTR, bstrWorkspaceParams: ?BSTR, lTimeout: i32, lFlags: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResourceDismissed: fn( self: *const IWorkspaceScriptable2, bstrWorkspaceId: ?BSTR, bstrWorkspaceFriendlyName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWorkspaceScriptable.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable2_StartWorkspaceEx(self: *const T, bstrWorkspaceId: ?BSTR, bstrWorkspaceFriendlyName: ?BSTR, bstrRedirectorName: ?BSTR, bstrUserName: ?BSTR, bstrPassword: ?BSTR, bstrAppContainer: ?BSTR, bstrWorkspaceParams: ?BSTR, lTimeout: i32, lFlags: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable2.VTable, self.vtable).StartWorkspaceEx(@ptrCast(*const IWorkspaceScriptable2, self), bstrWorkspaceId, bstrWorkspaceFriendlyName, bstrRedirectorName, bstrUserName, bstrPassword, bstrAppContainer, bstrWorkspaceParams, lTimeout, lFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable2_ResourceDismissed(self: *const T, bstrWorkspaceId: ?BSTR, bstrWorkspaceFriendlyName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable2.VTable, self.vtable).ResourceDismissed(@ptrCast(*const IWorkspaceScriptable2, self), bstrWorkspaceId, bstrWorkspaceFriendlyName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.1' const IID_IWorkspaceScriptable3_Value = Guid.initString("531e6512-2cbf-4bd2-80a5-d90a71636a9a"); pub const IID_IWorkspaceScriptable3 = &IID_IWorkspaceScriptable3_Value; pub const IWorkspaceScriptable3 = extern struct { pub const VTable = extern struct { base: IWorkspaceScriptable2.VTable, StartWorkspaceEx2: fn( self: *const IWorkspaceScriptable3, bstrWorkspaceId: ?BSTR, bstrWorkspaceFriendlyName: ?BSTR, bstrRedirectorName: ?BSTR, bstrUserName: ?BSTR, bstrPassword: ?BSTR, bstrAppContainer: ?BSTR, bstrWorkspaceParams: ?BSTR, lTimeout: i32, lFlags: i32, bstrEventLogUploadAddress: ?BSTR, correlationId: Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IWorkspaceScriptable2.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceScriptable3_StartWorkspaceEx2(self: *const T, bstrWorkspaceId: ?BSTR, bstrWorkspaceFriendlyName: ?BSTR, bstrRedirectorName: ?BSTR, bstrUserName: ?BSTR, bstrPassword: ?BSTR, bstrAppContainer: ?BSTR, bstrWorkspaceParams: ?BSTR, lTimeout: i32, lFlags: i32, bstrEventLogUploadAddress: ?BSTR, correlationId: Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceScriptable3.VTable, self.vtable).StartWorkspaceEx2(@ptrCast(*const IWorkspaceScriptable3, self), bstrWorkspaceId, bstrWorkspaceFriendlyName, bstrRedirectorName, bstrUserName, bstrPassword, bstrAppContainer, bstrWorkspaceParams, lTimeout, lFlags, bstrEventLogUploadAddress, correlationId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWorkspaceReportMessage_Value = Guid.initString("a7c06739-500f-4e8c-99a8-2bd6955899eb"); pub const IID_IWorkspaceReportMessage = &IID_IWorkspaceReportMessage_Value; pub const IWorkspaceReportMessage = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RegisterErrorLogMessage: fn( self: *const IWorkspaceReportMessage, bstrMessage: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsErrorMessageRegistered: fn( self: *const IWorkspaceReportMessage, bstrWkspId: ?BSTR, dwErrorType: u32, bstrErrorMessageType: ?BSTR, dwErrorCode: u32, pfErrorExist: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterErrorEvent: fn( self: *const IWorkspaceReportMessage, bstrWkspId: ?BSTR, dwErrorType: u32, bstrErrorMessageType: ?BSTR, dwErrorCode: 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 IWorkspaceReportMessage_RegisterErrorLogMessage(self: *const T, bstrMessage: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceReportMessage.VTable, self.vtable).RegisterErrorLogMessage(@ptrCast(*const IWorkspaceReportMessage, self), bstrMessage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceReportMessage_IsErrorMessageRegistered(self: *const T, bstrWkspId: ?BSTR, dwErrorType: u32, bstrErrorMessageType: ?BSTR, dwErrorCode: u32, pfErrorExist: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceReportMessage.VTable, self.vtable).IsErrorMessageRegistered(@ptrCast(*const IWorkspaceReportMessage, self), bstrWkspId, dwErrorType, bstrErrorMessageType, dwErrorCode, pfErrorExist); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceReportMessage_RegisterErrorEvent(self: *const T, bstrWkspId: ?BSTR, dwErrorType: u32, bstrErrorMessageType: ?BSTR, dwErrorCode: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceReportMessage.VTable, self.vtable).RegisterErrorEvent(@ptrCast(*const IWorkspaceReportMessage, self), bstrWkspId, dwErrorType, bstrErrorMessageType, dwErrorCode); } };} pub usingnamespace MethodMixin(@This()); }; const IID__ITSWkspEvents_Value = Guid.initString("b922bbb8-4c55-4fea-8496-beb0b44285e9"); pub const IID__ITSWkspEvents = &IID__ITSWkspEvents_Value; pub const _ITSWkspEvents = 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()); }; pub const TSSD_AddrV46Type = enum(i32) { UNDEFINED = 0, IPv4 = 4, IPv6 = 6, }; pub const TSSD_ADDR_UNDEFINED = TSSD_AddrV46Type.UNDEFINED; pub const TSSD_ADDR_IPv4 = TSSD_AddrV46Type.IPv4; pub const TSSD_ADDR_IPv6 = TSSD_AddrV46Type.IPv6; pub const TSSB_NOTIFICATION_TYPE = enum(i32) { INVALID = 0, TARGET_CHANGE = 1, SESSION_CHANGE = 2, CONNECTION_REQUEST_CHANGE = 4, }; pub const TSSB_NOTIFY_INVALID = TSSB_NOTIFICATION_TYPE.INVALID; pub const TSSB_NOTIFY_TARGET_CHANGE = TSSB_NOTIFICATION_TYPE.TARGET_CHANGE; pub const TSSB_NOTIFY_SESSION_CHANGE = TSSB_NOTIFICATION_TYPE.SESSION_CHANGE; pub const TSSB_NOTIFY_CONNECTION_REQUEST_CHANGE = TSSB_NOTIFICATION_TYPE.CONNECTION_REQUEST_CHANGE; pub const TARGET_STATE = enum(i32) { UNKNOWN = 1, INITIALIZING = 2, RUNNING = 3, DOWN = 4, HIBERNATED = 5, CHECKED_OUT = 6, STOPPED = 7, INVALID = 8, STARTING = 9, STOPPING = 10, MAXSTATE = 11, }; pub const TARGET_UNKNOWN = TARGET_STATE.UNKNOWN; pub const TARGET_INITIALIZING = TARGET_STATE.INITIALIZING; pub const TARGET_RUNNING = TARGET_STATE.RUNNING; pub const TARGET_DOWN = TARGET_STATE.DOWN; pub const TARGET_HIBERNATED = TARGET_STATE.HIBERNATED; pub const TARGET_CHECKED_OUT = TARGET_STATE.CHECKED_OUT; pub const TARGET_STOPPED = TARGET_STATE.STOPPED; pub const TARGET_INVALID = TARGET_STATE.INVALID; pub const TARGET_STARTING = TARGET_STATE.STARTING; pub const TARGET_STOPPING = TARGET_STATE.STOPPING; pub const TARGET_MAXSTATE = TARGET_STATE.MAXSTATE; pub const TARGET_CHANGE_TYPE = enum(i32) { CHANGE_UNSPEC = 1, EXTERNALIP_CHANGED = 2, INTERNALIP_CHANGED = 4, JOINED = 8, REMOVED = 16, STATE_CHANGED = 32, IDLE = 64, PENDING = 128, INUSE = 256, PATCH_STATE_CHANGED = 512, FARM_MEMBERSHIP_CHANGED = 1024, }; pub const TARGET_CHANGE_UNSPEC = TARGET_CHANGE_TYPE.CHANGE_UNSPEC; pub const TARGET_EXTERNALIP_CHANGED = TARGET_CHANGE_TYPE.EXTERNALIP_CHANGED; pub const TARGET_INTERNALIP_CHANGED = TARGET_CHANGE_TYPE.INTERNALIP_CHANGED; pub const TARGET_JOINED = TARGET_CHANGE_TYPE.JOINED; pub const TARGET_REMOVED = TARGET_CHANGE_TYPE.REMOVED; pub const TARGET_STATE_CHANGED = TARGET_CHANGE_TYPE.STATE_CHANGED; pub const TARGET_IDLE = TARGET_CHANGE_TYPE.IDLE; pub const TARGET_PENDING = TARGET_CHANGE_TYPE.PENDING; pub const TARGET_INUSE = TARGET_CHANGE_TYPE.INUSE; pub const TARGET_PATCH_STATE_CHANGED = TARGET_CHANGE_TYPE.PATCH_STATE_CHANGED; pub const TARGET_FARM_MEMBERSHIP_CHANGED = TARGET_CHANGE_TYPE.FARM_MEMBERSHIP_CHANGED; pub const TARGET_TYPE = enum(i32) { UNKNOWN = 0, FARM = 1, NONFARM = 2, }; pub const UNKNOWN = TARGET_TYPE.UNKNOWN; pub const FARM = TARGET_TYPE.FARM; pub const NONFARM = TARGET_TYPE.NONFARM; pub const TARGET_PATCH_STATE = enum(i32) { UNKNOWN = 0, NOT_STARTED = 1, IN_PROGRESS = 2, COMPLETED = 3, FAILED = 4, }; pub const TARGET_PATCH_UNKNOWN = TARGET_PATCH_STATE.UNKNOWN; pub const TARGET_PATCH_NOT_STARTED = TARGET_PATCH_STATE.NOT_STARTED; pub const TARGET_PATCH_IN_PROGRESS = TARGET_PATCH_STATE.IN_PROGRESS; pub const TARGET_PATCH_COMPLETED = TARGET_PATCH_STATE.COMPLETED; pub const TARGET_PATCH_FAILED = TARGET_PATCH_STATE.FAILED; pub const CLIENT_MESSAGE_TYPE = enum(i32) { INVALID = 0, STATUS = 1, ERROR = 2, }; pub const CLIENT_MESSAGE_CONNECTION_INVALID = CLIENT_MESSAGE_TYPE.INVALID; pub const CLIENT_MESSAGE_CONNECTION_STATUS = CLIENT_MESSAGE_TYPE.STATUS; pub const CLIENT_MESSAGE_CONNECTION_ERROR = CLIENT_MESSAGE_TYPE.ERROR; pub const CONNECTION_CHANGE_NOTIFICATION = enum(i32) { INVALID = 0, PENDING = 1, FAILED = 2, TIMEDOUT = 3, SUCCEEDED = 4, CANCELLED = 5, LB_COMPLETED = 6, QUERY_PL_COMPLETED = 7, ORCH_COMPLETED = 8, }; pub const CONNECTION_REQUEST_INVALID = CONNECTION_CHANGE_NOTIFICATION.INVALID; pub const CONNECTION_REQUEST_PENDING = CONNECTION_CHANGE_NOTIFICATION.PENDING; pub const CONNECTION_REQUEST_FAILED = CONNECTION_CHANGE_NOTIFICATION.FAILED; pub const CONNECTION_REQUEST_TIMEDOUT = CONNECTION_CHANGE_NOTIFICATION.TIMEDOUT; pub const CONNECTION_REQUEST_SUCCEEDED = CONNECTION_CHANGE_NOTIFICATION.SUCCEEDED; pub const CONNECTION_REQUEST_CANCELLED = CONNECTION_CHANGE_NOTIFICATION.CANCELLED; pub const CONNECTION_REQUEST_LB_COMPLETED = CONNECTION_CHANGE_NOTIFICATION.LB_COMPLETED; pub const CONNECTION_REQUEST_QUERY_PL_COMPLETED = CONNECTION_CHANGE_NOTIFICATION.QUERY_PL_COMPLETED; pub const CONNECTION_REQUEST_ORCH_COMPLETED = CONNECTION_CHANGE_NOTIFICATION.ORCH_COMPLETED; pub const RD_FARM_TYPE = enum(i32) { RDSH = 0, TEMP_VM = 1, MANUAL_PERSONAL_VM = 2, AUTO_PERSONAL_VM = 3, MANUAL_PERSONAL_RDSH = 4, AUTO_PERSONAL_RDSH = 5, TYPE_UNKNOWN = -1, }; pub const RD_FARM_RDSH = RD_FARM_TYPE.RDSH; pub const RD_FARM_TEMP_VM = RD_FARM_TYPE.TEMP_VM; pub const RD_FARM_MANUAL_PERSONAL_VM = RD_FARM_TYPE.MANUAL_PERSONAL_VM; pub const RD_FARM_AUTO_PERSONAL_VM = RD_FARM_TYPE.AUTO_PERSONAL_VM; pub const RD_FARM_MANUAL_PERSONAL_RDSH = RD_FARM_TYPE.MANUAL_PERSONAL_RDSH; pub const RD_FARM_AUTO_PERSONAL_RDSH = RD_FARM_TYPE.AUTO_PERSONAL_RDSH; pub const RD_FARM_TYPE_UNKNOWN = RD_FARM_TYPE.TYPE_UNKNOWN; pub const PLUGIN_TYPE = enum(i32) { UNKNOWN_PLUGIN = 0, POLICY_PLUGIN = 1, RESOURCE_PLUGIN = 2, LOAD_BALANCING_PLUGIN = 4, PLACEMENT_PLUGIN = 8, ORCHESTRATION_PLUGIN = 16, PROVISIONING_PLUGIN = 32, TASK_PLUGIN = 64, }; pub const UNKNOWN_PLUGIN = PLUGIN_TYPE.UNKNOWN_PLUGIN; pub const POLICY_PLUGIN = PLUGIN_TYPE.POLICY_PLUGIN; pub const RESOURCE_PLUGIN = PLUGIN_TYPE.RESOURCE_PLUGIN; pub const LOAD_BALANCING_PLUGIN = PLUGIN_TYPE.LOAD_BALANCING_PLUGIN; pub const PLACEMENT_PLUGIN = PLUGIN_TYPE.PLACEMENT_PLUGIN; pub const ORCHESTRATION_PLUGIN = PLUGIN_TYPE.ORCHESTRATION_PLUGIN; pub const PROVISIONING_PLUGIN = PLUGIN_TYPE.PROVISIONING_PLUGIN; pub const TASK_PLUGIN = PLUGIN_TYPE.TASK_PLUGIN; pub const TSSESSION_STATE = enum(i32) { INVALID = -1, ACTIVE = 0, CONNECTED = 1, CONNECTQUERY = 2, SHADOW = 3, DISCONNECTED = 4, IDLE = 5, LISTEN = 6, RESET = 7, DOWN = 8, INIT = 9, MAX = 10, }; pub const STATE_INVALID = TSSESSION_STATE.INVALID; pub const STATE_ACTIVE = TSSESSION_STATE.ACTIVE; pub const STATE_CONNECTED = TSSESSION_STATE.CONNECTED; pub const STATE_CONNECTQUERY = TSSESSION_STATE.CONNECTQUERY; pub const STATE_SHADOW = TSSESSION_STATE.SHADOW; pub const STATE_DISCONNECTED = TSSESSION_STATE.DISCONNECTED; pub const STATE_IDLE = TSSESSION_STATE.IDLE; pub const STATE_LISTEN = TSSESSION_STATE.LISTEN; pub const STATE_RESET = TSSESSION_STATE.RESET; pub const STATE_DOWN = TSSESSION_STATE.DOWN; pub const STATE_INIT = TSSESSION_STATE.INIT; pub const STATE_MAX = TSSESSION_STATE.MAX; pub const TARGET_OWNER = enum(i32) { UNKNOWN = 0, MS_TS_PLUGIN = 1, MS_VM_PLUGIN = 2, }; pub const OWNER_UNKNOWN = TARGET_OWNER.UNKNOWN; pub const OWNER_MS_TS_PLUGIN = TARGET_OWNER.MS_TS_PLUGIN; pub const OWNER_MS_VM_PLUGIN = TARGET_OWNER.MS_VM_PLUGIN; pub const CLIENT_DISPLAY = extern struct { HorizontalResolution: u32, VerticalResolution: u32, ColorDepth: u32, }; pub const TSSD_ConnectionPoint = extern struct { ServerAddressB: [16]u8, AddressType: TSSD_AddrV46Type, PortNumber: u16, AddressScope: u32, }; pub const VM_NOTIFY_STATUS = enum(i32) { PENDING = 0, IN_PROGRESS = 1, COMPLETE = 2, FAILED = 3, CANCELED = 4, }; pub const VM_NOTIFY_STATUS_PENDING = VM_NOTIFY_STATUS.PENDING; pub const VM_NOTIFY_STATUS_IN_PROGRESS = VM_NOTIFY_STATUS.IN_PROGRESS; pub const VM_NOTIFY_STATUS_COMPLETE = VM_NOTIFY_STATUS.COMPLETE; pub const VM_NOTIFY_STATUS_FAILED = VM_NOTIFY_STATUS.FAILED; pub const VM_NOTIFY_STATUS_CANCELED = VM_NOTIFY_STATUS.CANCELED; pub const VM_NOTIFY_ENTRY = extern struct { VmName: [128]u16, VmHost: [128]u16, }; pub const VM_PATCH_INFO = extern struct { dwNumEntries: u32, pVmNames: ?*?PWSTR, }; pub const VM_NOTIFY_INFO = extern struct { dwNumEntries: u32, ppVmEntries: ?*?*VM_NOTIFY_ENTRY, }; pub const VM_HOST_NOTIFY_STATUS = enum(i32) { PENDING = 0, IN_PROGRESS = 1, COMPLETE = 2, FAILED = 3, }; pub const VM_HOST_STATUS_INIT_PENDING = VM_HOST_NOTIFY_STATUS.PENDING; pub const VM_HOST_STATUS_INIT_IN_PROGRESS = VM_HOST_NOTIFY_STATUS.IN_PROGRESS; pub const VM_HOST_STATUS_INIT_COMPLETE = VM_HOST_NOTIFY_STATUS.COMPLETE; pub const VM_HOST_STATUS_INIT_FAILED = VM_HOST_NOTIFY_STATUS.FAILED; pub const RDV_TASK_STATUS = enum(i32) { UNKNOWN = 0, SEARCHING = 1, DOWNLOADING = 2, APPLYING = 3, REBOOTING = 4, REBOOTED = 5, SUCCESS = 6, FAILED = 7, TIMEOUT = 8, }; pub const RDV_TASK_STATUS_UNKNOWN = RDV_TASK_STATUS.UNKNOWN; pub const RDV_TASK_STATUS_SEARCHING = RDV_TASK_STATUS.SEARCHING; pub const RDV_TASK_STATUS_DOWNLOADING = RDV_TASK_STATUS.DOWNLOADING; pub const RDV_TASK_STATUS_APPLYING = RDV_TASK_STATUS.APPLYING; pub const RDV_TASK_STATUS_REBOOTING = RDV_TASK_STATUS.REBOOTING; pub const RDV_TASK_STATUS_REBOOTED = RDV_TASK_STATUS.REBOOTED; pub const RDV_TASK_STATUS_SUCCESS = RDV_TASK_STATUS.SUCCESS; pub const RDV_TASK_STATUS_FAILED = RDV_TASK_STATUS.FAILED; pub const RDV_TASK_STATUS_TIMEOUT = RDV_TASK_STATUS.TIMEOUT; pub const TS_SB_SORT_BY = enum(i32) { NONE = 0, NAME = 1, PROP = 2, }; pub const TS_SB_SORT_BY_NONE = TS_SB_SORT_BY.NONE; pub const TS_SB_SORT_BY_NAME = TS_SB_SORT_BY.NAME; pub const TS_SB_SORT_BY_PROP = TS_SB_SORT_BY.PROP; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbPlugin_Value = Guid.initString("48cd7406-caab-465f-a5d6-baa863b9ea4f"); pub const IID_ITsSbPlugin = &IID_ITsSbPlugin_Value; pub const ITsSbPlugin = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const ITsSbPlugin, pProvider: ?*ITsSbProvider, pNotifySink: ?*ITsSbPluginNotifySink, pPropertySet: ?*ITsSbPluginPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Terminate: fn( self: *const ITsSbPlugin, hr: HRESULT, ) 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 ITsSbPlugin_Initialize(self: *const T, pProvider: ?*ITsSbProvider, pNotifySink: ?*ITsSbPluginNotifySink, pPropertySet: ?*ITsSbPluginPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbPlugin.VTable, self.vtable).Initialize(@ptrCast(*const ITsSbPlugin, self), pProvider, pNotifySink, pPropertySet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbPlugin_Terminate(self: *const T, hr: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbPlugin.VTable, self.vtable).Terminate(@ptrCast(*const ITsSbPlugin, self), hr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbResourcePlugin_Value = Guid.initString("ea8db42c-98ed-4535-a88b-2a164f35490f"); pub const IID_ITsSbResourcePlugin = &IID_ITsSbResourcePlugin_Value; pub const ITsSbResourcePlugin = extern struct { pub const VTable = extern struct { base: ITsSbPlugin.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPlugin.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbServiceNotification_Value = Guid.initString("86cb68ae-86e0-4f57-8a64-bb7406bc5550"); pub const IID_ITsSbServiceNotification = &IID_ITsSbServiceNotification_Value; pub const ITsSbServiceNotification = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, NotifyServiceFailure: fn( self: *const ITsSbServiceNotification, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyServiceSuccess: fn( self: *const ITsSbServiceNotification, ) 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 ITsSbServiceNotification_NotifyServiceFailure(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbServiceNotification.VTable, self.vtable).NotifyServiceFailure(@ptrCast(*const ITsSbServiceNotification, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbServiceNotification_NotifyServiceSuccess(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbServiceNotification.VTable, self.vtable).NotifyServiceSuccess(@ptrCast(*const ITsSbServiceNotification, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbLoadBalancing_Value = Guid.initString("24329274-9eb7-11dc-ae98-f2b456d89593"); pub const IID_ITsSbLoadBalancing = &IID_ITsSbLoadBalancing_Value; pub const ITsSbLoadBalancing = extern struct { pub const VTable = extern struct { base: ITsSbPlugin.VTable, GetMostSuitableTarget: fn( self: *const ITsSbLoadBalancing, pConnection: ?*ITsSbClientConnection, pLBSink: ?*ITsSbLoadBalancingNotifySink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPlugin.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbLoadBalancing_GetMostSuitableTarget(self: *const T, pConnection: ?*ITsSbClientConnection, pLBSink: ?*ITsSbLoadBalancingNotifySink) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbLoadBalancing.VTable, self.vtable).GetMostSuitableTarget(@ptrCast(*const ITsSbLoadBalancing, self), pConnection, pLBSink); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbPlacement_Value = Guid.initString("daadee5f-6d32-480e-9e36-ddab2329f06d"); pub const IID_ITsSbPlacement = &IID_ITsSbPlacement_Value; pub const ITsSbPlacement = extern struct { pub const VTable = extern struct { base: ITsSbPlugin.VTable, QueryEnvironmentForTarget: fn( self: *const ITsSbPlacement, pConnection: ?*ITsSbClientConnection, pPlacementSink: ?*ITsSbPlacementNotifySink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPlugin.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbPlacement_QueryEnvironmentForTarget(self: *const T, pConnection: ?*ITsSbClientConnection, pPlacementSink: ?*ITsSbPlacementNotifySink) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbPlacement.VTable, self.vtable).QueryEnvironmentForTarget(@ptrCast(*const ITsSbPlacement, self), pConnection, pPlacementSink); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbOrchestration_Value = Guid.initString("64fc1172-9eb7-11dc-8b00-3aba56d89593"); pub const IID_ITsSbOrchestration = &IID_ITsSbOrchestration_Value; pub const ITsSbOrchestration = extern struct { pub const VTable = extern struct { base: ITsSbPlugin.VTable, PrepareTargetForConnect: fn( self: *const ITsSbOrchestration, pConnection: ?*ITsSbClientConnection, pOrchestrationNotifySink: ?*ITsSbOrchestrationNotifySink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPlugin.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbOrchestration_PrepareTargetForConnect(self: *const T, pConnection: ?*ITsSbClientConnection, pOrchestrationNotifySink: ?*ITsSbOrchestrationNotifySink) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbOrchestration.VTable, self.vtable).PrepareTargetForConnect(@ptrCast(*const ITsSbOrchestration, self), pConnection, pOrchestrationNotifySink); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbEnvironment_Value = Guid.initString("8c87f7f7-bf51-4a5c-87bf-8e94fb6e2256"); pub const IID_ITsSbEnvironment = &IID_ITsSbEnvironment_Value; pub const ITsSbEnvironment = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const ITsSbEnvironment, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ServerWeight: fn( self: *const ITsSbEnvironment, pVal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EnvironmentPropertySet: fn( self: *const ITsSbEnvironment, ppPropertySet: ?*?*ITsSbEnvironmentPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EnvironmentPropertySet: fn( self: *const ITsSbEnvironment, pVal: ?*ITsSbEnvironmentPropertySet, ) 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 ITsSbEnvironment_get_Name(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbEnvironment.VTable, self.vtable).get_Name(@ptrCast(*const ITsSbEnvironment, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbEnvironment_get_ServerWeight(self: *const T, pVal: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbEnvironment.VTable, self.vtable).get_ServerWeight(@ptrCast(*const ITsSbEnvironment, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbEnvironment_get_EnvironmentPropertySet(self: *const T, ppPropertySet: ?*?*ITsSbEnvironmentPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbEnvironment.VTable, self.vtable).get_EnvironmentPropertySet(@ptrCast(*const ITsSbEnvironment, self), ppPropertySet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbEnvironment_put_EnvironmentPropertySet(self: *const T, pVal: ?*ITsSbEnvironmentPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbEnvironment.VTable, self.vtable).put_EnvironmentPropertySet(@ptrCast(*const ITsSbEnvironment, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbLoadBalanceResult_Value = Guid.initString("24fdb7ac-fea6-11dc-9672-9a8956d89593"); pub const IID_ITsSbLoadBalanceResult = &IID_ITsSbLoadBalanceResult_Value; pub const ITsSbLoadBalanceResult = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetName: fn( self: *const ITsSbLoadBalanceResult, pVal: ?*?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 ITsSbLoadBalanceResult_get_TargetName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbLoadBalanceResult.VTable, self.vtable).get_TargetName(@ptrCast(*const ITsSbLoadBalanceResult, self), pVal); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbTarget_Value = Guid.initString("16616ecc-272d-411d-b324-126893033856"); pub const IID_ITsSbTarget = &IID_ITsSbTarget_Value; pub const ITsSbTarget = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetName: fn( self: *const ITsSbTarget, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TargetName: fn( self: *const ITsSbTarget, Val: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FarmName: fn( self: *const ITsSbTarget, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FarmName: fn( self: *const ITsSbTarget, Val: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetFQDN: fn( self: *const ITsSbTarget, TargetFqdnName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TargetFQDN: fn( self: *const ITsSbTarget, Val: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetNetbios: fn( self: *const ITsSbTarget, TargetNetbiosName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TargetNetbios: fn( self: *const ITsSbTarget, Val: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IpAddresses: fn( self: *const ITsSbTarget, SOCKADDR: [*]TSSD_ConnectionPoint, numAddresses: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_IpAddresses: fn( self: *const ITsSbTarget, SOCKADDR: [*]TSSD_ConnectionPoint, numAddresses: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetState: fn( self: *const ITsSbTarget, pState: ?*TARGET_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TargetState: fn( self: *const ITsSbTarget, State: TARGET_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetPropertySet: fn( self: *const ITsSbTarget, ppPropertySet: ?*?*ITsSbTargetPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TargetPropertySet: fn( self: *const ITsSbTarget, pVal: ?*ITsSbTargetPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EnvironmentName: fn( self: *const ITsSbTarget, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EnvironmentName: fn( self: *const ITsSbTarget, Val: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NumSessions: fn( self: *const ITsSbTarget, pNumSessions: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NumPendingConnections: fn( self: *const ITsSbTarget, pNumPendingConnections: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetLoad: fn( self: *const ITsSbTarget, pTargetLoad: ?*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 ITsSbTarget_get_TargetName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_TargetName(@ptrCast(*const ITsSbTarget, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_put_TargetName(self: *const T, Val: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).put_TargetName(@ptrCast(*const ITsSbTarget, self), Val); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_FarmName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_FarmName(@ptrCast(*const ITsSbTarget, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_put_FarmName(self: *const T, Val: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).put_FarmName(@ptrCast(*const ITsSbTarget, self), Val); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_TargetFQDN(self: *const T, TargetFqdnName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_TargetFQDN(@ptrCast(*const ITsSbTarget, self), TargetFqdnName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_put_TargetFQDN(self: *const T, Val: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).put_TargetFQDN(@ptrCast(*const ITsSbTarget, self), Val); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_TargetNetbios(self: *const T, TargetNetbiosName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_TargetNetbios(@ptrCast(*const ITsSbTarget, self), TargetNetbiosName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_put_TargetNetbios(self: *const T, Val: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).put_TargetNetbios(@ptrCast(*const ITsSbTarget, self), Val); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_IpAddresses(self: *const T, SOCKADDR: [*]TSSD_ConnectionPoint, numAddresses: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_IpAddresses(@ptrCast(*const ITsSbTarget, self), SOCKADDR, numAddresses); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_put_IpAddresses(self: *const T, SOCKADDR: [*]TSSD_ConnectionPoint, numAddresses: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).put_IpAddresses(@ptrCast(*const ITsSbTarget, self), SOCKADDR, numAddresses); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_TargetState(self: *const T, pState: ?*TARGET_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_TargetState(@ptrCast(*const ITsSbTarget, self), pState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_put_TargetState(self: *const T, State: TARGET_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).put_TargetState(@ptrCast(*const ITsSbTarget, self), State); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_TargetPropertySet(self: *const T, ppPropertySet: ?*?*ITsSbTargetPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_TargetPropertySet(@ptrCast(*const ITsSbTarget, self), ppPropertySet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_put_TargetPropertySet(self: *const T, pVal: ?*ITsSbTargetPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).put_TargetPropertySet(@ptrCast(*const ITsSbTarget, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_EnvironmentName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_EnvironmentName(@ptrCast(*const ITsSbTarget, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_put_EnvironmentName(self: *const T, Val: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).put_EnvironmentName(@ptrCast(*const ITsSbTarget, self), Val); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_NumSessions(self: *const T, pNumSessions: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_NumSessions(@ptrCast(*const ITsSbTarget, self), pNumSessions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_NumPendingConnections(self: *const T, pNumPendingConnections: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_NumPendingConnections(@ptrCast(*const ITsSbTarget, self), pNumPendingConnections); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTarget_get_TargetLoad(self: *const T, pTargetLoad: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTarget.VTable, self.vtable).get_TargetLoad(@ptrCast(*const ITsSbTarget, self), pTargetLoad); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbSession_Value = Guid.initString("d453aac7-b1d8-4c5e-ba34-9afb4c8c5510"); pub const IID_ITsSbSession = &IID_ITsSbSession_Value; pub const ITsSbSession = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SessionId: fn( self: *const ITsSbSession, pVal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetName: fn( self: *const ITsSbSession, targetName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TargetName: fn( self: *const ITsSbSession, targetName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Username: fn( self: *const ITsSbSession, userName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Domain: fn( self: *const ITsSbSession, domain: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_State: fn( self: *const ITsSbSession, pState: ?*TSSESSION_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_State: fn( self: *const ITsSbSession, State: TSSESSION_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CreateTime: fn( self: *const ITsSbSession, pTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_CreateTime: fn( self: *const ITsSbSession, Time: FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisconnectTime: fn( self: *const ITsSbSession, pTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DisconnectTime: fn( self: *const ITsSbSession, Time: FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialProgram: fn( self: *const ITsSbSession, app: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialProgram: fn( self: *const ITsSbSession, Application: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ClientDisplay: fn( self: *const ITsSbSession, pClientDisplay: ?*CLIENT_DISPLAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ClientDisplay: fn( self: *const ITsSbSession, pClientDisplay: CLIENT_DISPLAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ProtocolType: fn( self: *const ITsSbSession, pVal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ProtocolType: fn( self: *const ITsSbSession, Val: 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 ITsSbSession_get_SessionId(self: *const T, pVal: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_SessionId(@ptrCast(*const ITsSbSession, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_TargetName(self: *const T, targetName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_TargetName(@ptrCast(*const ITsSbSession, self), targetName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_put_TargetName(self: *const T, targetName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).put_TargetName(@ptrCast(*const ITsSbSession, self), targetName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_Username(self: *const T, userName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_Username(@ptrCast(*const ITsSbSession, self), userName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_Domain(self: *const T, domain: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_Domain(@ptrCast(*const ITsSbSession, self), domain); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_State(self: *const T, pState: ?*TSSESSION_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_State(@ptrCast(*const ITsSbSession, self), pState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_put_State(self: *const T, State: TSSESSION_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).put_State(@ptrCast(*const ITsSbSession, self), State); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_CreateTime(self: *const T, pTime: ?*FILETIME) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_CreateTime(@ptrCast(*const ITsSbSession, self), pTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_put_CreateTime(self: *const T, Time: FILETIME) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).put_CreateTime(@ptrCast(*const ITsSbSession, self), Time); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_DisconnectTime(self: *const T, pTime: ?*FILETIME) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_DisconnectTime(@ptrCast(*const ITsSbSession, self), pTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_put_DisconnectTime(self: *const T, Time: FILETIME) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).put_DisconnectTime(@ptrCast(*const ITsSbSession, self), Time); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_InitialProgram(self: *const T, app: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_InitialProgram(@ptrCast(*const ITsSbSession, self), app); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_put_InitialProgram(self: *const T, Application: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).put_InitialProgram(@ptrCast(*const ITsSbSession, self), Application); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_ClientDisplay(self: *const T, pClientDisplay: ?*CLIENT_DISPLAY) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_ClientDisplay(@ptrCast(*const ITsSbSession, self), pClientDisplay); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_put_ClientDisplay(self: *const T, pClientDisplay: CLIENT_DISPLAY) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).put_ClientDisplay(@ptrCast(*const ITsSbSession, self), pClientDisplay); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_get_ProtocolType(self: *const T, pVal: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).get_ProtocolType(@ptrCast(*const ITsSbSession, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbSession_put_ProtocolType(self: *const T, Val: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbSession.VTable, self.vtable).put_ProtocolType(@ptrCast(*const ITsSbSession, self), Val); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbResourceNotification_Value = Guid.initString("65d3e85a-c39b-11dc-b92d-3cd255d89593"); pub const IID_ITsSbResourceNotification = &IID_ITsSbResourceNotification_Value; pub const ITsSbResourceNotification = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, NotifySessionChange: fn( self: *const ITsSbResourceNotification, changeType: TSSESSION_STATE, pSession: ?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyTargetChange: fn( self: *const ITsSbResourceNotification, TargetChangeType: u32, pTarget: ?*ITsSbTarget, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyClientConnectionStateChange: fn( self: *const ITsSbResourceNotification, ChangeType: CONNECTION_CHANGE_NOTIFICATION, pConnection: ?*ITsSbClientConnection, ) 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 ITsSbResourceNotification_NotifySessionChange(self: *const T, changeType: TSSESSION_STATE, pSession: ?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourceNotification.VTable, self.vtable).NotifySessionChange(@ptrCast(*const ITsSbResourceNotification, self), changeType, pSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourceNotification_NotifyTargetChange(self: *const T, TargetChangeType: u32, pTarget: ?*ITsSbTarget) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourceNotification.VTable, self.vtable).NotifyTargetChange(@ptrCast(*const ITsSbResourceNotification, self), TargetChangeType, pTarget); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourceNotification_NotifyClientConnectionStateChange(self: *const T, ChangeType: CONNECTION_CHANGE_NOTIFICATION, pConnection: ?*ITsSbClientConnection) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourceNotification.VTable, self.vtable).NotifyClientConnectionStateChange(@ptrCast(*const ITsSbResourceNotification, self), ChangeType, pConnection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbResourceNotificationEx_Value = Guid.initString("a8a47fde-ca91-44d2-b897-3aa28a43b2b7"); pub const IID_ITsSbResourceNotificationEx = &IID_ITsSbResourceNotificationEx_Value; pub const ITsSbResourceNotificationEx = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, NotifySessionChangeEx: fn( self: *const ITsSbResourceNotificationEx, targetName: ?BSTR, userName: ?BSTR, domain: ?BSTR, sessionId: u32, sessionState: TSSESSION_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyTargetChangeEx: fn( self: *const ITsSbResourceNotificationEx, targetName: ?BSTR, targetChangeType: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyClientConnectionStateChangeEx: fn( self: *const ITsSbResourceNotificationEx, userName: ?BSTR, domain: ?BSTR, initialProgram: ?BSTR, poolName: ?BSTR, targetName: ?BSTR, connectionChangeType: CONNECTION_CHANGE_NOTIFICATION, ) 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 ITsSbResourceNotificationEx_NotifySessionChangeEx(self: *const T, targetName: ?BSTR, userName: ?BSTR, domain: ?BSTR, sessionId: u32, sessionState: TSSESSION_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourceNotificationEx.VTable, self.vtable).NotifySessionChangeEx(@ptrCast(*const ITsSbResourceNotificationEx, self), targetName, userName, domain, sessionId, sessionState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourceNotificationEx_NotifyTargetChangeEx(self: *const T, targetName: ?BSTR, targetChangeType: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourceNotificationEx.VTable, self.vtable).NotifyTargetChangeEx(@ptrCast(*const ITsSbResourceNotificationEx, self), targetName, targetChangeType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourceNotificationEx_NotifyClientConnectionStateChangeEx(self: *const T, userName: ?BSTR, domain: ?BSTR, initialProgram: ?BSTR, poolName: ?BSTR, targetName: ?BSTR, connectionChangeType: CONNECTION_CHANGE_NOTIFICATION) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourceNotificationEx.VTable, self.vtable).NotifyClientConnectionStateChangeEx(@ptrCast(*const ITsSbResourceNotificationEx, self), userName, domain, initialProgram, poolName, targetName, connectionChangeType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbTaskInfo_Value = Guid.initString("523d1083-89be-48dd-99ea-04e82ffa7265"); pub const IID_ITsSbTaskInfo = &IID_ITsSbTaskInfo_Value; pub const ITsSbTaskInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TargetId: fn( self: *const ITsSbTaskInfo, pName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StartTime: fn( self: *const ITsSbTaskInfo, pStartTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EndTime: fn( self: *const ITsSbTaskInfo, pEndTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Deadline: fn( self: *const ITsSbTaskInfo, pDeadline: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Identifier: fn( self: *const ITsSbTaskInfo, pIdentifier: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Label: fn( self: *const ITsSbTaskInfo, pLabel: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Context: fn( self: *const ITsSbTaskInfo, pContext: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Plugin: fn( self: *const ITsSbTaskInfo, pPlugin: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const ITsSbTaskInfo, pStatus: ?*RDV_TASK_STATUS, ) 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 ITsSbTaskInfo_get_TargetId(self: *const T, pName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_TargetId(@ptrCast(*const ITsSbTaskInfo, self), pName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskInfo_get_StartTime(self: *const T, pStartTime: ?*FILETIME) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_StartTime(@ptrCast(*const ITsSbTaskInfo, self), pStartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskInfo_get_EndTime(self: *const T, pEndTime: ?*FILETIME) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_EndTime(@ptrCast(*const ITsSbTaskInfo, self), pEndTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskInfo_get_Deadline(self: *const T, pDeadline: ?*FILETIME) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_Deadline(@ptrCast(*const ITsSbTaskInfo, self), pDeadline); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskInfo_get_Identifier(self: *const T, pIdentifier: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_Identifier(@ptrCast(*const ITsSbTaskInfo, self), pIdentifier); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskInfo_get_Label(self: *const T, pLabel: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_Label(@ptrCast(*const ITsSbTaskInfo, self), pLabel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskInfo_get_Context(self: *const T, pContext: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_Context(@ptrCast(*const ITsSbTaskInfo, self), pContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskInfo_get_Plugin(self: *const T, pPlugin: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_Plugin(@ptrCast(*const ITsSbTaskInfo, self), pPlugin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskInfo_get_Status(self: *const T, pStatus: ?*RDV_TASK_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskInfo.VTable, self.vtable).get_Status(@ptrCast(*const ITsSbTaskInfo, self), pStatus); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbTaskPlugin_Value = Guid.initString("fa22ef0f-8705-41be-93bc-44bdbcf1c9c4"); pub const IID_ITsSbTaskPlugin = &IID_ITsSbTaskPlugin_Value; pub const ITsSbTaskPlugin = extern struct { pub const VTable = extern struct { base: ITsSbPlugin.VTable, InitializeTaskPlugin: fn( self: *const ITsSbTaskPlugin, pITsSbTaskPluginNotifySink: ?*ITsSbTaskPluginNotifySink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTaskQueue: fn( self: *const ITsSbTaskPlugin, pszHostName: ?BSTR, SbTaskInfoSize: u32, pITsSbTaskInfo: [*]?*ITsSbTaskInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPlugin.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskPlugin_InitializeTaskPlugin(self: *const T, pITsSbTaskPluginNotifySink: ?*ITsSbTaskPluginNotifySink) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskPlugin.VTable, self.vtable).InitializeTaskPlugin(@ptrCast(*const ITsSbTaskPlugin, self), pITsSbTaskPluginNotifySink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskPlugin_SetTaskQueue(self: *const T, pszHostName: ?BSTR, SbTaskInfoSize: u32, pITsSbTaskInfo: [*]?*ITsSbTaskInfo) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskPlugin.VTable, self.vtable).SetTaskQueue(@ptrCast(*const ITsSbTaskPlugin, self), pszHostName, SbTaskInfoSize, pITsSbTaskInfo); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbPropertySet_Value = Guid.initString("5c025171-bb1e-4baf-a212-6d5e9774b33b"); pub const IID_ITsSbPropertySet = &IID_ITsSbPropertySet_Value; pub const ITsSbPropertySet = extern struct { pub const VTable = extern struct { base: IPropertyBag.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPropertyBag.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbPluginPropertySet_Value = Guid.initString("95006e34-7eff-4b6c-bb40-49a4fda7cea6"); pub const IID_ITsSbPluginPropertySet = &IID_ITsSbPluginPropertySet_Value; pub const ITsSbPluginPropertySet = extern struct { pub const VTable = extern struct { base: ITsSbPropertySet.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPropertySet.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbClientConnectionPropertySet_Value = Guid.initString("e51995b0-46d6-11dd-aa21-cedc55d89593"); pub const IID_ITsSbClientConnectionPropertySet = &IID_ITsSbClientConnectionPropertySet_Value; pub const ITsSbClientConnectionPropertySet = extern struct { pub const VTable = extern struct { base: ITsSbPropertySet.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPropertySet.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbTargetPropertySet_Value = Guid.initString("f7bda5d6-994c-4e11-a079-2763b61830ac"); pub const IID_ITsSbTargetPropertySet = &IID_ITsSbTargetPropertySet_Value; pub const ITsSbTargetPropertySet = extern struct { pub const VTable = extern struct { base: ITsSbPropertySet.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPropertySet.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbEnvironmentPropertySet_Value = Guid.initString("d0d1bf7e-7acf-11dd-a243-e51156d89593"); pub const IID_ITsSbEnvironmentPropertySet = &IID_ITsSbEnvironmentPropertySet_Value; pub const ITsSbEnvironmentPropertySet = extern struct { pub const VTable = extern struct { base: ITsSbPropertySet.VTable, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPropertySet.MethodMixin(T); };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbBaseNotifySink_Value = Guid.initString("808a6537-1282-4989-9e09-f43938b71722"); pub const IID_ITsSbBaseNotifySink = &IID_ITsSbBaseNotifySink_Value; pub const ITsSbBaseNotifySink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnError: fn( self: *const ITsSbBaseNotifySink, hrError: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnReportStatus: fn( self: *const ITsSbBaseNotifySink, messageType: CLIENT_MESSAGE_TYPE, messageID: 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 ITsSbBaseNotifySink_OnError(self: *const T, hrError: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbBaseNotifySink.VTable, self.vtable).OnError(@ptrCast(*const ITsSbBaseNotifySink, self), hrError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbBaseNotifySink_OnReportStatus(self: *const T, messageType: CLIENT_MESSAGE_TYPE, messageID: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbBaseNotifySink.VTable, self.vtable).OnReportStatus(@ptrCast(*const ITsSbBaseNotifySink, self), messageType, messageID); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbPluginNotifySink_Value = Guid.initString("44dfe30b-c3be-40f5-bf82-7a95bb795adf"); pub const IID_ITsSbPluginNotifySink = &IID_ITsSbPluginNotifySink_Value; pub const ITsSbPluginNotifySink = extern struct { pub const VTable = extern struct { base: ITsSbBaseNotifySink.VTable, OnInitialized: fn( self: *const ITsSbPluginNotifySink, hr: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnTerminated: fn( self: *const ITsSbPluginNotifySink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbBaseNotifySink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbPluginNotifySink_OnInitialized(self: *const T, hr: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbPluginNotifySink.VTable, self.vtable).OnInitialized(@ptrCast(*const ITsSbPluginNotifySink, self), hr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbPluginNotifySink_OnTerminated(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbPluginNotifySink.VTable, self.vtable).OnTerminated(@ptrCast(*const ITsSbPluginNotifySink, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbLoadBalancingNotifySink_Value = Guid.initString("5f8a8297-3244-4e6a-958a-27c822c1e141"); pub const IID_ITsSbLoadBalancingNotifySink = &IID_ITsSbLoadBalancingNotifySink_Value; pub const ITsSbLoadBalancingNotifySink = extern struct { pub const VTable = extern struct { base: ITsSbBaseNotifySink.VTable, OnGetMostSuitableTarget: fn( self: *const ITsSbLoadBalancingNotifySink, pLBResult: ?*ITsSbLoadBalanceResult, fIsNewConnection: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbBaseNotifySink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbLoadBalancingNotifySink_OnGetMostSuitableTarget(self: *const T, pLBResult: ?*ITsSbLoadBalanceResult, fIsNewConnection: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbLoadBalancingNotifySink.VTable, self.vtable).OnGetMostSuitableTarget(@ptrCast(*const ITsSbLoadBalancingNotifySink, self), pLBResult, fIsNewConnection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbPlacementNotifySink_Value = Guid.initString("68a0c487-2b4f-46c2-94a1-6ce685183634"); pub const IID_ITsSbPlacementNotifySink = &IID_ITsSbPlacementNotifySink_Value; pub const ITsSbPlacementNotifySink = extern struct { pub const VTable = extern struct { base: ITsSbBaseNotifySink.VTable, OnQueryEnvironmentCompleted: fn( self: *const ITsSbPlacementNotifySink, pEnvironment: ?*ITsSbEnvironment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbBaseNotifySink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbPlacementNotifySink_OnQueryEnvironmentCompleted(self: *const T, pEnvironment: ?*ITsSbEnvironment) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbPlacementNotifySink.VTable, self.vtable).OnQueryEnvironmentCompleted(@ptrCast(*const ITsSbPlacementNotifySink, self), pEnvironment); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbOrchestrationNotifySink_Value = Guid.initString("36c37d61-926b-442f-bca5-118c6d50dcf2"); pub const IID_ITsSbOrchestrationNotifySink = &IID_ITsSbOrchestrationNotifySink_Value; pub const ITsSbOrchestrationNotifySink = extern struct { pub const VTable = extern struct { base: ITsSbBaseNotifySink.VTable, OnReadyToConnect: fn( self: *const ITsSbOrchestrationNotifySink, pTarget: ?*ITsSbTarget, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbBaseNotifySink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbOrchestrationNotifySink_OnReadyToConnect(self: *const T, pTarget: ?*ITsSbTarget) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbOrchestrationNotifySink.VTable, self.vtable).OnReadyToConnect(@ptrCast(*const ITsSbOrchestrationNotifySink, self), pTarget); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbTaskPluginNotifySink_Value = Guid.initString("6aaf899e-c2ec-45ee-aa37-45e60895261a"); pub const IID_ITsSbTaskPluginNotifySink = &IID_ITsSbTaskPluginNotifySink_Value; pub const ITsSbTaskPluginNotifySink = extern struct { pub const VTable = extern struct { base: ITsSbBaseNotifySink.VTable, OnSetTaskTime: fn( self: *const ITsSbTaskPluginNotifySink, szTargetName: ?BSTR, TaskStartTime: FILETIME, TaskEndTime: FILETIME, TaskDeadline: FILETIME, szTaskLabel: ?BSTR, szTaskIdentifier: ?BSTR, szTaskPlugin: ?BSTR, dwTaskStatus: u32, saContext: ?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDeleteTaskTime: fn( self: *const ITsSbTaskPluginNotifySink, szTargetName: ?BSTR, szTaskIdentifier: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnUpdateTaskStatus: fn( self: *const ITsSbTaskPluginNotifySink, szTargetName: ?BSTR, TaskIdentifier: ?BSTR, TaskStatus: RDV_TASK_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnReportTasks: fn( self: *const ITsSbTaskPluginNotifySink, szHostName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbBaseNotifySink.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskPluginNotifySink_OnSetTaskTime(self: *const T, szTargetName: ?BSTR, TaskStartTime: FILETIME, TaskEndTime: FILETIME, TaskDeadline: FILETIME, szTaskLabel: ?BSTR, szTaskIdentifier: ?BSTR, szTaskPlugin: ?BSTR, dwTaskStatus: u32, saContext: ?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskPluginNotifySink.VTable, self.vtable).OnSetTaskTime(@ptrCast(*const ITsSbTaskPluginNotifySink, self), szTargetName, TaskStartTime, TaskEndTime, TaskDeadline, szTaskLabel, szTaskIdentifier, szTaskPlugin, dwTaskStatus, saContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskPluginNotifySink_OnDeleteTaskTime(self: *const T, szTargetName: ?BSTR, szTaskIdentifier: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskPluginNotifySink.VTable, self.vtable).OnDeleteTaskTime(@ptrCast(*const ITsSbTaskPluginNotifySink, self), szTargetName, szTaskIdentifier); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskPluginNotifySink_OnUpdateTaskStatus(self: *const T, szTargetName: ?BSTR, TaskIdentifier: ?BSTR, TaskStatus: RDV_TASK_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskPluginNotifySink.VTable, self.vtable).OnUpdateTaskStatus(@ptrCast(*const ITsSbTaskPluginNotifySink, self), szTargetName, TaskIdentifier, TaskStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbTaskPluginNotifySink_OnReportTasks(self: *const T, szHostName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbTaskPluginNotifySink.VTable, self.vtable).OnReportTasks(@ptrCast(*const ITsSbTaskPluginNotifySink, self), szHostName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbClientConnection_Value = Guid.initString("18857499-ad61-4b1b-b7df-cbcd41fb8338"); pub const IID_ITsSbClientConnection = &IID_ITsSbClientConnection_Value; pub const ITsSbClientConnection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserName: fn( self: *const ITsSbClientConnection, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Domain: fn( self: *const ITsSbClientConnection, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialProgram: fn( self: *const ITsSbClientConnection, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LoadBalanceResult: fn( self: *const ITsSbClientConnection, ppVal: ?*?*ITsSbLoadBalanceResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FarmName: fn( self: *const ITsSbClientConnection, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutContext: fn( self: *const ITsSbClientConnection, contextId: ?BSTR, context: VARIANT, existingContext: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContext: fn( self: *const ITsSbClientConnection, contextId: ?BSTR, context: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Environment: fn( self: *const ITsSbClientConnection, ppEnvironment: ?*?*ITsSbEnvironment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ConnectionError: fn( self: *const ITsSbClientConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SamUserAccount: fn( self: *const ITsSbClientConnection, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ClientConnectionPropertySet: fn( self: *const ITsSbClientConnection, ppPropertySet: ?*?*ITsSbClientConnectionPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IsFirstAssignment: fn( self: *const ITsSbClientConnection, ppVal: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RdFarmType: fn( self: *const ITsSbClientConnection, pRdFarmType: ?*RD_FARM_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserSidString: fn( self: *const ITsSbClientConnection, pszUserSidString: ?*?*i8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisconnectedSession: fn( self: *const ITsSbClientConnection, ppSession: ?*?*ITsSbSession, ) 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 ITsSbClientConnection_get_UserName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_UserName(@ptrCast(*const ITsSbClientConnection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_Domain(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_Domain(@ptrCast(*const ITsSbClientConnection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_InitialProgram(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_InitialProgram(@ptrCast(*const ITsSbClientConnection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_LoadBalanceResult(self: *const T, ppVal: ?*?*ITsSbLoadBalanceResult) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_LoadBalanceResult(@ptrCast(*const ITsSbClientConnection, self), ppVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_FarmName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_FarmName(@ptrCast(*const ITsSbClientConnection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_PutContext(self: *const T, contextId: ?BSTR, context: VARIANT, existingContext: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).PutContext(@ptrCast(*const ITsSbClientConnection, self), contextId, context, existingContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_GetContext(self: *const T, contextId: ?BSTR, context: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).GetContext(@ptrCast(*const ITsSbClientConnection, self), contextId, context); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_Environment(self: *const T, ppEnvironment: ?*?*ITsSbEnvironment) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_Environment(@ptrCast(*const ITsSbClientConnection, self), ppEnvironment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_ConnectionError(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_ConnectionError(@ptrCast(*const ITsSbClientConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_SamUserAccount(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_SamUserAccount(@ptrCast(*const ITsSbClientConnection, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_ClientConnectionPropertySet(self: *const T, ppPropertySet: ?*?*ITsSbClientConnectionPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_ClientConnectionPropertySet(@ptrCast(*const ITsSbClientConnection, self), ppPropertySet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_IsFirstAssignment(self: *const T, ppVal: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_IsFirstAssignment(@ptrCast(*const ITsSbClientConnection, self), ppVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_RdFarmType(self: *const T, pRdFarmType: ?*RD_FARM_TYPE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_RdFarmType(@ptrCast(*const ITsSbClientConnection, self), pRdFarmType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_get_UserSidString(self: *const T, pszUserSidString: ?*?*i8) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).get_UserSidString(@ptrCast(*const ITsSbClientConnection, self), pszUserSidString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbClientConnection_GetDisconnectedSession(self: *const T, ppSession: ?*?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbClientConnection.VTable, self.vtable).GetDisconnectedSession(@ptrCast(*const ITsSbClientConnection, self), ppSession); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbProvider_Value = Guid.initString("87a4098f-6d7b-44dd-bc17-8ce44e370d52"); pub const IID_ITsSbProvider = &IID_ITsSbProvider_Value; pub const ITsSbProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateTargetObject: fn( self: *const ITsSbProvider, TargetName: ?BSTR, EnvironmentName: ?BSTR, ppTarget: ?*?*ITsSbTarget, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateLoadBalanceResultObject: fn( self: *const ITsSbProvider, TargetName: ?BSTR, ppLBResult: ?*?*ITsSbLoadBalanceResult, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateSessionObject: fn( self: *const ITsSbProvider, TargetName: ?BSTR, UserName: ?BSTR, Domain: ?BSTR, SessionId: u32, ppSession: ?*?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePluginPropertySet: fn( self: *const ITsSbProvider, ppPropertySet: ?*?*ITsSbPluginPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateTargetPropertySetObject: fn( self: *const ITsSbProvider, ppPropertySet: ?*?*ITsSbTargetPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateEnvironmentObject: fn( self: *const ITsSbProvider, Name: ?BSTR, ServerWeight: u32, ppEnvironment: ?*?*ITsSbEnvironment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetResourcePluginStore: fn( self: *const ITsSbProvider, ppStore: ?*?*ITsSbResourcePluginStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFilterPluginStore: fn( self: *const ITsSbProvider, ppStore: ?*?*ITsSbFilterPluginStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterForNotification: fn( self: *const ITsSbProvider, notificationType: u32, ResourceToMonitor: ?BSTR, pPluginNotification: ?*ITsSbResourceNotification, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnRegisterForNotification: fn( self: *const ITsSbProvider, notificationType: u32, ResourceToMonitor: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInstanceOfGlobalStore: fn( self: *const ITsSbProvider, ppGlobalStore: ?*?*ITsSbGlobalStore, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateEnvironmentPropertySetObject: fn( self: *const ITsSbProvider, ppPropertySet: ?*?*ITsSbEnvironmentPropertySet, ) 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 ITsSbProvider_CreateTargetObject(self: *const T, TargetName: ?BSTR, EnvironmentName: ?BSTR, ppTarget: ?*?*ITsSbTarget) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).CreateTargetObject(@ptrCast(*const ITsSbProvider, self), TargetName, EnvironmentName, ppTarget); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_CreateLoadBalanceResultObject(self: *const T, TargetName: ?BSTR, ppLBResult: ?*?*ITsSbLoadBalanceResult) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).CreateLoadBalanceResultObject(@ptrCast(*const ITsSbProvider, self), TargetName, ppLBResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_CreateSessionObject(self: *const T, TargetName: ?BSTR, UserName: ?BSTR, Domain: ?BSTR, SessionId: u32, ppSession: ?*?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).CreateSessionObject(@ptrCast(*const ITsSbProvider, self), TargetName, UserName, Domain, SessionId, ppSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_CreatePluginPropertySet(self: *const T, ppPropertySet: ?*?*ITsSbPluginPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).CreatePluginPropertySet(@ptrCast(*const ITsSbProvider, self), ppPropertySet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_CreateTargetPropertySetObject(self: *const T, ppPropertySet: ?*?*ITsSbTargetPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).CreateTargetPropertySetObject(@ptrCast(*const ITsSbProvider, self), ppPropertySet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_CreateEnvironmentObject(self: *const T, Name: ?BSTR, ServerWeight: u32, ppEnvironment: ?*?*ITsSbEnvironment) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).CreateEnvironmentObject(@ptrCast(*const ITsSbProvider, self), Name, ServerWeight, ppEnvironment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_GetResourcePluginStore(self: *const T, ppStore: ?*?*ITsSbResourcePluginStore) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).GetResourcePluginStore(@ptrCast(*const ITsSbProvider, self), ppStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_GetFilterPluginStore(self: *const T, ppStore: ?*?*ITsSbFilterPluginStore) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).GetFilterPluginStore(@ptrCast(*const ITsSbProvider, self), ppStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_RegisterForNotification(self: *const T, notificationType: u32, ResourceToMonitor: ?BSTR, pPluginNotification: ?*ITsSbResourceNotification) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).RegisterForNotification(@ptrCast(*const ITsSbProvider, self), notificationType, ResourceToMonitor, pPluginNotification); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_UnRegisterForNotification(self: *const T, notificationType: u32, ResourceToMonitor: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).UnRegisterForNotification(@ptrCast(*const ITsSbProvider, self), notificationType, ResourceToMonitor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_GetInstanceOfGlobalStore(self: *const T, ppGlobalStore: ?*?*ITsSbGlobalStore) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).GetInstanceOfGlobalStore(@ptrCast(*const ITsSbProvider, self), ppGlobalStore); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvider_CreateEnvironmentPropertySetObject(self: *const T, ppPropertySet: ?*?*ITsSbEnvironmentPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvider.VTable, self.vtable).CreateEnvironmentPropertySetObject(@ptrCast(*const ITsSbProvider, self), ppPropertySet); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbResourcePluginStore_Value = Guid.initString("5c38f65f-bcf1-4036-a6bf-9e3cccae0b63"); pub const IID_ITsSbResourcePluginStore = &IID_ITsSbResourcePluginStore_Value; pub const ITsSbResourcePluginStore = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, QueryTarget: fn( self: *const ITsSbResourcePluginStore, TargetName: ?BSTR, FarmName: ?BSTR, ppTarget: ?*?*ITsSbTarget, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QuerySessionBySessionId: fn( self: *const ITsSbResourcePluginStore, dwSessionId: u32, TargetName: ?BSTR, ppSession: ?*?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddTargetToStore: fn( self: *const ITsSbResourcePluginStore, pTarget: ?*ITsSbTarget, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddSessionToStore: fn( self: *const ITsSbResourcePluginStore, pSession: ?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddEnvironmentToStore: fn( self: *const ITsSbResourcePluginStore, pEnvironment: ?*ITsSbEnvironment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveEnvironmentFromStore: fn( self: *const ITsSbResourcePluginStore, EnvironmentName: ?BSTR, bIgnoreOwner: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateFarms: fn( self: *const ITsSbResourcePluginStore, pdwCount: ?*u32, pVal: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryEnvironment: fn( self: *const ITsSbResourcePluginStore, EnvironmentName: ?BSTR, ppEnvironment: ?*?*ITsSbEnvironment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateEnvironments: fn( self: *const ITsSbResourcePluginStore, pdwCount: ?*u32, pVal: [*]?*?*ITsSbEnvironment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveTarget: fn( self: *const ITsSbResourcePluginStore, pTarget: ?*ITsSbTarget, bForceWrite: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveEnvironment: fn( self: *const ITsSbResourcePluginStore, pEnvironment: ?*ITsSbEnvironment, bForceWrite: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveSession: fn( self: *const ITsSbResourcePluginStore, pSession: ?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTargetProperty: fn( self: *const ITsSbResourcePluginStore, TargetName: ?BSTR, PropertyName: ?BSTR, pProperty: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnvironmentProperty: fn( self: *const ITsSbResourcePluginStore, EnvironmentName: ?BSTR, PropertyName: ?BSTR, pProperty: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTargetState: fn( self: *const ITsSbResourcePluginStore, targetName: ?BSTR, newState: TARGET_STATE, pOldState: ?*TARGET_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSessionState: fn( self: *const ITsSbResourcePluginStore, sbSession: ?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateTargets: fn( self: *const ITsSbResourcePluginStore, FarmName: ?BSTR, EnvName: ?BSTR, sortByFieldId: TS_SB_SORT_BY, sortyByPropName: ?BSTR, pdwCount: ?*u32, pVal: [*]?*?*ITsSbTarget, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateSessions: fn( self: *const ITsSbResourcePluginStore, targetName: ?BSTR, userName: ?BSTR, userDomain: ?BSTR, poolName: ?BSTR, initialProgram: ?BSTR, pSessionState: ?*TSSESSION_STATE, pdwCount: ?*u32, ppVal: [*]?*?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFarmProperty: fn( self: *const ITsSbResourcePluginStore, farmName: ?BSTR, propertyName: ?BSTR, pVarValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteTarget: fn( self: *const ITsSbResourcePluginStore, targetName: ?BSTR, hostName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTargetPropertyWithVersionCheck: fn( self: *const ITsSbResourcePluginStore, pTarget: ?*ITsSbTarget, PropertyName: ?BSTR, pProperty: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEnvironmentPropertyWithVersionCheck: fn( self: *const ITsSbResourcePluginStore, pEnvironment: ?*ITsSbEnvironment, PropertyName: ?BSTR, pProperty: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AcquireTargetLock: fn( self: *const ITsSbResourcePluginStore, targetName: ?BSTR, dwTimeout: u32, ppContext: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseTargetLock: fn( self: *const ITsSbResourcePluginStore, pContext: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, TestAndSetServerState: fn( self: *const ITsSbResourcePluginStore, PoolName: ?BSTR, ServerFQDN: ?BSTR, NewState: TARGET_STATE, TestState: TARGET_STATE, pInitState: ?*TARGET_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetServerWaitingToStart: fn( self: *const ITsSbResourcePluginStore, PoolName: ?BSTR, serverName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetServerState: fn( self: *const ITsSbResourcePluginStore, PoolName: ?BSTR, ServerFQDN: ?BSTR, pState: ?*TARGET_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetServerDrainMode: fn( self: *const ITsSbResourcePluginStore, ServerFQDN: ?BSTR, DrainMode: 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 ITsSbResourcePluginStore_QueryTarget(self: *const T, TargetName: ?BSTR, FarmName: ?BSTR, ppTarget: ?*?*ITsSbTarget) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).QueryTarget(@ptrCast(*const ITsSbResourcePluginStore, self), TargetName, FarmName, ppTarget); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_QuerySessionBySessionId(self: *const T, dwSessionId: u32, TargetName: ?BSTR, ppSession: ?*?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).QuerySessionBySessionId(@ptrCast(*const ITsSbResourcePluginStore, self), dwSessionId, TargetName, ppSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_AddTargetToStore(self: *const T, pTarget: ?*ITsSbTarget) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).AddTargetToStore(@ptrCast(*const ITsSbResourcePluginStore, self), pTarget); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_AddSessionToStore(self: *const T, pSession: ?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).AddSessionToStore(@ptrCast(*const ITsSbResourcePluginStore, self), pSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_AddEnvironmentToStore(self: *const T, pEnvironment: ?*ITsSbEnvironment) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).AddEnvironmentToStore(@ptrCast(*const ITsSbResourcePluginStore, self), pEnvironment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_RemoveEnvironmentFromStore(self: *const T, EnvironmentName: ?BSTR, bIgnoreOwner: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).RemoveEnvironmentFromStore(@ptrCast(*const ITsSbResourcePluginStore, self), EnvironmentName, bIgnoreOwner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_EnumerateFarms(self: *const T, pdwCount: ?*u32, pVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).EnumerateFarms(@ptrCast(*const ITsSbResourcePluginStore, self), pdwCount, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_QueryEnvironment(self: *const T, EnvironmentName: ?BSTR, ppEnvironment: ?*?*ITsSbEnvironment) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).QueryEnvironment(@ptrCast(*const ITsSbResourcePluginStore, self), EnvironmentName, ppEnvironment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_EnumerateEnvironments(self: *const T, pdwCount: ?*u32, pVal: [*]?*?*ITsSbEnvironment) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).EnumerateEnvironments(@ptrCast(*const ITsSbResourcePluginStore, self), pdwCount, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SaveTarget(self: *const T, pTarget: ?*ITsSbTarget, bForceWrite: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SaveTarget(@ptrCast(*const ITsSbResourcePluginStore, self), pTarget, bForceWrite); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SaveEnvironment(self: *const T, pEnvironment: ?*ITsSbEnvironment, bForceWrite: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SaveEnvironment(@ptrCast(*const ITsSbResourcePluginStore, self), pEnvironment, bForceWrite); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SaveSession(self: *const T, pSession: ?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SaveSession(@ptrCast(*const ITsSbResourcePluginStore, self), pSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SetTargetProperty(self: *const T, TargetName: ?BSTR, PropertyName: ?BSTR, pProperty: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SetTargetProperty(@ptrCast(*const ITsSbResourcePluginStore, self), TargetName, PropertyName, pProperty); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SetEnvironmentProperty(self: *const T, EnvironmentName: ?BSTR, PropertyName: ?BSTR, pProperty: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SetEnvironmentProperty(@ptrCast(*const ITsSbResourcePluginStore, self), EnvironmentName, PropertyName, pProperty); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SetTargetState(self: *const T, targetName: ?BSTR, newState: TARGET_STATE, pOldState: ?*TARGET_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SetTargetState(@ptrCast(*const ITsSbResourcePluginStore, self), targetName, newState, pOldState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SetSessionState(self: *const T, sbSession: ?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SetSessionState(@ptrCast(*const ITsSbResourcePluginStore, self), sbSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_EnumerateTargets(self: *const T, FarmName: ?BSTR, EnvName: ?BSTR, sortByFieldId: TS_SB_SORT_BY, sortyByPropName: ?BSTR, pdwCount: ?*u32, pVal: [*]?*?*ITsSbTarget) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).EnumerateTargets(@ptrCast(*const ITsSbResourcePluginStore, self), FarmName, EnvName, sortByFieldId, sortyByPropName, pdwCount, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_EnumerateSessions(self: *const T, targetName: ?BSTR, userName: ?BSTR, userDomain: ?BSTR, poolName: ?BSTR, initialProgram: ?BSTR, pSessionState: ?*TSSESSION_STATE, pdwCount: ?*u32, ppVal: [*]?*?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).EnumerateSessions(@ptrCast(*const ITsSbResourcePluginStore, self), targetName, userName, userDomain, poolName, initialProgram, pSessionState, pdwCount, ppVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_GetFarmProperty(self: *const T, farmName: ?BSTR, propertyName: ?BSTR, pVarValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).GetFarmProperty(@ptrCast(*const ITsSbResourcePluginStore, self), farmName, propertyName, pVarValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_DeleteTarget(self: *const T, targetName: ?BSTR, hostName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).DeleteTarget(@ptrCast(*const ITsSbResourcePluginStore, self), targetName, hostName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SetTargetPropertyWithVersionCheck(self: *const T, pTarget: ?*ITsSbTarget, PropertyName: ?BSTR, pProperty: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SetTargetPropertyWithVersionCheck(@ptrCast(*const ITsSbResourcePluginStore, self), pTarget, PropertyName, pProperty); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SetEnvironmentPropertyWithVersionCheck(self: *const T, pEnvironment: ?*ITsSbEnvironment, PropertyName: ?BSTR, pProperty: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SetEnvironmentPropertyWithVersionCheck(@ptrCast(*const ITsSbResourcePluginStore, self), pEnvironment, PropertyName, pProperty); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_AcquireTargetLock(self: *const T, targetName: ?BSTR, dwTimeout: u32, ppContext: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).AcquireTargetLock(@ptrCast(*const ITsSbResourcePluginStore, self), targetName, dwTimeout, ppContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_ReleaseTargetLock(self: *const T, pContext: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).ReleaseTargetLock(@ptrCast(*const ITsSbResourcePluginStore, self), pContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_TestAndSetServerState(self: *const T, PoolName: ?BSTR, ServerFQDN: ?BSTR, NewState: TARGET_STATE, TestState: TARGET_STATE, pInitState: ?*TARGET_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).TestAndSetServerState(@ptrCast(*const ITsSbResourcePluginStore, self), PoolName, ServerFQDN, NewState, TestState, pInitState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SetServerWaitingToStart(self: *const T, PoolName: ?BSTR, serverName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SetServerWaitingToStart(@ptrCast(*const ITsSbResourcePluginStore, self), PoolName, serverName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_GetServerState(self: *const T, PoolName: ?BSTR, ServerFQDN: ?BSTR, pState: ?*TARGET_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).GetServerState(@ptrCast(*const ITsSbResourcePluginStore, self), PoolName, ServerFQDN, pState); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbResourcePluginStore_SetServerDrainMode(self: *const T, ServerFQDN: ?BSTR, DrainMode: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbResourcePluginStore.VTable, self.vtable).SetServerDrainMode(@ptrCast(*const ITsSbResourcePluginStore, self), ServerFQDN, DrainMode); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbFilterPluginStore_Value = Guid.initString("85b44b0f-ed78-413f-9702-fa6d3b5ee755"); pub const IID_ITsSbFilterPluginStore = &IID_ITsSbFilterPluginStore_Value; pub const ITsSbFilterPluginStore = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SaveProperties: fn( self: *const ITsSbFilterPluginStore, pPropertySet: ?*ITsSbPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateProperties: fn( self: *const ITsSbFilterPluginStore, ppPropertySet: ?*?*ITsSbPropertySet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteProperties: fn( self: *const ITsSbFilterPluginStore, propertyName: ?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 ITsSbFilterPluginStore_SaveProperties(self: *const T, pPropertySet: ?*ITsSbPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbFilterPluginStore.VTable, self.vtable).SaveProperties(@ptrCast(*const ITsSbFilterPluginStore, self), pPropertySet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbFilterPluginStore_EnumerateProperties(self: *const T, ppPropertySet: ?*?*ITsSbPropertySet) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbFilterPluginStore.VTable, self.vtable).EnumerateProperties(@ptrCast(*const ITsSbFilterPluginStore, self), ppPropertySet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbFilterPluginStore_DeleteProperties(self: *const T, propertyName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbFilterPluginStore.VTable, self.vtable).DeleteProperties(@ptrCast(*const ITsSbFilterPluginStore, self), propertyName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbGlobalStore_Value = Guid.initString("9ab60f7b-bd72-4d9f-8a3a-a0ea5574e635"); pub const IID_ITsSbGlobalStore = &IID_ITsSbGlobalStore_Value; pub const ITsSbGlobalStore = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, QueryTarget: fn( self: *const ITsSbGlobalStore, ProviderName: ?BSTR, TargetName: ?BSTR, FarmName: ?BSTR, ppTarget: ?*?*ITsSbTarget, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QuerySessionBySessionId: fn( self: *const ITsSbGlobalStore, ProviderName: ?BSTR, dwSessionId: u32, TargetName: ?BSTR, ppSession: ?*?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateFarms: fn( self: *const ITsSbGlobalStore, ProviderName: ?BSTR, pdwCount: ?*u32, pVal: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateTargets: fn( self: *const ITsSbGlobalStore, ProviderName: ?BSTR, FarmName: ?BSTR, EnvName: ?BSTR, pdwCount: ?*u32, pVal: [*]?*?*ITsSbTarget, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateEnvironmentsByProvider: fn( self: *const ITsSbGlobalStore, ProviderName: ?BSTR, pdwCount: ?*u32, ppVal: [*]?*?*ITsSbEnvironment, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumerateSessions: fn( self: *const ITsSbGlobalStore, ProviderName: ?BSTR, targetName: ?BSTR, userName: ?BSTR, userDomain: ?BSTR, poolName: ?BSTR, initialProgram: ?BSTR, pSessionState: ?*TSSESSION_STATE, pdwCount: ?*u32, ppVal: [*]?*?*ITsSbSession, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFarmProperty: fn( self: *const ITsSbGlobalStore, farmName: ?BSTR, propertyName: ?BSTR, pVarValue: ?*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 ITsSbGlobalStore_QueryTarget(self: *const T, ProviderName: ?BSTR, TargetName: ?BSTR, FarmName: ?BSTR, ppTarget: ?*?*ITsSbTarget) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGlobalStore.VTable, self.vtable).QueryTarget(@ptrCast(*const ITsSbGlobalStore, self), ProviderName, TargetName, FarmName, ppTarget); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbGlobalStore_QuerySessionBySessionId(self: *const T, ProviderName: ?BSTR, dwSessionId: u32, TargetName: ?BSTR, ppSession: ?*?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGlobalStore.VTable, self.vtable).QuerySessionBySessionId(@ptrCast(*const ITsSbGlobalStore, self), ProviderName, dwSessionId, TargetName, ppSession); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbGlobalStore_EnumerateFarms(self: *const T, ProviderName: ?BSTR, pdwCount: ?*u32, pVal: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGlobalStore.VTable, self.vtable).EnumerateFarms(@ptrCast(*const ITsSbGlobalStore, self), ProviderName, pdwCount, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbGlobalStore_EnumerateTargets(self: *const T, ProviderName: ?BSTR, FarmName: ?BSTR, EnvName: ?BSTR, pdwCount: ?*u32, pVal: [*]?*?*ITsSbTarget) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGlobalStore.VTable, self.vtable).EnumerateTargets(@ptrCast(*const ITsSbGlobalStore, self), ProviderName, FarmName, EnvName, pdwCount, pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbGlobalStore_EnumerateEnvironmentsByProvider(self: *const T, ProviderName: ?BSTR, pdwCount: ?*u32, ppVal: [*]?*?*ITsSbEnvironment) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGlobalStore.VTable, self.vtable).EnumerateEnvironmentsByProvider(@ptrCast(*const ITsSbGlobalStore, self), ProviderName, pdwCount, ppVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbGlobalStore_EnumerateSessions(self: *const T, ProviderName: ?BSTR, targetName: ?BSTR, userName: ?BSTR, userDomain: ?BSTR, poolName: ?BSTR, initialProgram: ?BSTR, pSessionState: ?*TSSESSION_STATE, pdwCount: ?*u32, ppVal: [*]?*?*ITsSbSession) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGlobalStore.VTable, self.vtable).EnumerateSessions(@ptrCast(*const ITsSbGlobalStore, self), ProviderName, targetName, userName, userDomain, poolName, initialProgram, pSessionState, pdwCount, ppVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbGlobalStore_GetFarmProperty(self: *const T, farmName: ?BSTR, propertyName: ?BSTR, pVarValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGlobalStore.VTable, self.vtable).GetFarmProperty(@ptrCast(*const ITsSbGlobalStore, self), farmName, propertyName, pVarValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbProvisioningPluginNotifySink_Value = Guid.initString("aca87a8e-818b-4581-a032-49c3dfb9c701"); pub const IID_ITsSbProvisioningPluginNotifySink = &IID_ITsSbProvisioningPluginNotifySink_Value; pub const ITsSbProvisioningPluginNotifySink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnJobCreated: fn( self: *const ITsSbProvisioningPluginNotifySink, pVmNotifyInfo: ?*VM_NOTIFY_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnVirtualMachineStatusChanged: fn( self: *const ITsSbProvisioningPluginNotifySink, pVmNotifyEntry: ?*VM_NOTIFY_ENTRY, VmNotifyStatus: VM_NOTIFY_STATUS, ErrorCode: HRESULT, ErrorDescr: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnJobCompleted: fn( self: *const ITsSbProvisioningPluginNotifySink, ResultCode: HRESULT, ResultDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnJobCancelled: fn( self: *const ITsSbProvisioningPluginNotifySink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LockVirtualMachine: fn( self: *const ITsSbProvisioningPluginNotifySink, pVmNotifyEntry: ?*VM_NOTIFY_ENTRY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnVirtualMachineHostStatusChanged: fn( self: *const ITsSbProvisioningPluginNotifySink, VmHost: ?BSTR, VmHostNotifyStatus: VM_HOST_NOTIFY_STATUS, ErrorCode: HRESULT, ErrorDescr: ?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 ITsSbProvisioningPluginNotifySink_OnJobCreated(self: *const T, pVmNotifyInfo: ?*VM_NOTIFY_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioningPluginNotifySink.VTable, self.vtable).OnJobCreated(@ptrCast(*const ITsSbProvisioningPluginNotifySink, self), pVmNotifyInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioningPluginNotifySink_OnVirtualMachineStatusChanged(self: *const T, pVmNotifyEntry: ?*VM_NOTIFY_ENTRY, VmNotifyStatus: VM_NOTIFY_STATUS, ErrorCode: HRESULT, ErrorDescr: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioningPluginNotifySink.VTable, self.vtable).OnVirtualMachineStatusChanged(@ptrCast(*const ITsSbProvisioningPluginNotifySink, self), pVmNotifyEntry, VmNotifyStatus, ErrorCode, ErrorDescr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioningPluginNotifySink_OnJobCompleted(self: *const T, ResultCode: HRESULT, ResultDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioningPluginNotifySink.VTable, self.vtable).OnJobCompleted(@ptrCast(*const ITsSbProvisioningPluginNotifySink, self), ResultCode, ResultDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioningPluginNotifySink_OnJobCancelled(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioningPluginNotifySink.VTable, self.vtable).OnJobCancelled(@ptrCast(*const ITsSbProvisioningPluginNotifySink, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioningPluginNotifySink_LockVirtualMachine(self: *const T, pVmNotifyEntry: ?*VM_NOTIFY_ENTRY) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioningPluginNotifySink.VTable, self.vtable).LockVirtualMachine(@ptrCast(*const ITsSbProvisioningPluginNotifySink, self), pVmNotifyEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioningPluginNotifySink_OnVirtualMachineHostStatusChanged(self: *const T, VmHost: ?BSTR, VmHostNotifyStatus: VM_HOST_NOTIFY_STATUS, ErrorCode: HRESULT, ErrorDescr: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioningPluginNotifySink.VTable, self.vtable).OnVirtualMachineHostStatusChanged(@ptrCast(*const ITsSbProvisioningPluginNotifySink, self), VmHost, VmHostNotifyStatus, ErrorCode, ErrorDescr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_ITsSbProvisioning_Value = Guid.initString("2f6f0dbb-9e4f-462b-9c3f-fccc3dcb6232"); pub const IID_ITsSbProvisioning = &IID_ITsSbProvisioning_Value; pub const ITsSbProvisioning = extern struct { pub const VTable = extern struct { base: ITsSbPlugin.VTable, CreateVirtualMachines: fn( self: *const ITsSbProvisioning, JobXmlString: ?BSTR, JobGuid: ?BSTR, pSink: ?*ITsSbProvisioningPluginNotifySink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PatchVirtualMachines: fn( self: *const ITsSbProvisioning, JobXmlString: ?BSTR, JobGuid: ?BSTR, pSink: ?*ITsSbProvisioningPluginNotifySink, pVMPatchInfo: ?*VM_PATCH_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteVirtualMachines: fn( self: *const ITsSbProvisioning, JobXmlString: ?BSTR, JobGuid: ?BSTR, pSink: ?*ITsSbProvisioningPluginNotifySink, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelJob: fn( self: *const ITsSbProvisioning, JobGuid: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ITsSbPlugin.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioning_CreateVirtualMachines(self: *const T, JobXmlString: ?BSTR, JobGuid: ?BSTR, pSink: ?*ITsSbProvisioningPluginNotifySink) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioning.VTable, self.vtable).CreateVirtualMachines(@ptrCast(*const ITsSbProvisioning, self), JobXmlString, JobGuid, pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioning_PatchVirtualMachines(self: *const T, JobXmlString: ?BSTR, JobGuid: ?BSTR, pSink: ?*ITsSbProvisioningPluginNotifySink, pVMPatchInfo: ?*VM_PATCH_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioning.VTable, self.vtable).PatchVirtualMachines(@ptrCast(*const ITsSbProvisioning, self), JobXmlString, JobGuid, pSink, pVMPatchInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioning_DeleteVirtualMachines(self: *const T, JobXmlString: ?BSTR, JobGuid: ?BSTR, pSink: ?*ITsSbProvisioningPluginNotifySink) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioning.VTable, self.vtable).DeleteVirtualMachines(@ptrCast(*const ITsSbProvisioning, self), JobXmlString, JobGuid, pSink); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbProvisioning_CancelJob(self: *const T, JobGuid: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbProvisioning.VTable, self.vtable).CancelJob(@ptrCast(*const ITsSbProvisioning, self), JobGuid); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2016' const IID_ITsSbGenericNotifySink_Value = Guid.initString("4c4c8c4f-300b-46ad-9164-8468a7e7568c"); pub const IID_ITsSbGenericNotifySink = &IID_ITsSbGenericNotifySink_Value; pub const ITsSbGenericNotifySink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnCompleted: fn( self: *const ITsSbGenericNotifySink, Status: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWaitTimeout: fn( self: *const ITsSbGenericNotifySink, pftTimeout: ?*FILETIME, ) 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 ITsSbGenericNotifySink_OnCompleted(self: *const T, Status: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGenericNotifySink.VTable, self.vtable).OnCompleted(@ptrCast(*const ITsSbGenericNotifySink, self), Status); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITsSbGenericNotifySink_GetWaitTimeout(self: *const T, pftTimeout: ?*FILETIME) callconv(.Inline) HRESULT { return @ptrCast(*const ITsSbGenericNotifySink.VTable, self.vtable).GetWaitTimeout(@ptrCast(*const ITsSbGenericNotifySink, self), pftTimeout); } };} pub usingnamespace MethodMixin(@This()); }; pub const pluginResource = extern struct { alias: [256]u16, name: [256]u16, resourceFileContents: ?PWSTR, fileExtension: [256]u16, resourcePluginType: [256]u16, isDiscoverable: u8, resourceType: i32, pceIconSize: u32, iconContents: ?*u8, pcePluginBlobSize: u32, blobContents: ?*u8, }; // TODO: this type is limited to platform 'windowsServer2008' const IID_ItsPubPlugin_Value = Guid.initString("70c04b05-f347-412b-822f-36c99c54ca45"); pub const IID_ItsPubPlugin = &IID_ItsPubPlugin_Value; pub const ItsPubPlugin = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetResourceList: fn( self: *const ItsPubPlugin, userID: ?[*:0]const u16, pceAppListSize: ?*i32, resourceList: ?*?*pluginResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetResource: fn( self: *const ItsPubPlugin, alias: ?[*:0]const u16, flags: i32, resource: ?*pluginResource, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCacheLastUpdateTime: fn( self: *const ItsPubPlugin, lastUpdateTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_pluginName: fn( self: *const ItsPubPlugin, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_pluginVersion: fn( self: *const ItsPubPlugin, pVal: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolveResource: fn( self: *const ItsPubPlugin, resourceType: ?*u32, resourceLocation: ?PWSTR, endPointName: ?PWSTR, userID: ?PWSTR, alias: ?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 ItsPubPlugin_GetResourceList(self: *const T, userID: ?[*:0]const u16, pceAppListSize: ?*i32, resourceList: ?*?*pluginResource) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin.VTable, self.vtable).GetResourceList(@ptrCast(*const ItsPubPlugin, self), userID, pceAppListSize, resourceList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin_GetResource(self: *const T, alias: ?[*:0]const u16, flags: i32, resource: ?*pluginResource) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin.VTable, self.vtable).GetResource(@ptrCast(*const ItsPubPlugin, self), alias, flags, resource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin_GetCacheLastUpdateTime(self: *const T, lastUpdateTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin.VTable, self.vtable).GetCacheLastUpdateTime(@ptrCast(*const ItsPubPlugin, self), lastUpdateTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin_get_pluginName(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin.VTable, self.vtable).get_pluginName(@ptrCast(*const ItsPubPlugin, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin_get_pluginVersion(self: *const T, pVal: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin.VTable, self.vtable).get_pluginVersion(@ptrCast(*const ItsPubPlugin, self), pVal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin_ResolveResource(self: *const T, resourceType: ?*u32, resourceLocation: ?PWSTR, endPointName: ?PWSTR, userID: ?PWSTR, alias: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin.VTable, self.vtable).ResolveResource(@ptrCast(*const ItsPubPlugin, self), resourceType, resourceLocation, endPointName, userID, alias); } };} pub usingnamespace MethodMixin(@This()); }; pub const pluginResource2FileAssociation = extern struct { extName: [256]u16, primaryHandler: u8, pceIconSize: u32, iconContents: ?*u8, }; pub const pluginResource2 = extern struct { resourceV1: pluginResource, pceFileAssocListSize: u32, fileAssocList: ?*pluginResource2FileAssociation, securityDescriptor: ?PWSTR, pceFolderListSize: u32, folderList: ?*?*u16, }; pub const TSPUB_PLUGIN_PD_RESOLUTION_TYPE = enum(i32) { OR_CREATE = 0, EXISTING = 1, }; pub const TSPUB_PLUGIN_PD_QUERY_OR_CREATE = TSPUB_PLUGIN_PD_RESOLUTION_TYPE.OR_CREATE; pub const TSPUB_PLUGIN_PD_QUERY_EXISTING = TSPUB_PLUGIN_PD_RESOLUTION_TYPE.EXISTING; pub const TSPUB_PLUGIN_PD_ASSIGNMENT_TYPE = enum(i32) { NEW = 0, EXISTING = 1, }; pub const TSPUB_PLUGIN_PD_ASSIGNMENT_NEW = TSPUB_PLUGIN_PD_ASSIGNMENT_TYPE.NEW; pub const TSPUB_PLUGIN_PD_ASSIGNMENT_EXISTING = TSPUB_PLUGIN_PD_ASSIGNMENT_TYPE.EXISTING; // TODO: this type is limited to platform 'windows8.0' const IID_ItsPubPlugin2_Value = Guid.initString("fa4ce418-aad7-4ec6-bad1-0a321ba465d5"); pub const IID_ItsPubPlugin2 = &IID_ItsPubPlugin2_Value; pub const ItsPubPlugin2 = extern struct { pub const VTable = extern struct { base: ItsPubPlugin.VTable, GetResource2List: fn( self: *const ItsPubPlugin2, userID: ?[*:0]const u16, pceAppListSize: ?*i32, resourceList: ?*?*pluginResource2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetResource2: fn( self: *const ItsPubPlugin2, alias: ?[*:0]const u16, flags: i32, resource: ?*pluginResource2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResolvePersonalDesktop: fn( self: *const ItsPubPlugin2, userId: ?[*:0]const u16, poolId: ?[*:0]const u16, ePdResolutionType: TSPUB_PLUGIN_PD_RESOLUTION_TYPE, pPdAssignmentType: ?*TSPUB_PLUGIN_PD_ASSIGNMENT_TYPE, endPointName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeletePersonalDesktopAssignment: fn( self: *const ItsPubPlugin2, userId: ?[*:0]const u16, poolId: ?[*:0]const u16, endpointName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace ItsPubPlugin.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin2_GetResource2List(self: *const T, userID: ?[*:0]const u16, pceAppListSize: ?*i32, resourceList: ?*?*pluginResource2) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin2.VTable, self.vtable).GetResource2List(@ptrCast(*const ItsPubPlugin2, self), userID, pceAppListSize, resourceList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin2_GetResource2(self: *const T, alias: ?[*:0]const u16, flags: i32, resource: ?*pluginResource2) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin2.VTable, self.vtable).GetResource2(@ptrCast(*const ItsPubPlugin2, self), alias, flags, resource); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin2_ResolvePersonalDesktop(self: *const T, userId: ?[*:0]const u16, poolId: ?[*:0]const u16, ePdResolutionType: TSPUB_PLUGIN_PD_RESOLUTION_TYPE, pPdAssignmentType: ?*TSPUB_PLUGIN_PD_ASSIGNMENT_TYPE, endPointName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin2.VTable, self.vtable).ResolvePersonalDesktop(@ptrCast(*const ItsPubPlugin2, self), userId, poolId, ePdResolutionType, pPdAssignmentType, endPointName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ItsPubPlugin2_DeletePersonalDesktopAssignment(self: *const T, userId: ?[*:0]const u16, poolId: ?[*:0]const u16, endpointName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const ItsPubPlugin2.VTable, self.vtable).DeletePersonalDesktopAssignment(@ptrCast(*const ItsPubPlugin2, self), userId, poolId, endpointName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IWorkspaceResTypeRegistry_Value = Guid.initString("1d428c79-6e2e-4351-a361-c0401a03a0ba"); pub const IID_IWorkspaceResTypeRegistry = &IID_IWorkspaceResTypeRegistry_Value; pub const IWorkspaceResTypeRegistry = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, AddResourceType: fn( self: *const IWorkspaceResTypeRegistry, fMachineWide: i16, bstrFileExtension: ?BSTR, bstrLauncher: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteResourceType: fn( self: *const IWorkspaceResTypeRegistry, fMachineWide: i16, bstrFileExtension: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRegisteredFileExtensions: fn( self: *const IWorkspaceResTypeRegistry, fMachineWide: i16, psaFileExtensions: ?*?*SAFEARRAY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetResourceTypeInfo: fn( self: *const IWorkspaceResTypeRegistry, fMachineWide: i16, bstrFileExtension: ?BSTR, pbstrLauncher: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ModifyResourceType: fn( self: *const IWorkspaceResTypeRegistry, fMachineWide: i16, bstrFileExtension: ?BSTR, bstrLauncher: ?BSTR, ) 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 IWorkspaceResTypeRegistry_AddResourceType(self: *const T, fMachineWide: i16, bstrFileExtension: ?BSTR, bstrLauncher: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceResTypeRegistry.VTable, self.vtable).AddResourceType(@ptrCast(*const IWorkspaceResTypeRegistry, self), fMachineWide, bstrFileExtension, bstrLauncher); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceResTypeRegistry_DeleteResourceType(self: *const T, fMachineWide: i16, bstrFileExtension: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceResTypeRegistry.VTable, self.vtable).DeleteResourceType(@ptrCast(*const IWorkspaceResTypeRegistry, self), fMachineWide, bstrFileExtension); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceResTypeRegistry_GetRegisteredFileExtensions(self: *const T, fMachineWide: i16, psaFileExtensions: ?*?*SAFEARRAY) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceResTypeRegistry.VTable, self.vtable).GetRegisteredFileExtensions(@ptrCast(*const IWorkspaceResTypeRegistry, self), fMachineWide, psaFileExtensions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceResTypeRegistry_GetResourceTypeInfo(self: *const T, fMachineWide: i16, bstrFileExtension: ?BSTR, pbstrLauncher: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceResTypeRegistry.VTable, self.vtable).GetResourceTypeInfo(@ptrCast(*const IWorkspaceResTypeRegistry, self), fMachineWide, bstrFileExtension, pbstrLauncher); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWorkspaceResTypeRegistry_ModifyResourceType(self: *const T, fMachineWide: i16, bstrFileExtension: ?BSTR, bstrLauncher: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWorkspaceResTypeRegistry.VTable, self.vtable).ModifyResourceType(@ptrCast(*const IWorkspaceResTypeRegistry, self), fMachineWide, bstrFileExtension, bstrLauncher); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWTSPlugin_Value = Guid.initString("a1230201-1439-4e62-a414-190d0ac3d40e"); pub const IID_IWTSPlugin = &IID_IWTSPlugin_Value; pub const IWTSPlugin = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWTSPlugin, pChannelMgr: ?*IWTSVirtualChannelManager, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Connected: fn( self: *const IWTSPlugin, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Disconnected: fn( self: *const IWTSPlugin, dwDisconnectCode: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Terminated: fn( self: *const IWTSPlugin, ) 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 IWTSPlugin_Initialize(self: *const T, pChannelMgr: ?*IWTSVirtualChannelManager) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSPlugin.VTable, self.vtable).Initialize(@ptrCast(*const IWTSPlugin, self), pChannelMgr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSPlugin_Connected(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSPlugin.VTable, self.vtable).Connected(@ptrCast(*const IWTSPlugin, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSPlugin_Disconnected(self: *const T, dwDisconnectCode: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSPlugin.VTable, self.vtable).Disconnected(@ptrCast(*const IWTSPlugin, self), dwDisconnectCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSPlugin_Terminated(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSPlugin.VTable, self.vtable).Terminated(@ptrCast(*const IWTSPlugin, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWTSListener_Value = Guid.initString("a1230206-9a39-4d58-8674-cdb4dff4e73b"); pub const IID_IWTSListener = &IID_IWTSListener_Value; pub const IWTSListener = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetConfiguration: fn( self: *const IWTSListener, ppPropertyBag: ?*?*IPropertyBag, ) 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 IWTSListener_GetConfiguration(self: *const T, ppPropertyBag: ?*?*IPropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSListener.VTable, self.vtable).GetConfiguration(@ptrCast(*const IWTSListener, self), ppPropertyBag); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWTSListenerCallback_Value = Guid.initString("a1230203-d6a7-11d8-b9fd-000bdbd1f198"); pub const IID_IWTSListenerCallback = &IID_IWTSListenerCallback_Value; pub const IWTSListenerCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnNewChannelConnection: fn( self: *const IWTSListenerCallback, pChannel: ?*IWTSVirtualChannel, data: ?BSTR, pbAccept: ?*BOOL, ppCallback: ?*?*IWTSVirtualChannelCallback, ) 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 IWTSListenerCallback_OnNewChannelConnection(self: *const T, pChannel: ?*IWTSVirtualChannel, data: ?BSTR, pbAccept: ?*BOOL, ppCallback: ?*?*IWTSVirtualChannelCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSListenerCallback.VTable, self.vtable).OnNewChannelConnection(@ptrCast(*const IWTSListenerCallback, self), pChannel, data, pbAccept, ppCallback); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWTSVirtualChannelCallback_Value = Guid.initString("a1230204-d6a7-11d8-b9fd-000bdbd1f198"); pub const IID_IWTSVirtualChannelCallback = &IID_IWTSVirtualChannelCallback_Value; pub const IWTSVirtualChannelCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnDataReceived: fn( self: *const IWTSVirtualChannelCallback, cbSize: u32, pBuffer: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnClose: fn( self: *const IWTSVirtualChannelCallback, ) 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 IWTSVirtualChannelCallback_OnDataReceived(self: *const T, cbSize: u32, pBuffer: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSVirtualChannelCallback.VTable, self.vtable).OnDataReceived(@ptrCast(*const IWTSVirtualChannelCallback, self), cbSize, pBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSVirtualChannelCallback_OnClose(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSVirtualChannelCallback.VTable, self.vtable).OnClose(@ptrCast(*const IWTSVirtualChannelCallback, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWTSVirtualChannelManager_Value = Guid.initString("a1230205-d6a7-11d8-b9fd-000bdbd1f198"); pub const IID_IWTSVirtualChannelManager = &IID_IWTSVirtualChannelManager_Value; pub const IWTSVirtualChannelManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateListener: fn( self: *const IWTSVirtualChannelManager, pszChannelName: ?*const u8, uFlags: u32, pListenerCallback: ?*IWTSListenerCallback, ppListener: ?*?*IWTSListener, ) 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 IWTSVirtualChannelManager_CreateListener(self: *const T, pszChannelName: ?*const u8, uFlags: u32, pListenerCallback: ?*IWTSListenerCallback, ppListener: ?*?*IWTSListener) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSVirtualChannelManager.VTable, self.vtable).CreateListener(@ptrCast(*const IWTSVirtualChannelManager, self), pszChannelName, uFlags, pListenerCallback, ppListener); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IWTSVirtualChannel_Value = Guid.initString("a1230207-d6a7-11d8-b9fd-000bdbd1f198"); pub const IID_IWTSVirtualChannel = &IID_IWTSVirtualChannel_Value; pub const IWTSVirtualChannel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Write: fn( self: *const IWTSVirtualChannel, cbSize: u32, pBuffer: [*:0]u8, pReserved: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWTSVirtualChannel, ) 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 IWTSVirtualChannel_Write(self: *const T, cbSize: u32, pBuffer: [*:0]u8, pReserved: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSVirtualChannel.VTable, self.vtable).Write(@ptrCast(*const IWTSVirtualChannel, self), cbSize, pBuffer, pReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSVirtualChannel_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSVirtualChannel.VTable, self.vtable).Close(@ptrCast(*const IWTSVirtualChannel, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWTSPluginServiceProvider_Value = Guid.initString("d3e07363-087c-476c-86a7-dbb15f46ddb4"); pub const IID_IWTSPluginServiceProvider = &IID_IWTSPluginServiceProvider_Value; pub const IWTSPluginServiceProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetService: fn( self: *const IWTSPluginServiceProvider, ServiceId: Guid, ppunkObject: ?*?*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 IWTSPluginServiceProvider_GetService(self: *const T, ServiceId: Guid, ppunkObject: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSPluginServiceProvider.VTable, self.vtable).GetService(@ptrCast(*const IWTSPluginServiceProvider, self), ServiceId, ppunkObject); } };} pub usingnamespace MethodMixin(@This()); }; pub const BITMAP_RENDERER_STATISTICS = extern struct { dwFramesDelivered: u32, dwFramesDropped: u32, }; // TODO: this type is limited to platform 'windows8.0' const IID_IWTSBitmapRenderer_Value = Guid.initString("5b7acc97-f3c9-46f7-8c5b-fa685d3441b1"); pub const IID_IWTSBitmapRenderer = &IID_IWTSBitmapRenderer_Value; pub const IWTSBitmapRenderer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Render: fn( self: *const IWTSBitmapRenderer, imageFormat: Guid, dwWidth: u32, dwHeight: u32, cbStride: i32, cbImageBuffer: u32, pImageBuffer: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRendererStatistics: fn( self: *const IWTSBitmapRenderer, pStatistics: ?*BITMAP_RENDERER_STATISTICS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveMapping: fn( self: *const IWTSBitmapRenderer, ) 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 IWTSBitmapRenderer_Render(self: *const T, imageFormat: Guid, dwWidth: u32, dwHeight: u32, cbStride: i32, cbImageBuffer: u32, pImageBuffer: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSBitmapRenderer.VTable, self.vtable).Render(@ptrCast(*const IWTSBitmapRenderer, self), imageFormat, dwWidth, dwHeight, cbStride, cbImageBuffer, pImageBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSBitmapRenderer_GetRendererStatistics(self: *const T, pStatistics: ?*BITMAP_RENDERER_STATISTICS) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSBitmapRenderer.VTable, self.vtable).GetRendererStatistics(@ptrCast(*const IWTSBitmapRenderer, self), pStatistics); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSBitmapRenderer_RemoveMapping(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSBitmapRenderer.VTable, self.vtable).RemoveMapping(@ptrCast(*const IWTSBitmapRenderer, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWTSBitmapRendererCallback_Value = Guid.initString("d782928e-fe4e-4e77-ae90-9cd0b3e3b353"); pub const IID_IWTSBitmapRendererCallback = &IID_IWTSBitmapRendererCallback_Value; pub const IWTSBitmapRendererCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnTargetSizeChanged: fn( self: *const IWTSBitmapRendererCallback, rcNewSize: RECT, ) 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 IWTSBitmapRendererCallback_OnTargetSizeChanged(self: *const T, rcNewSize: RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSBitmapRendererCallback.VTable, self.vtable).OnTargetSizeChanged(@ptrCast(*const IWTSBitmapRendererCallback, self), rcNewSize); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWTSBitmapRenderService_Value = Guid.initString("ea326091-05fe-40c1-b49c-3d2ef4626a0e"); pub const IID_IWTSBitmapRenderService = &IID_IWTSBitmapRenderService_Value; pub const IWTSBitmapRenderService = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetMappedRenderer: fn( self: *const IWTSBitmapRenderService, mappingId: u64, pMappedRendererCallback: ?*IWTSBitmapRendererCallback, ppMappedRenderer: ?*?*IWTSBitmapRenderer, ) 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 IWTSBitmapRenderService_GetMappedRenderer(self: *const T, mappingId: u64, pMappedRendererCallback: ?*IWTSBitmapRendererCallback, ppMappedRenderer: ?*?*IWTSBitmapRenderer) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSBitmapRenderService.VTable, self.vtable).GetMappedRenderer(@ptrCast(*const IWTSBitmapRenderService, self), mappingId, pMappedRendererCallback, ppMappedRenderer); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWRdsGraphicsChannelEvents_Value = Guid.initString("67f2368c-d674-4fae-66a5-d20628a640d2"); pub const IID_IWRdsGraphicsChannelEvents = &IID_IWRdsGraphicsChannelEvents_Value; pub const IWRdsGraphicsChannelEvents = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnDataReceived: fn( self: *const IWRdsGraphicsChannelEvents, cbSize: u32, pBuffer: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnClose: fn( self: *const IWRdsGraphicsChannelEvents, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnChannelOpened: fn( self: *const IWRdsGraphicsChannelEvents, OpenResult: HRESULT, pOpenContext: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDataSent: fn( self: *const IWRdsGraphicsChannelEvents, pWriteContext: ?*IUnknown, bCancelled: BOOL, pBuffer: ?*u8, cbBuffer: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnMetricsUpdate: fn( self: *const IWRdsGraphicsChannelEvents, bandwidth: u32, RTT: u32, lastSentByteIndex: u64, ) 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 IWRdsGraphicsChannelEvents_OnDataReceived(self: *const T, cbSize: u32, pBuffer: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannelEvents.VTable, self.vtable).OnDataReceived(@ptrCast(*const IWRdsGraphicsChannelEvents, self), cbSize, pBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsGraphicsChannelEvents_OnClose(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannelEvents.VTable, self.vtable).OnClose(@ptrCast(*const IWRdsGraphicsChannelEvents, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsGraphicsChannelEvents_OnChannelOpened(self: *const T, OpenResult: HRESULT, pOpenContext: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannelEvents.VTable, self.vtable).OnChannelOpened(@ptrCast(*const IWRdsGraphicsChannelEvents, self), OpenResult, pOpenContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsGraphicsChannelEvents_OnDataSent(self: *const T, pWriteContext: ?*IUnknown, bCancelled: BOOL, pBuffer: ?*u8, cbBuffer: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannelEvents.VTable, self.vtable).OnDataSent(@ptrCast(*const IWRdsGraphicsChannelEvents, self), pWriteContext, bCancelled, pBuffer, cbBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsGraphicsChannelEvents_OnMetricsUpdate(self: *const T, bandwidth: u32, RTT: u32, lastSentByteIndex: u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannelEvents.VTable, self.vtable).OnMetricsUpdate(@ptrCast(*const IWRdsGraphicsChannelEvents, self), bandwidth, RTT, lastSentByteIndex); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IWRdsGraphicsChannel_Value = Guid.initString("684b7a0b-edff-43ad-d5a2-4a8d5388f401"); pub const IID_IWRdsGraphicsChannel = &IID_IWRdsGraphicsChannel_Value; pub const IWRdsGraphicsChannel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Write: fn( self: *const IWRdsGraphicsChannel, cbSize: u32, pBuffer: ?*u8, pContext: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWRdsGraphicsChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Open: fn( self: *const IWRdsGraphicsChannel, pChannelEvents: ?*IWRdsGraphicsChannelEvents, pOpenContext: ?*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 IWRdsGraphicsChannel_Write(self: *const T, cbSize: u32, pBuffer: ?*u8, pContext: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannel.VTable, self.vtable).Write(@ptrCast(*const IWRdsGraphicsChannel, self), cbSize, pBuffer, pContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsGraphicsChannel_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannel.VTable, self.vtable).Close(@ptrCast(*const IWRdsGraphicsChannel, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsGraphicsChannel_Open(self: *const T, pChannelEvents: ?*IWRdsGraphicsChannelEvents, pOpenContext: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannel.VTable, self.vtable).Open(@ptrCast(*const IWRdsGraphicsChannel, self), pChannelEvents, pOpenContext); } };} pub usingnamespace MethodMixin(@This()); }; pub const WRdsGraphicsChannelType = enum(i32) { GuaranteedDelivery = 0, BestEffortDelivery = 1, }; pub const WRdsGraphicsChannelType_GuaranteedDelivery = WRdsGraphicsChannelType.GuaranteedDelivery; pub const WRdsGraphicsChannelType_BestEffortDelivery = WRdsGraphicsChannelType.BestEffortDelivery; // TODO: this type is limited to platform 'windows8.0' const IID_IWRdsGraphicsChannelManager_Value = Guid.initString("0fd57159-e83e-476a-a8b9-4a7976e71e18"); pub const IID_IWRdsGraphicsChannelManager = &IID_IWRdsGraphicsChannelManager_Value; pub const IWRdsGraphicsChannelManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateChannel: fn( self: *const IWRdsGraphicsChannelManager, pszChannelName: ?*const u8, channelType: WRdsGraphicsChannelType, ppVirtualChannel: ?*?*IWRdsGraphicsChannel, ) 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 IWRdsGraphicsChannelManager_CreateChannel(self: *const T, pszChannelName: ?*const u8, channelType: WRdsGraphicsChannelType, ppVirtualChannel: ?*?*IWRdsGraphicsChannel) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsGraphicsChannelManager.VTable, self.vtable).CreateChannel(@ptrCast(*const IWRdsGraphicsChannelManager, self), pszChannelName, channelType, ppVirtualChannel); } };} pub usingnamespace MethodMixin(@This()); }; pub const RFX_GFX_RECT = packed struct { left: i32, top: i32, right: i32, bottom: i32, }; pub const RFX_GFX_MSG_HEADER = packed struct { uMSGType: u16, cbSize: u16, }; pub const RFX_GFX_MONITOR_INFO = packed struct { left: i32, top: i32, right: i32, bottom: i32, physicalWidth: u32, physicalHeight: u32, orientation: u32, primary: BOOL, }; pub const RFX_GFX_MSG_CLIENT_DESKTOP_INFO_REQUEST = extern struct { channelHdr: RFX_GFX_MSG_HEADER, }; pub const RFX_GFX_MSG_CLIENT_DESKTOP_INFO_RESPONSE = packed struct { channelHdr: RFX_GFX_MSG_HEADER, reserved: u32, monitorCount: u32, MonitorData: [16]RFX_GFX_MONITOR_INFO, clientUniqueId: [32]u16, }; pub const RFX_GFX_MSG_DESKTOP_CONFIG_CHANGE_NOTIFY = packed struct { channelHdr: RFX_GFX_MSG_HEADER, ulWidth: u32, ulHeight: u32, ulBpp: u32, Reserved: u32, }; pub const RFX_GFX_MSG_DESKTOP_CONFIG_CHANGE_CONFIRM = extern struct { channelHdr: RFX_GFX_MSG_HEADER, }; pub const RFX_GFX_MSG_DESKTOP_INPUT_RESET = packed struct { channelHdr: RFX_GFX_MSG_HEADER, ulWidth: u32, ulHeight: u32, }; pub const RFX_GFX_MSG_DISCONNECT_NOTIFY = packed struct { channelHdr: RFX_GFX_MSG_HEADER, DisconnectReason: u32, }; pub const RFX_GFX_MSG_DESKTOP_RESEND_REQUEST = extern struct { channelHdr: RFX_GFX_MSG_HEADER, RedrawRect: RFX_GFX_RECT, }; pub const RFX_GFX_MSG_RDP_DATA = extern struct { channelHdr: RFX_GFX_MSG_HEADER, rdpData: [1]u8, }; pub const WTS_SOCKADDR = extern struct { sin_family: u16, u: extern union { ipv4: extern struct { sin_port: u16, IN_ADDR: u32, sin_zero: [8]u8, }, ipv6: extern struct { sin6_port: u16, sin6_flowinfo: u32, sin6_addr: [8]u16, sin6_scope_id: u32, }, }, }; pub const WTS_SMALL_RECT = extern struct { Left: i16, Top: i16, Right: i16, Bottom: i16, }; pub const WTS_RCM_SERVICE_STATE = enum(i32) { NONE = 0, START = 1, STOP = 2, }; pub const WTS_SERVICE_NONE = WTS_RCM_SERVICE_STATE.NONE; pub const WTS_SERVICE_START = WTS_RCM_SERVICE_STATE.START; pub const WTS_SERVICE_STOP = WTS_RCM_SERVICE_STATE.STOP; pub const WTS_RCM_DRAIN_STATE = enum(i32) { STATE_NONE = 0, IN_DRAIN = 1, NOT_IN_DRAIN = 2, }; pub const WTS_DRAIN_STATE_NONE = WTS_RCM_DRAIN_STATE.STATE_NONE; pub const WTS_DRAIN_IN_DRAIN = WTS_RCM_DRAIN_STATE.IN_DRAIN; pub const WTS_DRAIN_NOT_IN_DRAIN = WTS_RCM_DRAIN_STATE.NOT_IN_DRAIN; pub const WTS_SERVICE_STATE = extern struct { RcmServiceState: WTS_RCM_SERVICE_STATE, RcmDrainState: WTS_RCM_DRAIN_STATE, }; pub const WTS_SESSION_ID = extern struct { SessionUniqueGuid: Guid, SessionId: u32, }; pub const WTS_USER_CREDENTIAL = extern struct { UserName: [256]u16, Password: [<PASSWORD>, Domain: [256]u16, }; pub const WTS_SYSTEMTIME = extern struct { wYear: u16, wMonth: u16, wDayOfWeek: u16, wDay: u16, wHour: u16, wMinute: u16, wSecond: u16, wMilliseconds: u16, }; pub const WTS_TIME_ZONE_INFORMATION = extern struct { Bias: i32, StandardName: [32]u16, StandardDate: WTS_SYSTEMTIME, StandardBias: i32, DaylightName: [32]u16, DaylightDate: WTS_SYSTEMTIME, DaylightBias: i32, }; pub const WRDS_DYNAMIC_TIME_ZONE_INFORMATION = extern struct { Bias: i32, StandardName: [32]u16, StandardDate: WTS_SYSTEMTIME, StandardBias: i32, DaylightName: [32]u16, DaylightDate: WTS_SYSTEMTIME, DaylightBias: i32, TimeZoneKeyName: [128]u16, DynamicDaylightTimeDisabled: u16, }; pub const WTS_CLIENT_DATA = extern struct { fDisableCtrlAltDel: BOOLEAN, fDoubleClickDetect: BOOLEAN, fEnableWindowsKey: BOOLEAN, fHideTitleBar: BOOLEAN, fInheritAutoLogon: BOOL, fPromptForPassword: BOOLEAN, fUsingSavedCreds: BOOLEAN, Domain: [256]u16, UserName: [256]u16, Password: [<PASSWORD>, fPasswordIsScPin: BOOLEAN, fInheritInitialProgram: BOOL, WorkDirectory: [257]u16, InitialProgram: [257]u16, fMaximizeShell: BOOLEAN, EncryptionLevel: u8, PerformanceFlags: u32, ProtocolName: [9]u16, ProtocolType: u16, fInheritColorDepth: BOOL, HRes: u16, VRes: u16, ColorDepth: u16, DisplayDriverName: [9]u16, DisplayDeviceName: [20]u16, fMouse: BOOLEAN, KeyboardLayout: u32, KeyboardType: u32, KeyboardSubType: u32, KeyboardFunctionKey: u32, imeFileName: [33]u16, ActiveInputLocale: u32, fNoAudioPlayback: BOOLEAN, fRemoteConsoleAudio: BOOLEAN, AudioDriverName: [9]u16, ClientTimeZone: WTS_TIME_ZONE_INFORMATION, ClientName: [21]u16, SerialNumber: u32, ClientAddressFamily: u32, ClientAddress: [31]u16, ClientSockAddress: WTS_SOCKADDR, ClientDirectory: [257]u16, ClientBuildNumber: u32, ClientProductId: u16, OutBufCountHost: u16, OutBufCountClient: u16, OutBufLength: u16, ClientSessionId: u32, ClientDigProductId: [33]u16, fDisableCpm: BOOLEAN, fDisableCdm: BOOLEAN, fDisableCcm: BOOLEAN, fDisableLPT: BOOLEAN, fDisableClip: BOOLEAN, fDisablePNP: BOOLEAN, }; pub const WTS_USER_DATA = extern struct { WorkDirectory: [257]u16, InitialProgram: [257]u16, UserTimeZone: WTS_TIME_ZONE_INFORMATION, }; pub const WTS_POLICY_DATA = extern struct { fDisableEncryption: BOOLEAN, fDisableAutoReconnect: BOOLEAN, ColorDepth: u32, MinEncryptionLevel: u8, fDisableCpm: BOOLEAN, fDisableCdm: BOOLEAN, fDisableCcm: BOOLEAN, fDisableLPT: BOOLEAN, fDisableClip: BOOLEAN, fDisablePNPRedir: BOOLEAN, }; pub const WTS_PROTOCOL_CACHE = extern struct { CacheReads: u32, CacheHits: u32, }; pub const WTS_CACHE_STATS_UN = extern union { ProtocolCache: [4]WTS_PROTOCOL_CACHE, TShareCacheStats: u32, Reserved: [20]u32, }; pub const WTS_CACHE_STATS = extern struct { Specific: u32, Data: WTS_CACHE_STATS_UN, ProtocolType: u16, Length: u16, }; pub const WTS_PROTOCOL_COUNTERS = extern struct { WdBytes: u32, WdFrames: u32, WaitForOutBuf: u32, Frames: u32, Bytes: u32, CompressedBytes: u32, CompressFlushes: u32, Errors: u32, Timeouts: u32, AsyncFramingError: u32, AsyncOverrunError: u32, AsyncOverflowError: u32, AsyncParityError: u32, TdErrors: u32, ProtocolType: u16, Length: u16, Specific: u16, Reserved: [100]u32, }; pub const WTS_PROTOCOL_STATUS = extern struct { Output: WTS_PROTOCOL_COUNTERS, Input: WTS_PROTOCOL_COUNTERS, Cache: WTS_CACHE_STATS, AsyncSignal: u32, AsyncSignalMask: u32, Counters: [100]LARGE_INTEGER, }; pub const WTS_DISPLAY_IOCTL = extern struct { pDisplayIOCtlData: [256]u8, cbDisplayIOCtlData: u32, }; pub const WTS_LOGON_ERROR_REDIRECTOR_RESPONSE = enum(i32) { INVALID = 0, NOT_HANDLED = 1, HANDLED_SHOW = 2, HANDLED_DONT_SHOW = 3, HANDLED_DONT_SHOW_START_OVER = 4, }; pub const WTS_LOGON_ERR_INVALID = WTS_LOGON_ERROR_REDIRECTOR_RESPONSE.INVALID; pub const WTS_LOGON_ERR_NOT_HANDLED = WTS_LOGON_ERROR_REDIRECTOR_RESPONSE.NOT_HANDLED; pub const WTS_LOGON_ERR_HANDLED_SHOW = WTS_LOGON_ERROR_REDIRECTOR_RESPONSE.HANDLED_SHOW; pub const WTS_LOGON_ERR_HANDLED_DONT_SHOW = WTS_LOGON_ERROR_REDIRECTOR_RESPONSE.HANDLED_DONT_SHOW; pub const WTS_LOGON_ERR_HANDLED_DONT_SHOW_START_OVER = WTS_LOGON_ERROR_REDIRECTOR_RESPONSE.HANDLED_DONT_SHOW_START_OVER; pub const WTS_PROPERTY_VALUE = extern struct { Type: u16, u: extern union { ulVal: u32, strVal: extern struct { size: u32, pstrVal: ?PWSTR, }, bVal: extern struct { size: u32, pbVal: ?PSTR, }, guidVal: Guid, }, }; pub const WTS_CERT_TYPE = enum(i32) { INVALID = 0, PROPRIETORY = 1, X509 = 2, }; pub const WTS_CERT_TYPE_INVALID = WTS_CERT_TYPE.INVALID; pub const WTS_CERT_TYPE_PROPRIETORY = WTS_CERT_TYPE.PROPRIETORY; pub const WTS_CERT_TYPE_X509 = WTS_CERT_TYPE.X509; pub const WTS_LICENSE_CAPABILITIES = extern struct { KeyExchangeAlg: u32, ProtocolVer: u32, fAuthenticateServer: BOOL, CertType: WTS_CERT_TYPE, cbClientName: u32, rgbClientName: [42]u8, }; pub const WRDS_CONNECTION_SETTING_LEVEL = enum(i32) { INVALID = 0, @"1" = 1, }; pub const WRDS_CONNECTION_SETTING_LEVEL_INVALID = WRDS_CONNECTION_SETTING_LEVEL.INVALID; pub const WRDS_CONNECTION_SETTING_LEVEL_1 = WRDS_CONNECTION_SETTING_LEVEL.@"1"; pub const WRDS_LISTENER_SETTING_LEVEL = enum(i32) { INVALID = 0, @"1" = 1, }; pub const WRDS_LISTENER_SETTING_LEVEL_INVALID = WRDS_LISTENER_SETTING_LEVEL.INVALID; pub const WRDS_LISTENER_SETTING_LEVEL_1 = WRDS_LISTENER_SETTING_LEVEL.@"1"; pub const WRDS_SETTING_TYPE = enum(i32) { INVALID = 0, MACHINE = 1, USER = 2, SAM = 3, }; pub const WRDS_SETTING_TYPE_INVALID = WRDS_SETTING_TYPE.INVALID; pub const WRDS_SETTING_TYPE_MACHINE = WRDS_SETTING_TYPE.MACHINE; pub const WRDS_SETTING_TYPE_USER = WRDS_SETTING_TYPE.USER; pub const WRDS_SETTING_TYPE_SAM = WRDS_SETTING_TYPE.SAM; pub const WRDS_SETTING_STATUS = enum(i32) { NOTAPPLICABLE = -1, DISABLED = 0, ENABLED = 1, NOTCONFIGURED = 2, }; pub const WRDS_SETTING_STATUS_NOTAPPLICABLE = WRDS_SETTING_STATUS.NOTAPPLICABLE; pub const WRDS_SETTING_STATUS_DISABLED = WRDS_SETTING_STATUS.DISABLED; pub const WRDS_SETTING_STATUS_ENABLED = WRDS_SETTING_STATUS.ENABLED; pub const WRDS_SETTING_STATUS_NOTCONFIGURED = WRDS_SETTING_STATUS.NOTCONFIGURED; pub const WRDS_SETTING_LEVEL = enum(i32) { INVALID = 0, @"1" = 1, }; pub const WRDS_SETTING_LEVEL_INVALID = WRDS_SETTING_LEVEL.INVALID; pub const WRDS_SETTING_LEVEL_1 = WRDS_SETTING_LEVEL.@"1"; pub const WRDS_LISTENER_SETTINGS_1 = extern struct { MaxProtocolListenerConnectionCount: u32, SecurityDescriptorSize: u32, pSecurityDescriptor: ?*u8, }; pub const WRDS_LISTENER_SETTING = extern union { WRdsListenerSettings1: WRDS_LISTENER_SETTINGS_1, }; pub const WRDS_LISTENER_SETTINGS = extern struct { WRdsListenerSettingLevel: WRDS_LISTENER_SETTING_LEVEL, WRdsListenerSetting: WRDS_LISTENER_SETTING, }; pub const WRDS_CONNECTION_SETTINGS_1 = extern struct { fInheritInitialProgram: BOOLEAN, fInheritColorDepth: BOOLEAN, fHideTitleBar: BOOLEAN, fInheritAutoLogon: BOOLEAN, fMaximizeShell: BOOLEAN, fDisablePNP: BOOLEAN, fPasswordIsScPin: BOOLEAN, fPromptForPassword: BOOLEAN, fDisableCpm: BOOLEAN, fDisableCdm: BOOLEAN, fDisableCcm: BOOLEAN, fDisableLPT: BOOLEAN, fDisableClip: BOOLEAN, fResetBroken: BOOLEAN, fDisableEncryption: BOOLEAN, fDisableAutoReconnect: BOOLEAN, fDisableCtrlAltDel: BOOLEAN, fDoubleClickDetect: BOOLEAN, fEnableWindowsKey: BOOLEAN, fUsingSavedCreds: BOOLEAN, fMouse: BOOLEAN, fNoAudioPlayback: BOOLEAN, fRemoteConsoleAudio: BOOLEAN, EncryptionLevel: u8, ColorDepth: u16, ProtocolType: u16, HRes: u16, VRes: u16, ClientProductId: u16, OutBufCountHost: u16, OutBufCountClient: u16, OutBufLength: u16, KeyboardLayout: u32, MaxConnectionTime: u32, MaxDisconnectionTime: u32, MaxIdleTime: u32, PerformanceFlags: u32, KeyboardType: u32, KeyboardSubType: u32, KeyboardFunctionKey: u32, ActiveInputLocale: u32, SerialNumber: u32, ClientAddressFamily: u32, ClientBuildNumber: u32, ClientSessionId: u32, WorkDirectory: [257]u16, InitialProgram: [257]u16, UserName: [256]u16, Domain: [256]u16, Password: <PASSWORD>, ProtocolName: [9]u16, DisplayDriverName: [9]u16, DisplayDeviceName: [20]u16, imeFileName: [33]u16, AudioDriverName: [9]u16, ClientName: [21]u16, ClientAddress: [31]u16, ClientDirectory: [257]u16, ClientDigProductId: [33]u16, ClientSockAddress: WTS_SOCKADDR, ClientTimeZone: WTS_TIME_ZONE_INFORMATION, WRdsListenerSettings: WRDS_LISTENER_SETTINGS, EventLogActivityId: Guid, ContextSize: u32, ContextData: ?*u8, }; pub const WRDS_SETTINGS_1 = extern struct { WRdsDisableClipStatus: WRDS_SETTING_STATUS, WRdsDisableClipValue: u32, WRdsDisableLPTStatus: WRDS_SETTING_STATUS, WRdsDisableLPTValue: u32, WRdsDisableCcmStatus: WRDS_SETTING_STATUS, WRdsDisableCcmValue: u32, WRdsDisableCdmStatus: WRDS_SETTING_STATUS, WRdsDisableCdmValue: u32, WRdsDisableCpmStatus: WRDS_SETTING_STATUS, WRdsDisableCpmValue: u32, WRdsDisablePnpStatus: WRDS_SETTING_STATUS, WRdsDisablePnpValue: u32, WRdsEncryptionLevelStatus: WRDS_SETTING_STATUS, WRdsEncryptionValue: u32, WRdsColorDepthStatus: WRDS_SETTING_STATUS, WRdsColorDepthValue: u32, WRdsDisableAutoReconnecetStatus: WRDS_SETTING_STATUS, WRdsDisableAutoReconnecetValue: u32, WRdsDisableEncryptionStatus: WRDS_SETTING_STATUS, WRdsDisableEncryptionValue: u32, WRdsResetBrokenStatus: WRDS_SETTING_STATUS, WRdsResetBrokenValue: u32, WRdsMaxIdleTimeStatus: WRDS_SETTING_STATUS, WRdsMaxIdleTimeValue: u32, WRdsMaxDisconnectTimeStatus: WRDS_SETTING_STATUS, WRdsMaxDisconnectTimeValue: u32, WRdsMaxConnectTimeStatus: WRDS_SETTING_STATUS, WRdsMaxConnectTimeValue: u32, WRdsKeepAliveStatus: WRDS_SETTING_STATUS, WRdsKeepAliveStartValue: BOOLEAN, WRdsKeepAliveIntervalValue: u32, }; pub const WRDS_CONNECTION_SETTING = extern union { WRdsConnectionSettings1: WRDS_CONNECTION_SETTINGS_1, }; pub const WRDS_CONNECTION_SETTINGS = extern struct { WRdsConnectionSettingLevel: WRDS_CONNECTION_SETTING_LEVEL, WRdsConnectionSetting: WRDS_CONNECTION_SETTING, }; pub const WRDS_SETTING = extern union { WRdsSettings1: WRDS_SETTINGS_1, }; pub const WRDS_SETTINGS = extern struct { WRdsSettingType: WRDS_SETTING_TYPE, WRdsSettingLevel: WRDS_SETTING_LEVEL, WRdsSetting: WRDS_SETTING, }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolManager_Value = Guid.initString("f9eaf6cc-ed79-4f01-821d-1f881b9f66cc"); pub const IID_IWTSProtocolManager = &IID_IWTSProtocolManager_Value; pub const IWTSProtocolManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateListener: fn( self: *const IWTSProtocolManager, wszListenerName: ?PWSTR, pProtocolListener: ?*?*IWTSProtocolListener, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyServiceStateChange: fn( self: *const IWTSProtocolManager, pTSServiceStateChange: ?*WTS_SERVICE_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySessionOfServiceStart: fn( self: *const IWTSProtocolManager, SessionId: ?*WTS_SESSION_ID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySessionOfServiceStop: fn( self: *const IWTSProtocolManager, SessionId: ?*WTS_SESSION_ID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySessionStateChange: fn( self: *const IWTSProtocolManager, SessionId: ?*WTS_SESSION_ID, EventId: 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 IWTSProtocolManager_CreateListener(self: *const T, wszListenerName: ?PWSTR, pProtocolListener: ?*?*IWTSProtocolListener) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolManager.VTable, self.vtable).CreateListener(@ptrCast(*const IWTSProtocolManager, self), wszListenerName, pProtocolListener); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolManager_NotifyServiceStateChange(self: *const T, pTSServiceStateChange: ?*WTS_SERVICE_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolManager.VTable, self.vtable).NotifyServiceStateChange(@ptrCast(*const IWTSProtocolManager, self), pTSServiceStateChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolManager_NotifySessionOfServiceStart(self: *const T, SessionId: ?*WTS_SESSION_ID) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolManager.VTable, self.vtable).NotifySessionOfServiceStart(@ptrCast(*const IWTSProtocolManager, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolManager_NotifySessionOfServiceStop(self: *const T, SessionId: ?*WTS_SESSION_ID) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolManager.VTable, self.vtable).NotifySessionOfServiceStop(@ptrCast(*const IWTSProtocolManager, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolManager_NotifySessionStateChange(self: *const T, SessionId: ?*WTS_SESSION_ID, EventId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolManager.VTable, self.vtable).NotifySessionStateChange(@ptrCast(*const IWTSProtocolManager, self), SessionId, EventId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolListener_Value = Guid.initString("23083765-45f0-4394-8f69-32b2bc0ef4ca"); pub const IID_IWTSProtocolListener = &IID_IWTSProtocolListener_Value; pub const IWTSProtocolListener = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, StartListen: fn( self: *const IWTSProtocolListener, pCallback: ?*IWTSProtocolListenerCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopListen: fn( self: *const IWTSProtocolListener, ) 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 IWTSProtocolListener_StartListen(self: *const T, pCallback: ?*IWTSProtocolListenerCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolListener.VTable, self.vtable).StartListen(@ptrCast(*const IWTSProtocolListener, self), pCallback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolListener_StopListen(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolListener.VTable, self.vtable).StopListen(@ptrCast(*const IWTSProtocolListener, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolListenerCallback_Value = Guid.initString("23083765-1a2d-4de2-97de-4a35f260f0b3"); pub const IID_IWTSProtocolListenerCallback = &IID_IWTSProtocolListenerCallback_Value; pub const IWTSProtocolListenerCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnConnected: fn( self: *const IWTSProtocolListenerCallback, pConnection: ?*IWTSProtocolConnection, pCallback: ?*?*IWTSProtocolConnectionCallback, ) 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 IWTSProtocolListenerCallback_OnConnected(self: *const T, pConnection: ?*IWTSProtocolConnection, pCallback: ?*?*IWTSProtocolConnectionCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolListenerCallback.VTable, self.vtable).OnConnected(@ptrCast(*const IWTSProtocolListenerCallback, self), pConnection, pCallback); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolConnection_Value = Guid.initString("23083765-9095-4648-98bf-ef81c914032d"); pub const IID_IWTSProtocolConnection = &IID_IWTSProtocolConnection_Value; pub const IWTSProtocolConnection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLogonErrorRedirector: fn( self: *const IWTSProtocolConnection, ppLogonErrorRedir: ?*?*IWTSProtocolLogonErrorRedirector, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SendPolicyData: fn( self: *const IWTSProtocolConnection, pPolicyData: ?*WTS_POLICY_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AcceptConnection: fn( self: *const IWTSProtocolConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClientData: fn( self: *const IWTSProtocolConnection, pClientData: ?*WTS_CLIENT_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUserCredentials: fn( self: *const IWTSProtocolConnection, pUserCreds: ?*WTS_USER_CREDENTIAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLicenseConnection: fn( self: *const IWTSProtocolConnection, ppLicenseConnection: ?*?*IWTSProtocolLicenseConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AuthenticateClientToSession: fn( self: *const IWTSProtocolConnection, SessionId: ?*WTS_SESSION_ID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySessionId: fn( self: *const IWTSProtocolConnection, SessionId: ?*WTS_SESSION_ID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProtocolHandles: fn( self: *const IWTSProtocolConnection, pKeyboardHandle: ?*HANDLE_PTR, pMouseHandle: ?*HANDLE_PTR, pBeepHandle: ?*HANDLE_PTR, pVideoHandle: ?*HANDLE_PTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ConnectNotify: fn( self: *const IWTSProtocolConnection, SessionId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsUserAllowedToLogon: fn( self: *const IWTSProtocolConnection, SessionId: u32, UserToken: HANDLE_PTR, pDomainName: ?PWSTR, pUserName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionArbitrationEnumeration: fn( self: *const IWTSProtocolConnection, hUserToken: HANDLE_PTR, bSingleSessionPerUserEnabled: BOOL, pSessionIdArray: [*]u32, pdwSessionIdentifierCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LogonNotify: fn( self: *const IWTSProtocolConnection, hClientToken: HANDLE_PTR, wszUserName: ?PWSTR, wszDomainName: ?PWSTR, SessionId: ?*WTS_SESSION_ID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUserData: fn( self: *const IWTSProtocolConnection, pPolicyData: ?*WTS_POLICY_DATA, pClientData: ?*WTS_USER_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisconnectNotify: fn( self: *const IWTSProtocolConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWTSProtocolConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProtocolStatus: fn( self: *const IWTSProtocolConnection, pProtocolStatus: ?*WTS_PROTOCOL_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLastInputTime: fn( self: *const IWTSProtocolConnection, pLastInputTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetErrorInfo: fn( self: *const IWTSProtocolConnection, ulError: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SendBeep: fn( self: *const IWTSProtocolConnection, Frequency: u32, Duration: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateVirtualChannel: fn( self: *const IWTSProtocolConnection, szEndpointName: ?PSTR, bStatic: BOOL, RequestedPriority: u32, phChannel: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryProperty: fn( self: *const IWTSProtocolConnection, QueryType: Guid, ulNumEntriesIn: u32, ulNumEntriesOut: u32, pPropertyEntriesIn: [*]WTS_PROPERTY_VALUE, pPropertyEntriesOut: [*]WTS_PROPERTY_VALUE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetShadowConnection: fn( self: *const IWTSProtocolConnection, ppShadowConnection: ?*?*IWTSProtocolShadowConnection, ) 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 IWTSProtocolConnection_GetLogonErrorRedirector(self: *const T, ppLogonErrorRedir: ?*?*IWTSProtocolLogonErrorRedirector) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetLogonErrorRedirector(@ptrCast(*const IWTSProtocolConnection, self), ppLogonErrorRedir); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_SendPolicyData(self: *const T, pPolicyData: ?*WTS_POLICY_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).SendPolicyData(@ptrCast(*const IWTSProtocolConnection, self), pPolicyData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_AcceptConnection(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).AcceptConnection(@ptrCast(*const IWTSProtocolConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_GetClientData(self: *const T, pClientData: ?*WTS_CLIENT_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetClientData(@ptrCast(*const IWTSProtocolConnection, self), pClientData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_GetUserCredentials(self: *const T, pUserCreds: ?*WTS_USER_CREDENTIAL) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetUserCredentials(@ptrCast(*const IWTSProtocolConnection, self), pUserCreds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_GetLicenseConnection(self: *const T, ppLicenseConnection: ?*?*IWTSProtocolLicenseConnection) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetLicenseConnection(@ptrCast(*const IWTSProtocolConnection, self), ppLicenseConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_AuthenticateClientToSession(self: *const T, SessionId: ?*WTS_SESSION_ID) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).AuthenticateClientToSession(@ptrCast(*const IWTSProtocolConnection, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_NotifySessionId(self: *const T, SessionId: ?*WTS_SESSION_ID) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).NotifySessionId(@ptrCast(*const IWTSProtocolConnection, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_GetProtocolHandles(self: *const T, pKeyboardHandle: ?*HANDLE_PTR, pMouseHandle: ?*HANDLE_PTR, pBeepHandle: ?*HANDLE_PTR, pVideoHandle: ?*HANDLE_PTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetProtocolHandles(@ptrCast(*const IWTSProtocolConnection, self), pKeyboardHandle, pMouseHandle, pBeepHandle, pVideoHandle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_ConnectNotify(self: *const T, SessionId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).ConnectNotify(@ptrCast(*const IWTSProtocolConnection, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_IsUserAllowedToLogon(self: *const T, SessionId: u32, UserToken: HANDLE_PTR, pDomainName: ?PWSTR, pUserName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).IsUserAllowedToLogon(@ptrCast(*const IWTSProtocolConnection, self), SessionId, UserToken, pDomainName, pUserName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_SessionArbitrationEnumeration(self: *const T, hUserToken: HANDLE_PTR, bSingleSessionPerUserEnabled: BOOL, pSessionIdArray: [*]u32, pdwSessionIdentifierCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).SessionArbitrationEnumeration(@ptrCast(*const IWTSProtocolConnection, self), hUserToken, bSingleSessionPerUserEnabled, pSessionIdArray, pdwSessionIdentifierCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_LogonNotify(self: *const T, hClientToken: HANDLE_PTR, wszUserName: ?PWSTR, wszDomainName: ?PWSTR, SessionId: ?*WTS_SESSION_ID) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).LogonNotify(@ptrCast(*const IWTSProtocolConnection, self), hClientToken, wszUserName, wszDomainName, SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_GetUserData(self: *const T, pPolicyData: ?*WTS_POLICY_DATA, pClientData: ?*WTS_USER_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetUserData(@ptrCast(*const IWTSProtocolConnection, self), pPolicyData, pClientData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_DisconnectNotify(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).DisconnectNotify(@ptrCast(*const IWTSProtocolConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).Close(@ptrCast(*const IWTSProtocolConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_GetProtocolStatus(self: *const T, pProtocolStatus: ?*WTS_PROTOCOL_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetProtocolStatus(@ptrCast(*const IWTSProtocolConnection, self), pProtocolStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_GetLastInputTime(self: *const T, pLastInputTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetLastInputTime(@ptrCast(*const IWTSProtocolConnection, self), pLastInputTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_SetErrorInfo(self: *const T, ulError: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).SetErrorInfo(@ptrCast(*const IWTSProtocolConnection, self), ulError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_SendBeep(self: *const T, Frequency: u32, Duration: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).SendBeep(@ptrCast(*const IWTSProtocolConnection, self), Frequency, Duration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_CreateVirtualChannel(self: *const T, szEndpointName: ?PSTR, bStatic: BOOL, RequestedPriority: u32, phChannel: ?*usize) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).CreateVirtualChannel(@ptrCast(*const IWTSProtocolConnection, self), szEndpointName, bStatic, RequestedPriority, phChannel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_QueryProperty(self: *const T, QueryType: Guid, ulNumEntriesIn: u32, ulNumEntriesOut: u32, pPropertyEntriesIn: [*]WTS_PROPERTY_VALUE, pPropertyEntriesOut: [*]WTS_PROPERTY_VALUE) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).QueryProperty(@ptrCast(*const IWTSProtocolConnection, self), QueryType, ulNumEntriesIn, ulNumEntriesOut, pPropertyEntriesIn, pPropertyEntriesOut); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnection_GetShadowConnection(self: *const T, ppShadowConnection: ?*?*IWTSProtocolShadowConnection) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnection.VTable, self.vtable).GetShadowConnection(@ptrCast(*const IWTSProtocolConnection, self), ppShadowConnection); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolConnectionCallback_Value = Guid.initString("23083765-75eb-41fe-b4fb-e086242afa0f"); pub const IID_IWTSProtocolConnectionCallback = &IID_IWTSProtocolConnectionCallback_Value; pub const IWTSProtocolConnectionCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnReady: fn( self: *const IWTSProtocolConnectionCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BrokenConnection: fn( self: *const IWTSProtocolConnectionCallback, Reason: u32, Source: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopScreenUpdates: fn( self: *const IWTSProtocolConnectionCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RedrawWindow: fn( self: *const IWTSProtocolConnectionCallback, rect: ?*WTS_SMALL_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisplayIOCtl: fn( self: *const IWTSProtocolConnectionCallback, DisplayIOCtl: ?*WTS_DISPLAY_IOCTL, ) 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 IWTSProtocolConnectionCallback_OnReady(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnectionCallback.VTable, self.vtable).OnReady(@ptrCast(*const IWTSProtocolConnectionCallback, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnectionCallback_BrokenConnection(self: *const T, Reason: u32, Source: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnectionCallback.VTable, self.vtable).BrokenConnection(@ptrCast(*const IWTSProtocolConnectionCallback, self), Reason, Source); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnectionCallback_StopScreenUpdates(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnectionCallback.VTable, self.vtable).StopScreenUpdates(@ptrCast(*const IWTSProtocolConnectionCallback, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnectionCallback_RedrawWindow(self: *const T, rect: ?*WTS_SMALL_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnectionCallback.VTable, self.vtable).RedrawWindow(@ptrCast(*const IWTSProtocolConnectionCallback, self), rect); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolConnectionCallback_DisplayIOCtl(self: *const T, DisplayIOCtl: ?*WTS_DISPLAY_IOCTL) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolConnectionCallback.VTable, self.vtable).DisplayIOCtl(@ptrCast(*const IWTSProtocolConnectionCallback, self), DisplayIOCtl); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolShadowConnection_Value = Guid.initString("ee3b0c14-37fb-456b-bab3-6d6cd51e13bf"); pub const IID_IWTSProtocolShadowConnection = &IID_IWTSProtocolShadowConnection_Value; pub const IWTSProtocolShadowConnection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Start: fn( self: *const IWTSProtocolShadowConnection, pTargetServerName: ?PWSTR, TargetSessionId: u32, HotKeyVk: u8, HotkeyModifiers: u16, pShadowCallback: ?*IWTSProtocolShadowCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IWTSProtocolShadowConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoTarget: fn( self: *const IWTSProtocolShadowConnection, pParam1: [*:0]u8, Param1Size: u32, pParam2: [*:0]u8, Param2Size: u32, pParam3: [*:0]u8, Param3Size: u32, pParam4: [*:0]u8, Param4Size: u32, pClientName: ?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 IWTSProtocolShadowConnection_Start(self: *const T, pTargetServerName: ?PWSTR, TargetSessionId: u32, HotKeyVk: u8, HotkeyModifiers: u16, pShadowCallback: ?*IWTSProtocolShadowCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolShadowConnection.VTable, self.vtable).Start(@ptrCast(*const IWTSProtocolShadowConnection, self), pTargetServerName, TargetSessionId, HotKeyVk, HotkeyModifiers, pShadowCallback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolShadowConnection_Stop(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolShadowConnection.VTable, self.vtable).Stop(@ptrCast(*const IWTSProtocolShadowConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolShadowConnection_DoTarget(self: *const T, pParam1: [*:0]u8, Param1Size: u32, pParam2: [*:0]u8, Param2Size: u32, pParam3: [*:0]u8, Param3Size: u32, pParam4: [*:0]u8, Param4Size: u32, pClientName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolShadowConnection.VTable, self.vtable).DoTarget(@ptrCast(*const IWTSProtocolShadowConnection, self), pParam1, Param1Size, pParam2, Param2Size, pParam3, Param3Size, pParam4, Param4Size, pClientName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolShadowCallback_Value = Guid.initString("503a2504-aae5-4ab1-93e0-6d1c4bc6f71a"); pub const IID_IWTSProtocolShadowCallback = &IID_IWTSProtocolShadowCallback_Value; pub const IWTSProtocolShadowCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, StopShadow: fn( self: *const IWTSProtocolShadowCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InvokeTargetShadow: fn( self: *const IWTSProtocolShadowCallback, pTargetServerName: ?PWSTR, TargetSessionId: u32, pParam1: [*:0]u8, Param1Size: u32, pParam2: [*:0]u8, Param2Size: u32, pParam3: [*:0]u8, Param3Size: u32, pParam4: [*:0]u8, Param4Size: u32, pClientName: ?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 IWTSProtocolShadowCallback_StopShadow(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolShadowCallback.VTable, self.vtable).StopShadow(@ptrCast(*const IWTSProtocolShadowCallback, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolShadowCallback_InvokeTargetShadow(self: *const T, pTargetServerName: ?PWSTR, TargetSessionId: u32, pParam1: [*:0]u8, Param1Size: u32, pParam2: [*:0]u8, Param2Size: u32, pParam3: [*:0]u8, Param3Size: u32, pParam4: [*:0]u8, Param4Size: u32, pClientName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolShadowCallback.VTable, self.vtable).InvokeTargetShadow(@ptrCast(*const IWTSProtocolShadowCallback, self), pTargetServerName, TargetSessionId, pParam1, Param1Size, pParam2, Param2Size, pParam3, Param3Size, pParam4, Param4Size, pClientName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolLicenseConnection_Value = Guid.initString("23083765-178c-4079-8e4a-fea6496a4d70"); pub const IID_IWTSProtocolLicenseConnection = &IID_IWTSProtocolLicenseConnection_Value; pub const IWTSProtocolLicenseConnection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RequestLicensingCapabilities: fn( self: *const IWTSProtocolLicenseConnection, ppLicenseCapabilities: ?*WTS_LICENSE_CAPABILITIES, pcbLicenseCapabilities: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SendClientLicense: fn( self: *const IWTSProtocolLicenseConnection, pClientLicense: [*:0]u8, cbClientLicense: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestClientLicense: fn( self: *const IWTSProtocolLicenseConnection, Reserve1: [*:0]u8, Reserve2: u32, ppClientLicense: [*:0]u8, pcbClientLicense: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProtocolComplete: fn( self: *const IWTSProtocolLicenseConnection, ulComplete: 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 IWTSProtocolLicenseConnection_RequestLicensingCapabilities(self: *const T, ppLicenseCapabilities: ?*WTS_LICENSE_CAPABILITIES, pcbLicenseCapabilities: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolLicenseConnection.VTable, self.vtable).RequestLicensingCapabilities(@ptrCast(*const IWTSProtocolLicenseConnection, self), ppLicenseCapabilities, pcbLicenseCapabilities); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolLicenseConnection_SendClientLicense(self: *const T, pClientLicense: [*:0]u8, cbClientLicense: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolLicenseConnection.VTable, self.vtable).SendClientLicense(@ptrCast(*const IWTSProtocolLicenseConnection, self), pClientLicense, cbClientLicense); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolLicenseConnection_RequestClientLicense(self: *const T, Reserve1: [*:0]u8, Reserve2: u32, ppClientLicense: [*:0]u8, pcbClientLicense: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolLicenseConnection.VTable, self.vtable).RequestClientLicense(@ptrCast(*const IWTSProtocolLicenseConnection, self), Reserve1, Reserve2, ppClientLicense, pcbClientLicense); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolLicenseConnection_ProtocolComplete(self: *const T, ulComplete: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolLicenseConnection.VTable, self.vtable).ProtocolComplete(@ptrCast(*const IWTSProtocolLicenseConnection, self), ulComplete); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IWTSProtocolLogonErrorRedirector_Value = Guid.initString("fd9b61a7-2916-4627-8dee-4328711ad6cb"); pub const IID_IWTSProtocolLogonErrorRedirector = &IID_IWTSProtocolLogonErrorRedirector_Value; pub const IWTSProtocolLogonErrorRedirector = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnBeginPainting: fn( self: *const IWTSProtocolLogonErrorRedirector, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RedirectStatus: fn( self: *const IWTSProtocolLogonErrorRedirector, pszMessage: ?[*:0]const u16, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RedirectMessage: fn( self: *const IWTSProtocolLogonErrorRedirector, pszCaption: ?[*:0]const u16, pszMessage: ?[*:0]const u16, uType: u32, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RedirectLogonError: fn( self: *const IWTSProtocolLogonErrorRedirector, ntsStatus: i32, ntsSubstatus: i32, pszCaption: ?[*:0]const u16, pszMessage: ?[*:0]const u16, uType: u32, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE, ) 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 IWTSProtocolLogonErrorRedirector_OnBeginPainting(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolLogonErrorRedirector.VTable, self.vtable).OnBeginPainting(@ptrCast(*const IWTSProtocolLogonErrorRedirector, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolLogonErrorRedirector_RedirectStatus(self: *const T, pszMessage: ?[*:0]const u16, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolLogonErrorRedirector.VTable, self.vtable).RedirectStatus(@ptrCast(*const IWTSProtocolLogonErrorRedirector, self), pszMessage, pResponse); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolLogonErrorRedirector_RedirectMessage(self: *const T, pszCaption: ?[*:0]const u16, pszMessage: ?[*:0]const u16, uType: u32, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolLogonErrorRedirector.VTable, self.vtable).RedirectMessage(@ptrCast(*const IWTSProtocolLogonErrorRedirector, self), pszCaption, pszMessage, uType, pResponse); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWTSProtocolLogonErrorRedirector_RedirectLogonError(self: *const T, ntsStatus: i32, ntsSubstatus: i32, pszCaption: ?[*:0]const u16, pszMessage: ?[*:0]const u16, uType: u32, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE) callconv(.Inline) HRESULT { return @ptrCast(*const IWTSProtocolLogonErrorRedirector.VTable, self.vtable).RedirectLogonError(@ptrCast(*const IWTSProtocolLogonErrorRedirector, self), ntsStatus, ntsSubstatus, pszCaption, pszMessage, uType, pResponse); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolSettings_Value = Guid.initString("654a5a6a-2550-47eb-b6f7-ebd637475265"); pub const IID_IWRdsProtocolSettings = &IID_IWRdsProtocolSettings_Value; pub const IWRdsProtocolSettings = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSettings: fn( self: *const IWRdsProtocolSettings, WRdsSettingType: WRDS_SETTING_TYPE, WRdsSettingLevel: WRDS_SETTING_LEVEL, pWRdsSettings: ?*WRDS_SETTINGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MergeSettings: fn( self: *const IWRdsProtocolSettings, pWRdsSettings: ?*WRDS_SETTINGS, WRdsConnectionSettingLevel: WRDS_CONNECTION_SETTING_LEVEL, pWRdsConnectionSettings: ?*WRDS_CONNECTION_SETTINGS, ) 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 IWRdsProtocolSettings_GetSettings(self: *const T, WRdsSettingType: WRDS_SETTING_TYPE, WRdsSettingLevel: WRDS_SETTING_LEVEL, pWRdsSettings: ?*WRDS_SETTINGS) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolSettings.VTable, self.vtable).GetSettings(@ptrCast(*const IWRdsProtocolSettings, self), WRdsSettingType, WRdsSettingLevel, pWRdsSettings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolSettings_MergeSettings(self: *const T, pWRdsSettings: ?*WRDS_SETTINGS, WRdsConnectionSettingLevel: WRDS_CONNECTION_SETTING_LEVEL, pWRdsConnectionSettings: ?*WRDS_CONNECTION_SETTINGS) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolSettings.VTable, self.vtable).MergeSettings(@ptrCast(*const IWRdsProtocolSettings, self), pWRdsSettings, WRdsConnectionSettingLevel, pWRdsConnectionSettings); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolManager_Value = Guid.initString("dc796967-3abb-40cd-a446-105276b58950"); pub const IID_IWRdsProtocolManager = &IID_IWRdsProtocolManager_Value; pub const IWRdsProtocolManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IWRdsProtocolManager, pIWRdsSettings: ?*IWRdsProtocolSettings, pWRdsSettings: ?*WRDS_SETTINGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateListener: fn( self: *const IWRdsProtocolManager, wszListenerName: ?PWSTR, pProtocolListener: ?*?*IWRdsProtocolListener, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyServiceStateChange: fn( self: *const IWRdsProtocolManager, pTSServiceStateChange: ?*WTS_SERVICE_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySessionOfServiceStart: fn( self: *const IWRdsProtocolManager, SessionId: ?*WTS_SESSION_ID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySessionOfServiceStop: fn( self: *const IWRdsProtocolManager, SessionId: ?*WTS_SESSION_ID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySessionStateChange: fn( self: *const IWRdsProtocolManager, SessionId: ?*WTS_SESSION_ID, EventId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySettingsChange: fn( self: *const IWRdsProtocolManager, pWRdsSettings: ?*WRDS_SETTINGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Uninitialize: fn( self: *const IWRdsProtocolManager, ) 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 IWRdsProtocolManager_Initialize(self: *const T, pIWRdsSettings: ?*IWRdsProtocolSettings, pWRdsSettings: ?*WRDS_SETTINGS) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolManager.VTable, self.vtable).Initialize(@ptrCast(*const IWRdsProtocolManager, self), pIWRdsSettings, pWRdsSettings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolManager_CreateListener(self: *const T, wszListenerName: ?PWSTR, pProtocolListener: ?*?*IWRdsProtocolListener) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolManager.VTable, self.vtable).CreateListener(@ptrCast(*const IWRdsProtocolManager, self), wszListenerName, pProtocolListener); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolManager_NotifyServiceStateChange(self: *const T, pTSServiceStateChange: ?*WTS_SERVICE_STATE) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolManager.VTable, self.vtable).NotifyServiceStateChange(@ptrCast(*const IWRdsProtocolManager, self), pTSServiceStateChange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolManager_NotifySessionOfServiceStart(self: *const T, SessionId: ?*WTS_SESSION_ID) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolManager.VTable, self.vtable).NotifySessionOfServiceStart(@ptrCast(*const IWRdsProtocolManager, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolManager_NotifySessionOfServiceStop(self: *const T, SessionId: ?*WTS_SESSION_ID) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolManager.VTable, self.vtable).NotifySessionOfServiceStop(@ptrCast(*const IWRdsProtocolManager, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolManager_NotifySessionStateChange(self: *const T, SessionId: ?*WTS_SESSION_ID, EventId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolManager.VTable, self.vtable).NotifySessionStateChange(@ptrCast(*const IWRdsProtocolManager, self), SessionId, EventId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolManager_NotifySettingsChange(self: *const T, pWRdsSettings: ?*WRDS_SETTINGS) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolManager.VTable, self.vtable).NotifySettingsChange(@ptrCast(*const IWRdsProtocolManager, self), pWRdsSettings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolManager_Uninitialize(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolManager.VTable, self.vtable).Uninitialize(@ptrCast(*const IWRdsProtocolManager, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolListener_Value = Guid.initString("fcbc131b-c686-451d-a773-e279e230f540"); pub const IID_IWRdsProtocolListener = &IID_IWRdsProtocolListener_Value; pub const IWRdsProtocolListener = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSettings: fn( self: *const IWRdsProtocolListener, WRdsListenerSettingLevel: WRDS_LISTENER_SETTING_LEVEL, pWRdsListenerSettings: ?*WRDS_LISTENER_SETTINGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StartListen: fn( self: *const IWRdsProtocolListener, pCallback: ?*IWRdsProtocolListenerCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopListen: fn( self: *const IWRdsProtocolListener, ) 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 IWRdsProtocolListener_GetSettings(self: *const T, WRdsListenerSettingLevel: WRDS_LISTENER_SETTING_LEVEL, pWRdsListenerSettings: ?*WRDS_LISTENER_SETTINGS) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolListener.VTable, self.vtable).GetSettings(@ptrCast(*const IWRdsProtocolListener, self), WRdsListenerSettingLevel, pWRdsListenerSettings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolListener_StartListen(self: *const T, pCallback: ?*IWRdsProtocolListenerCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolListener.VTable, self.vtable).StartListen(@ptrCast(*const IWRdsProtocolListener, self), pCallback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolListener_StopListen(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolListener.VTable, self.vtable).StopListen(@ptrCast(*const IWRdsProtocolListener, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolListenerCallback_Value = Guid.initString("3ab27e5b-4449-4dc1-b74a-91621d4fe984"); pub const IID_IWRdsProtocolListenerCallback = &IID_IWRdsProtocolListenerCallback_Value; pub const IWRdsProtocolListenerCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnConnected: fn( self: *const IWRdsProtocolListenerCallback, pConnection: ?*IWRdsProtocolConnection, pWRdsConnectionSettings: ?*WRDS_CONNECTION_SETTINGS, pCallback: ?*?*IWRdsProtocolConnectionCallback, ) 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 IWRdsProtocolListenerCallback_OnConnected(self: *const T, pConnection: ?*IWRdsProtocolConnection, pWRdsConnectionSettings: ?*WRDS_CONNECTION_SETTINGS, pCallback: ?*?*IWRdsProtocolConnectionCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolListenerCallback.VTable, self.vtable).OnConnected(@ptrCast(*const IWRdsProtocolListenerCallback, self), pConnection, pWRdsConnectionSettings, pCallback); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolConnection_Value = Guid.initString("324ed94f-fdaf-4ff6-81a8-42abe755830b"); pub const IID_IWRdsProtocolConnection = &IID_IWRdsProtocolConnection_Value; pub const IWRdsProtocolConnection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetLogonErrorRedirector: fn( self: *const IWRdsProtocolConnection, ppLogonErrorRedir: ?*?*IWRdsProtocolLogonErrorRedirector, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AcceptConnection: fn( self: *const IWRdsProtocolConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClientData: fn( self: *const IWRdsProtocolConnection, pClientData: ?*WTS_CLIENT_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClientMonitorData: fn( self: *const IWRdsProtocolConnection, pNumMonitors: ?*u32, pPrimaryMonitor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUserCredentials: fn( self: *const IWRdsProtocolConnection, pUserCreds: ?*WTS_USER_CREDENTIAL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLicenseConnection: fn( self: *const IWRdsProtocolConnection, ppLicenseConnection: ?*?*IWRdsProtocolLicenseConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AuthenticateClientToSession: fn( self: *const IWRdsProtocolConnection, SessionId: ?*WTS_SESSION_ID, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifySessionId: fn( self: *const IWRdsProtocolConnection, SessionId: ?*WTS_SESSION_ID, SessionHandle: HANDLE_PTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInputHandles: fn( self: *const IWRdsProtocolConnection, pKeyboardHandle: ?*HANDLE_PTR, pMouseHandle: ?*HANDLE_PTR, pBeepHandle: ?*HANDLE_PTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVideoHandle: fn( self: *const IWRdsProtocolConnection, pVideoHandle: ?*HANDLE_PTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ConnectNotify: fn( self: *const IWRdsProtocolConnection, SessionId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsUserAllowedToLogon: fn( self: *const IWRdsProtocolConnection, SessionId: u32, UserToken: HANDLE_PTR, pDomainName: ?PWSTR, pUserName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SessionArbitrationEnumeration: fn( self: *const IWRdsProtocolConnection, hUserToken: HANDLE_PTR, bSingleSessionPerUserEnabled: BOOL, pSessionIdArray: [*]u32, pdwSessionIdentifierCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LogonNotify: fn( self: *const IWRdsProtocolConnection, hClientToken: HANDLE_PTR, wszUserName: ?PWSTR, wszDomainName: ?PWSTR, SessionId: ?*WTS_SESSION_ID, pWRdsConnectionSettings: ?*WRDS_CONNECTION_SETTINGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PreDisconnect: fn( self: *const IWRdsProtocolConnection, DisconnectReason: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisconnectNotify: fn( self: *const IWRdsProtocolConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IWRdsProtocolConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProtocolStatus: fn( self: *const IWRdsProtocolConnection, pProtocolStatus: ?*WTS_PROTOCOL_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLastInputTime: fn( self: *const IWRdsProtocolConnection, pLastInputTime: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetErrorInfo: fn( self: *const IWRdsProtocolConnection, ulError: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateVirtualChannel: fn( self: *const IWRdsProtocolConnection, szEndpointName: ?PSTR, bStatic: BOOL, RequestedPriority: u32, phChannel: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryProperty: fn( self: *const IWRdsProtocolConnection, QueryType: Guid, ulNumEntriesIn: u32, ulNumEntriesOut: u32, pPropertyEntriesIn: [*]WTS_PROPERTY_VALUE, pPropertyEntriesOut: [*]WTS_PROPERTY_VALUE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetShadowConnection: fn( self: *const IWRdsProtocolConnection, ppShadowConnection: ?*?*IWRdsProtocolShadowConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyCommandProcessCreated: fn( self: *const IWRdsProtocolConnection, SessionId: 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 IWRdsProtocolConnection_GetLogonErrorRedirector(self: *const T, ppLogonErrorRedir: ?*?*IWRdsProtocolLogonErrorRedirector) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetLogonErrorRedirector(@ptrCast(*const IWRdsProtocolConnection, self), ppLogonErrorRedir); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_AcceptConnection(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).AcceptConnection(@ptrCast(*const IWRdsProtocolConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetClientData(self: *const T, pClientData: ?*WTS_CLIENT_DATA) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetClientData(@ptrCast(*const IWRdsProtocolConnection, self), pClientData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetClientMonitorData(self: *const T, pNumMonitors: ?*u32, pPrimaryMonitor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetClientMonitorData(@ptrCast(*const IWRdsProtocolConnection, self), pNumMonitors, pPrimaryMonitor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetUserCredentials(self: *const T, pUserCreds: ?*WTS_USER_CREDENTIAL) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetUserCredentials(@ptrCast(*const IWRdsProtocolConnection, self), pUserCreds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetLicenseConnection(self: *const T, ppLicenseConnection: ?*?*IWRdsProtocolLicenseConnection) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetLicenseConnection(@ptrCast(*const IWRdsProtocolConnection, self), ppLicenseConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_AuthenticateClientToSession(self: *const T, SessionId: ?*WTS_SESSION_ID) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).AuthenticateClientToSession(@ptrCast(*const IWRdsProtocolConnection, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_NotifySessionId(self: *const T, SessionId: ?*WTS_SESSION_ID, SessionHandle: HANDLE_PTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).NotifySessionId(@ptrCast(*const IWRdsProtocolConnection, self), SessionId, SessionHandle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetInputHandles(self: *const T, pKeyboardHandle: ?*HANDLE_PTR, pMouseHandle: ?*HANDLE_PTR, pBeepHandle: ?*HANDLE_PTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetInputHandles(@ptrCast(*const IWRdsProtocolConnection, self), pKeyboardHandle, pMouseHandle, pBeepHandle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetVideoHandle(self: *const T, pVideoHandle: ?*HANDLE_PTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetVideoHandle(@ptrCast(*const IWRdsProtocolConnection, self), pVideoHandle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_ConnectNotify(self: *const T, SessionId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).ConnectNotify(@ptrCast(*const IWRdsProtocolConnection, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_IsUserAllowedToLogon(self: *const T, SessionId: u32, UserToken: HANDLE_PTR, pDomainName: ?PWSTR, pUserName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).IsUserAllowedToLogon(@ptrCast(*const IWRdsProtocolConnection, self), SessionId, UserToken, pDomainName, pUserName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_SessionArbitrationEnumeration(self: *const T, hUserToken: HANDLE_PTR, bSingleSessionPerUserEnabled: BOOL, pSessionIdArray: [*]u32, pdwSessionIdentifierCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).SessionArbitrationEnumeration(@ptrCast(*const IWRdsProtocolConnection, self), hUserToken, bSingleSessionPerUserEnabled, pSessionIdArray, pdwSessionIdentifierCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_LogonNotify(self: *const T, hClientToken: HANDLE_PTR, wszUserName: ?PWSTR, wszDomainName: ?PWSTR, SessionId: ?*WTS_SESSION_ID, pWRdsConnectionSettings: ?*WRDS_CONNECTION_SETTINGS) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).LogonNotify(@ptrCast(*const IWRdsProtocolConnection, self), hClientToken, wszUserName, wszDomainName, SessionId, pWRdsConnectionSettings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_PreDisconnect(self: *const T, DisconnectReason: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).PreDisconnect(@ptrCast(*const IWRdsProtocolConnection, self), DisconnectReason); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_DisconnectNotify(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).DisconnectNotify(@ptrCast(*const IWRdsProtocolConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).Close(@ptrCast(*const IWRdsProtocolConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetProtocolStatus(self: *const T, pProtocolStatus: ?*WTS_PROTOCOL_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetProtocolStatus(@ptrCast(*const IWRdsProtocolConnection, self), pProtocolStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetLastInputTime(self: *const T, pLastInputTime: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetLastInputTime(@ptrCast(*const IWRdsProtocolConnection, self), pLastInputTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_SetErrorInfo(self: *const T, ulError: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).SetErrorInfo(@ptrCast(*const IWRdsProtocolConnection, self), ulError); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_CreateVirtualChannel(self: *const T, szEndpointName: ?PSTR, bStatic: BOOL, RequestedPriority: u32, phChannel: ?*usize) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).CreateVirtualChannel(@ptrCast(*const IWRdsProtocolConnection, self), szEndpointName, bStatic, RequestedPriority, phChannel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_QueryProperty(self: *const T, QueryType: Guid, ulNumEntriesIn: u32, ulNumEntriesOut: u32, pPropertyEntriesIn: [*]WTS_PROPERTY_VALUE, pPropertyEntriesOut: [*]WTS_PROPERTY_VALUE) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).QueryProperty(@ptrCast(*const IWRdsProtocolConnection, self), QueryType, ulNumEntriesIn, ulNumEntriesOut, pPropertyEntriesIn, pPropertyEntriesOut); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_GetShadowConnection(self: *const T, ppShadowConnection: ?*?*IWRdsProtocolShadowConnection) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).GetShadowConnection(@ptrCast(*const IWRdsProtocolConnection, self), ppShadowConnection); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnection_NotifyCommandProcessCreated(self: *const T, SessionId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnection.VTable, self.vtable).NotifyCommandProcessCreated(@ptrCast(*const IWRdsProtocolConnection, self), SessionId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolConnectionCallback_Value = Guid.initString("f1d70332-d070-4ef1-a088-78313536c2d6"); pub const IID_IWRdsProtocolConnectionCallback = &IID_IWRdsProtocolConnectionCallback_Value; pub const IWRdsProtocolConnectionCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnReady: fn( self: *const IWRdsProtocolConnectionCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BrokenConnection: fn( self: *const IWRdsProtocolConnectionCallback, Reason: u32, Source: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, StopScreenUpdates: fn( self: *const IWRdsProtocolConnectionCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RedrawWindow: fn( self: *const IWRdsProtocolConnectionCallback, rect: ?*WTS_SMALL_RECT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConnectionId: fn( self: *const IWRdsProtocolConnectionCallback, pConnectionId: ?*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 IWRdsProtocolConnectionCallback_OnReady(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnectionCallback.VTable, self.vtable).OnReady(@ptrCast(*const IWRdsProtocolConnectionCallback, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnectionCallback_BrokenConnection(self: *const T, Reason: u32, Source: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnectionCallback.VTable, self.vtable).BrokenConnection(@ptrCast(*const IWRdsProtocolConnectionCallback, self), Reason, Source); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnectionCallback_StopScreenUpdates(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnectionCallback.VTable, self.vtable).StopScreenUpdates(@ptrCast(*const IWRdsProtocolConnectionCallback, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnectionCallback_RedrawWindow(self: *const T, rect: ?*WTS_SMALL_RECT) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnectionCallback.VTable, self.vtable).RedrawWindow(@ptrCast(*const IWRdsProtocolConnectionCallback, self), rect); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnectionCallback_GetConnectionId(self: *const T, pConnectionId: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnectionCallback.VTable, self.vtable).GetConnectionId(@ptrCast(*const IWRdsProtocolConnectionCallback, self), pConnectionId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolShadowConnection_Value = Guid.initString("9ae85ce6-cade-4548-8feb-99016597f60a"); pub const IID_IWRdsProtocolShadowConnection = &IID_IWRdsProtocolShadowConnection_Value; pub const IWRdsProtocolShadowConnection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Start: fn( self: *const IWRdsProtocolShadowConnection, pTargetServerName: ?PWSTR, TargetSessionId: u32, HotKeyVk: u8, HotkeyModifiers: u16, pShadowCallback: ?*IWRdsProtocolShadowCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IWRdsProtocolShadowConnection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DoTarget: fn( self: *const IWRdsProtocolShadowConnection, pParam1: [*:0]u8, Param1Size: u32, pParam2: [*:0]u8, Param2Size: u32, pParam3: [*:0]u8, Param3Size: u32, pParam4: [*:0]u8, Param4Size: u32, pClientName: ?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 IWRdsProtocolShadowConnection_Start(self: *const T, pTargetServerName: ?PWSTR, TargetSessionId: u32, HotKeyVk: u8, HotkeyModifiers: u16, pShadowCallback: ?*IWRdsProtocolShadowCallback) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolShadowConnection.VTable, self.vtable).Start(@ptrCast(*const IWRdsProtocolShadowConnection, self), pTargetServerName, TargetSessionId, HotKeyVk, HotkeyModifiers, pShadowCallback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolShadowConnection_Stop(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolShadowConnection.VTable, self.vtable).Stop(@ptrCast(*const IWRdsProtocolShadowConnection, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolShadowConnection_DoTarget(self: *const T, pParam1: [*:0]u8, Param1Size: u32, pParam2: [*:0]u8, Param2Size: u32, pParam3: [*:0]u8, Param3Size: u32, pParam4: [*:0]u8, Param4Size: u32, pClientName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolShadowConnection.VTable, self.vtable).DoTarget(@ptrCast(*const IWRdsProtocolShadowConnection, self), pParam1, Param1Size, pParam2, Param2Size, pParam3, Param3Size, pParam4, Param4Size, pClientName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolShadowCallback_Value = Guid.initString("e0667ce0-0372-40d6-adb2-a0f3322674d6"); pub const IID_IWRdsProtocolShadowCallback = &IID_IWRdsProtocolShadowCallback_Value; pub const IWRdsProtocolShadowCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, StopShadow: fn( self: *const IWRdsProtocolShadowCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InvokeTargetShadow: fn( self: *const IWRdsProtocolShadowCallback, pTargetServerName: ?PWSTR, TargetSessionId: u32, pParam1: [*:0]u8, Param1Size: u32, pParam2: [*:0]u8, Param2Size: u32, pParam3: [*:0]u8, Param3Size: u32, pParam4: [*:0]u8, Param4Size: u32, pClientName: ?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 IWRdsProtocolShadowCallback_StopShadow(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolShadowCallback.VTable, self.vtable).StopShadow(@ptrCast(*const IWRdsProtocolShadowCallback, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolShadowCallback_InvokeTargetShadow(self: *const T, pTargetServerName: ?PWSTR, TargetSessionId: u32, pParam1: [*:0]u8, Param1Size: u32, pParam2: [*:0]u8, Param2Size: u32, pParam3: [*:0]u8, Param3Size: u32, pParam4: [*:0]u8, Param4Size: u32, pClientName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolShadowCallback.VTable, self.vtable).InvokeTargetShadow(@ptrCast(*const IWRdsProtocolShadowCallback, self), pTargetServerName, TargetSessionId, pParam1, Param1Size, pParam2, Param2Size, pParam3, Param3Size, pParam4, Param4Size, pClientName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolLicenseConnection_Value = Guid.initString("1d6a145f-d095-4424-957a-407fae822d84"); pub const IID_IWRdsProtocolLicenseConnection = &IID_IWRdsProtocolLicenseConnection_Value; pub const IWRdsProtocolLicenseConnection = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RequestLicensingCapabilities: fn( self: *const IWRdsProtocolLicenseConnection, ppLicenseCapabilities: ?*WTS_LICENSE_CAPABILITIES, pcbLicenseCapabilities: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SendClientLicense: fn( self: *const IWRdsProtocolLicenseConnection, pClientLicense: [*:0]u8, cbClientLicense: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestClientLicense: fn( self: *const IWRdsProtocolLicenseConnection, Reserve1: [*:0]u8, Reserve2: u32, ppClientLicense: [*:0]u8, pcbClientLicense: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProtocolComplete: fn( self: *const IWRdsProtocolLicenseConnection, ulComplete: 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 IWRdsProtocolLicenseConnection_RequestLicensingCapabilities(self: *const T, ppLicenseCapabilities: ?*WTS_LICENSE_CAPABILITIES, pcbLicenseCapabilities: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolLicenseConnection.VTable, self.vtable).RequestLicensingCapabilities(@ptrCast(*const IWRdsProtocolLicenseConnection, self), ppLicenseCapabilities, pcbLicenseCapabilities); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolLicenseConnection_SendClientLicense(self: *const T, pClientLicense: [*:0]u8, cbClientLicense: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolLicenseConnection.VTable, self.vtable).SendClientLicense(@ptrCast(*const IWRdsProtocolLicenseConnection, self), pClientLicense, cbClientLicense); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolLicenseConnection_RequestClientLicense(self: *const T, Reserve1: [*:0]u8, Reserve2: u32, ppClientLicense: [*:0]u8, pcbClientLicense: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolLicenseConnection.VTable, self.vtable).RequestClientLicense(@ptrCast(*const IWRdsProtocolLicenseConnection, self), Reserve1, Reserve2, ppClientLicense, pcbClientLicense); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolLicenseConnection_ProtocolComplete(self: *const T, ulComplete: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolLicenseConnection.VTable, self.vtable).ProtocolComplete(@ptrCast(*const IWRdsProtocolLicenseConnection, self), ulComplete); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2012' const IID_IWRdsProtocolLogonErrorRedirector_Value = Guid.initString("519fe83b-142a-4120-a3d5-a405d315281a"); pub const IID_IWRdsProtocolLogonErrorRedirector = &IID_IWRdsProtocolLogonErrorRedirector_Value; pub const IWRdsProtocolLogonErrorRedirector = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnBeginPainting: fn( self: *const IWRdsProtocolLogonErrorRedirector, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RedirectStatus: fn( self: *const IWRdsProtocolLogonErrorRedirector, pszMessage: ?[*:0]const u16, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RedirectMessage: fn( self: *const IWRdsProtocolLogonErrorRedirector, pszCaption: ?[*:0]const u16, pszMessage: ?[*:0]const u16, uType: u32, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RedirectLogonError: fn( self: *const IWRdsProtocolLogonErrorRedirector, ntsStatus: i32, ntsSubstatus: i32, pszCaption: ?[*:0]const u16, pszMessage: ?[*:0]const u16, uType: u32, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE, ) 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 IWRdsProtocolLogonErrorRedirector_OnBeginPainting(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolLogonErrorRedirector.VTable, self.vtable).OnBeginPainting(@ptrCast(*const IWRdsProtocolLogonErrorRedirector, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolLogonErrorRedirector_RedirectStatus(self: *const T, pszMessage: ?[*:0]const u16, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolLogonErrorRedirector.VTable, self.vtable).RedirectStatus(@ptrCast(*const IWRdsProtocolLogonErrorRedirector, self), pszMessage, pResponse); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolLogonErrorRedirector_RedirectMessage(self: *const T, pszCaption: ?[*:0]const u16, pszMessage: ?[*:0]const u16, uType: u32, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolLogonErrorRedirector.VTable, self.vtable).RedirectMessage(@ptrCast(*const IWRdsProtocolLogonErrorRedirector, self), pszCaption, pszMessage, uType, pResponse); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolLogonErrorRedirector_RedirectLogonError(self: *const T, ntsStatus: i32, ntsSubstatus: i32, pszCaption: ?[*:0]const u16, pszMessage: ?[*:0]const u16, uType: u32, pResponse: ?*WTS_LOGON_ERROR_REDIRECTOR_RESPONSE) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolLogonErrorRedirector.VTable, self.vtable).RedirectLogonError(@ptrCast(*const IWRdsProtocolLogonErrorRedirector, self), ntsStatus, ntsSubstatus, pszCaption, pszMessage, uType, pResponse); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWRdsWddmIddProps_Value = Guid.initString("1382df4d-a289-43d1-a184-144726f9af90"); pub const IID_IWRdsWddmIddProps = &IID_IWRdsWddmIddProps_Value; pub const IWRdsWddmIddProps = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetHardwareId: fn( self: *const IWRdsWddmIddProps, pDisplayDriverHardwareId: [*:0]u16, Count: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDriverLoad: fn( self: *const IWRdsWddmIddProps, SessionId: u32, DriverHandle: HANDLE_PTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnDriverUnload: fn( self: *const IWRdsWddmIddProps, SessionId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnableWddmIdd: fn( self: *const IWRdsWddmIddProps, Enabled: BOOL, ) 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 IWRdsWddmIddProps_GetHardwareId(self: *const T, pDisplayDriverHardwareId: [*:0]u16, Count: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsWddmIddProps.VTable, self.vtable).GetHardwareId(@ptrCast(*const IWRdsWddmIddProps, self), pDisplayDriverHardwareId, Count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsWddmIddProps_OnDriverLoad(self: *const T, SessionId: u32, DriverHandle: HANDLE_PTR) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsWddmIddProps.VTable, self.vtable).OnDriverLoad(@ptrCast(*const IWRdsWddmIddProps, self), SessionId, DriverHandle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsWddmIddProps_OnDriverUnload(self: *const T, SessionId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsWddmIddProps.VTable, self.vtable).OnDriverUnload(@ptrCast(*const IWRdsWddmIddProps, self), SessionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsWddmIddProps_EnableWddmIdd(self: *const T, Enabled: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsWddmIddProps.VTable, self.vtable).EnableWddmIdd(@ptrCast(*const IWRdsWddmIddProps, self), Enabled); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWRdsProtocolConnectionSettings_Value = Guid.initString("83fcf5d3-f6f4-ea94-9cd2-32f280e1e510"); pub const IID_IWRdsProtocolConnectionSettings = &IID_IWRdsProtocolConnectionSettings_Value; pub const IWRdsProtocolConnectionSettings = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetConnectionSetting: fn( self: *const IWRdsProtocolConnectionSettings, PropertyID: Guid, pPropertyEntriesIn: ?*WTS_PROPERTY_VALUE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConnectionSetting: fn( self: *const IWRdsProtocolConnectionSettings, PropertyID: Guid, pPropertyEntriesOut: ?*WTS_PROPERTY_VALUE, ) 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 IWRdsProtocolConnectionSettings_SetConnectionSetting(self: *const T, PropertyID: Guid, pPropertyEntriesIn: ?*WTS_PROPERTY_VALUE) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnectionSettings.VTable, self.vtable).SetConnectionSetting(@ptrCast(*const IWRdsProtocolConnectionSettings, self), PropertyID, pPropertyEntriesIn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWRdsProtocolConnectionSettings_GetConnectionSetting(self: *const T, PropertyID: Guid, pPropertyEntriesOut: ?*WTS_PROPERTY_VALUE) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsProtocolConnectionSettings.VTable, self.vtable).GetConnectionSetting(@ptrCast(*const IWRdsProtocolConnectionSettings, self), PropertyID, pPropertyEntriesOut); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IWRdsEnhancedFastReconnectArbitrator_Value = Guid.initString("5718ae9b-47f2-499f-b634-d8175bd51131"); pub const IID_IWRdsEnhancedFastReconnectArbitrator = &IID_IWRdsEnhancedFastReconnectArbitrator_Value; pub const IWRdsEnhancedFastReconnectArbitrator = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSessionForEnhancedFastReconnect: fn( self: *const IWRdsEnhancedFastReconnectArbitrator, pSessionIdArray: ?*i32, dwSessionCount: u32, pResultSessionId: ?*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 IWRdsEnhancedFastReconnectArbitrator_GetSessionForEnhancedFastReconnect(self: *const T, pSessionIdArray: ?*i32, dwSessionCount: u32, pResultSessionId: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IWRdsEnhancedFastReconnectArbitrator.VTable, self.vtable).GetSessionForEnhancedFastReconnect(@ptrCast(*const IWRdsEnhancedFastReconnectArbitrator, self), pSessionIdArray, dwSessionCount, pResultSessionId); } };} pub usingnamespace MethodMixin(@This()); }; pub const PasswordEncodingType = enum(i32) { @"8" = 0, @"16LE" = 1, @"16BE" = 2, }; pub const PasswordEncodingUTF8 = PasswordEncodingType.@"8"; pub const PasswordEncodingUTF16LE = PasswordEncodingType.@"16LE"; pub const PasswordEncodingUTF16BE = PasswordEncodingType.@"16BE"; // TODO: this type is limited to platform 'windows8.0' const IID_IRemoteDesktopClientSettings_Value = Guid.initString("48a0f2a7-2713-431f-bbac-6f4558e7d64d"); pub const IID_IRemoteDesktopClientSettings = &IID_IRemoteDesktopClientSettings_Value; pub const IRemoteDesktopClientSettings = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, ApplySettings: fn( self: *const IRemoteDesktopClientSettings, rdpFileContents: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RetrieveSettings: fn( self: *const IRemoteDesktopClientSettings, rdpFileContents: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRdpProperty: fn( self: *const IRemoteDesktopClientSettings, propertyName: ?BSTR, value: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRdpProperty: fn( self: *const IRemoteDesktopClientSettings, propertyName: ?BSTR, value: VARIANT, ) 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 IRemoteDesktopClientSettings_ApplySettings(self: *const T, rdpFileContents: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientSettings.VTable, self.vtable).ApplySettings(@ptrCast(*const IRemoteDesktopClientSettings, self), rdpFileContents); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientSettings_RetrieveSettings(self: *const T, rdpFileContents: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientSettings.VTable, self.vtable).RetrieveSettings(@ptrCast(*const IRemoteDesktopClientSettings, self), rdpFileContents); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientSettings_GetRdpProperty(self: *const T, propertyName: ?BSTR, value: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientSettings.VTable, self.vtable).GetRdpProperty(@ptrCast(*const IRemoteDesktopClientSettings, self), propertyName, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientSettings_SetRdpProperty(self: *const T, propertyName: ?BSTR, value: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientSettings.VTable, self.vtable).SetRdpProperty(@ptrCast(*const IRemoteDesktopClientSettings, self), propertyName, value); } };} pub usingnamespace MethodMixin(@This()); }; pub const RemoteActionType = enum(i32) { Charms = 0, Appbar = 1, Snap = 2, StartScreen = 3, AppSwitch = 4, }; pub const RemoteActionCharms = RemoteActionType.Charms; pub const RemoteActionAppbar = RemoteActionType.Appbar; pub const RemoteActionSnap = RemoteActionType.Snap; pub const RemoteActionStartScreen = RemoteActionType.StartScreen; pub const RemoteActionAppSwitch = RemoteActionType.AppSwitch; pub const SnapshotEncodingType = enum(i32) { i = 0, }; pub const SnapshotEncodingDataUri = SnapshotEncodingType.i; pub const SnapshotFormatType = enum(i32) { Png = 0, Jpeg = 1, Bmp = 2, }; pub const SnapshotFormatPng = SnapshotFormatType.Png; pub const SnapshotFormatJpeg = SnapshotFormatType.Jpeg; pub const SnapshotFormatBmp = SnapshotFormatType.Bmp; // TODO: this type is limited to platform 'windows8.0' const IID_IRemoteDesktopClientActions_Value = Guid.initString("7d54bc4e-1028-45d4-8b0a-b9b6bffba176"); pub const IID_IRemoteDesktopClientActions = &IID_IRemoteDesktopClientActions_Value; pub const IRemoteDesktopClientActions = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, SuspendScreenUpdates: fn( self: *const IRemoteDesktopClientActions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResumeScreenUpdates: fn( self: *const IRemoteDesktopClientActions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ExecuteRemoteAction: fn( self: *const IRemoteDesktopClientActions, remoteAction: RemoteActionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSnapshot: fn( self: *const IRemoteDesktopClientActions, snapshotEncoding: SnapshotEncodingType, snapshotFormat: SnapshotFormatType, snapshotWidth: u32, snapshotHeight: u32, snapshotData: ?*?BSTR, ) 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 IRemoteDesktopClientActions_SuspendScreenUpdates(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientActions.VTable, self.vtable).SuspendScreenUpdates(@ptrCast(*const IRemoteDesktopClientActions, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientActions_ResumeScreenUpdates(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientActions.VTable, self.vtable).ResumeScreenUpdates(@ptrCast(*const IRemoteDesktopClientActions, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientActions_ExecuteRemoteAction(self: *const T, remoteAction: RemoteActionType) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientActions.VTable, self.vtable).ExecuteRemoteAction(@ptrCast(*const IRemoteDesktopClientActions, self), remoteAction); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientActions_GetSnapshot(self: *const T, snapshotEncoding: SnapshotEncodingType, snapshotFormat: SnapshotFormatType, snapshotWidth: u32, snapshotHeight: u32, snapshotData: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientActions.VTable, self.vtable).GetSnapshot(@ptrCast(*const IRemoteDesktopClientActions, self), snapshotEncoding, snapshotFormat, snapshotWidth, snapshotHeight, snapshotData); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows8.0' const IID_IRemoteDesktopClientTouchPointer_Value = Guid.initString("260ec22d-8cbc-44b5-9e88-2a37f6c93ae9"); pub const IID_IRemoteDesktopClientTouchPointer = &IID_IRemoteDesktopClientTouchPointer_Value; pub const IRemoteDesktopClientTouchPointer = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Enabled: fn( self: *const IRemoteDesktopClientTouchPointer, enabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Enabled: fn( self: *const IRemoteDesktopClientTouchPointer, enabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EventsEnabled: fn( self: *const IRemoteDesktopClientTouchPointer, eventsEnabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventsEnabled: fn( self: *const IRemoteDesktopClientTouchPointer, eventsEnabled: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PointerSpeed: fn( self: *const IRemoteDesktopClientTouchPointer, pointerSpeed: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PointerSpeed: fn( self: *const IRemoteDesktopClientTouchPointer, pointerSpeed: ?*u32, ) 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 IRemoteDesktopClientTouchPointer_put_Enabled(self: *const T, enabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientTouchPointer.VTable, self.vtable).put_Enabled(@ptrCast(*const IRemoteDesktopClientTouchPointer, self), enabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientTouchPointer_get_Enabled(self: *const T, enabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientTouchPointer.VTable, self.vtable).get_Enabled(@ptrCast(*const IRemoteDesktopClientTouchPointer, self), enabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientTouchPointer_put_EventsEnabled(self: *const T, eventsEnabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientTouchPointer.VTable, self.vtable).put_EventsEnabled(@ptrCast(*const IRemoteDesktopClientTouchPointer, self), eventsEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientTouchPointer_get_EventsEnabled(self: *const T, eventsEnabled: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientTouchPointer.VTable, self.vtable).get_EventsEnabled(@ptrCast(*const IRemoteDesktopClientTouchPointer, self), eventsEnabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientTouchPointer_put_PointerSpeed(self: *const T, pointerSpeed: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientTouchPointer.VTable, self.vtable).put_PointerSpeed(@ptrCast(*const IRemoteDesktopClientTouchPointer, self), pointerSpeed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClientTouchPointer_get_PointerSpeed(self: *const T, pointerSpeed: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClientTouchPointer.VTable, self.vtable).get_PointerSpeed(@ptrCast(*const IRemoteDesktopClientTouchPointer, self), pointerSpeed); } };} pub usingnamespace MethodMixin(@This()); }; pub const KeyCombinationType = enum(i32) { Home = 0, Left = 1, Up = 2, Right = 3, Down = 4, Scroll = 5, }; pub const KeyCombinationHome = KeyCombinationType.Home; pub const KeyCombinationLeft = KeyCombinationType.Left; pub const KeyCombinationUp = KeyCombinationType.Up; pub const KeyCombinationRight = KeyCombinationType.Right; pub const KeyCombinationDown = KeyCombinationType.Down; pub const KeyCombinationScroll = KeyCombinationType.Scroll; // TODO: this type is limited to platform 'windows8.0' const IID_IRemoteDesktopClient_Value = Guid.initString("57d25668-625a-4905-be4e-304caa13f89c"); pub const IID_IRemoteDesktopClient = &IID_IRemoteDesktopClient_Value; pub const IRemoteDesktopClient = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Connect: fn( self: *const IRemoteDesktopClient, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Disconnect: fn( self: *const IRemoteDesktopClient, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reconnect: fn( self: *const IRemoteDesktopClient, width: u32, height: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Settings: fn( self: *const IRemoteDesktopClient, settings: ?*?*IRemoteDesktopClientSettings, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Actions: fn( self: *const IRemoteDesktopClient, actions: ?*?*IRemoteDesktopClientActions, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TouchPointer: fn( self: *const IRemoteDesktopClient, touchPointer: ?*?*IRemoteDesktopClientTouchPointer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteSavedCredentials: fn( self: *const IRemoteDesktopClient, serverName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateSessionDisplaySettings: fn( self: *const IRemoteDesktopClient, width: u32, height: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, attachEvent: fn( self: *const IRemoteDesktopClient, eventName: ?BSTR, callback: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, detachEvent: fn( self: *const IRemoteDesktopClient, eventName: ?BSTR, callback: ?*IDispatch, ) 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 IRemoteDesktopClient_Connect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).Connect(@ptrCast(*const IRemoteDesktopClient, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_Disconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).Disconnect(@ptrCast(*const IRemoteDesktopClient, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_Reconnect(self: *const T, width: u32, height: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).Reconnect(@ptrCast(*const IRemoteDesktopClient, self), width, height); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_get_Settings(self: *const T, settings: ?*?*IRemoteDesktopClientSettings) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).get_Settings(@ptrCast(*const IRemoteDesktopClient, self), settings); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_get_Actions(self: *const T, actions: ?*?*IRemoteDesktopClientActions) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).get_Actions(@ptrCast(*const IRemoteDesktopClient, self), actions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_get_TouchPointer(self: *const T, touchPointer: ?*?*IRemoteDesktopClientTouchPointer) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).get_TouchPointer(@ptrCast(*const IRemoteDesktopClient, self), touchPointer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_DeleteSavedCredentials(self: *const T, serverName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).DeleteSavedCredentials(@ptrCast(*const IRemoteDesktopClient, self), serverName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_UpdateSessionDisplaySettings(self: *const T, width: u32, height: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).UpdateSessionDisplaySettings(@ptrCast(*const IRemoteDesktopClient, self), width, height); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_attachEvent(self: *const T, eventName: ?BSTR, callback: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).attachEvent(@ptrCast(*const IRemoteDesktopClient, self), eventName, callback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IRemoteDesktopClient_detachEvent(self: *const T, eventName: ?BSTR, callback: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteDesktopClient.VTable, self.vtable).detachEvent(@ptrCast(*const IRemoteDesktopClient, self), eventName, callback); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IRemoteSystemAdditionalInfoProvider_Value = Guid.initString("eeaa3d5f-ec63-4d27-af38-e86b1d7292cb"); pub const IID_IRemoteSystemAdditionalInfoProvider = &IID_IRemoteSystemAdditionalInfoProvider_Value; pub const IRemoteSystemAdditionalInfoProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetAdditionalInfo: fn( self: *const IRemoteSystemAdditionalInfoProvider, deduplicationId: ?*?HSTRING, riid: ?*const Guid, mapView: ?*?*anyopaque, ) 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 IRemoteSystemAdditionalInfoProvider_GetAdditionalInfo(self: *const T, deduplicationId: ?*?HSTRING, riid: ?*const Guid, mapView: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IRemoteSystemAdditionalInfoProvider.VTable, self.vtable).GetAdditionalInfo(@ptrCast(*const IRemoteSystemAdditionalInfoProvider, self), deduplicationId, riid, mapView); } };} pub usingnamespace MethodMixin(@This()); }; pub const WTSSESSION_NOTIFICATION = extern struct { cbSize: u32, dwSessionId: u32, }; //-------------------------------------------------------------------------------- // Section: Functions (65) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSStopRemoteControlSession( LogonId: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSStartRemoteControlSessionW( pTargetServerName: ?PWSTR, TargetLogonId: u32, HotkeyVk: u8, HotkeyModifiers: u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSStartRemoteControlSessionA( pTargetServerName: ?PSTR, TargetLogonId: u32, HotkeyVk: u8, HotkeyModifiers: u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSConnectSessionA( LogonId: u32, TargetLogonId: u32, pPassword: ?PSTR, bWait: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSConnectSessionW( LogonId: u32, TargetLogonId: u32, pPassword: ?PWSTR, bWait: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSEnumerateServersW( pDomainName: ?PWSTR, Reserved: u32, Version: u32, ppServerInfo: ?*?*WTS_SERVER_INFOW, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSEnumerateServersA( pDomainName: ?PSTR, Reserved: u32, Version: u32, ppServerInfo: ?*?*WTS_SERVER_INFOA, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSOpenServerW( pServerName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSOpenServerA( pServerName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSOpenServerExW( pServerName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSOpenServerExA( pServerName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSCloseServer( hServer: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSEnumerateSessionsW( hServer: ?HANDLE, Reserved: u32, Version: u32, ppSessionInfo: ?*?*WTS_SESSION_INFOW, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSEnumerateSessionsA( hServer: ?HANDLE, Reserved: u32, Version: u32, ppSessionInfo: ?*?*WTS_SESSION_INFOA, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSEnumerateSessionsExW( hServer: ?HANDLE, pLevel: ?*u32, Filter: u32, ppSessionInfo: ?*?*WTS_SESSION_INFO_1W, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSEnumerateSessionsExA( hServer: ?HANDLE, pLevel: ?*u32, Filter: u32, ppSessionInfo: ?*?*WTS_SESSION_INFO_1A, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSEnumerateProcessesW( hServer: ?HANDLE, Reserved: u32, Version: u32, ppProcessInfo: ?*?*WTS_PROCESS_INFOW, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSEnumerateProcessesA( hServer: ?HANDLE, Reserved: u32, Version: u32, ppProcessInfo: ?*?*WTS_PROCESS_INFOA, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSTerminateProcess( hServer: ?HANDLE, ProcessId: u32, ExitCode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSQuerySessionInformationW( hServer: ?HANDLE, SessionId: u32, WTSInfoClass: WTS_INFO_CLASS, ppBuffer: ?*?PWSTR, pBytesReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSQuerySessionInformationA( hServer: ?HANDLE, SessionId: u32, WTSInfoClass: WTS_INFO_CLASS, ppBuffer: ?*?PSTR, pBytesReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSQueryUserConfigW( pServerName: ?PWSTR, pUserName: ?PWSTR, WTSConfigClass: WTS_CONFIG_CLASS, ppBuffer: ?*?PWSTR, pBytesReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSQueryUserConfigA( pServerName: ?PSTR, pUserName: ?PSTR, WTSConfigClass: WTS_CONFIG_CLASS, ppBuffer: ?*?PSTR, pBytesReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSSetUserConfigW( pServerName: ?PWSTR, pUserName: ?PWSTR, WTSConfigClass: WTS_CONFIG_CLASS, // TODO: what to do with BytesParamIndex 4? pBuffer: ?PWSTR, DataLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSSetUserConfigA( pServerName: ?PSTR, pUserName: ?PSTR, WTSConfigClass: WTS_CONFIG_CLASS, // TODO: what to do with BytesParamIndex 4? pBuffer: ?PSTR, DataLength: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSSendMessageW( hServer: ?HANDLE, SessionId: u32, // TODO: what to do with BytesParamIndex 3? pTitle: ?PWSTR, TitleLength: u32, // TODO: what to do with BytesParamIndex 5? pMessage: ?PWSTR, MessageLength: u32, Style: MESSAGEBOX_STYLE, Timeout: u32, pResponse: ?*MESSAGEBOX_RESULT, bWait: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSSendMessageA( hServer: ?HANDLE, SessionId: u32, // TODO: what to do with BytesParamIndex 3? pTitle: ?PSTR, TitleLength: u32, // TODO: what to do with BytesParamIndex 5? pMessage: ?PSTR, MessageLength: u32, Style: MESSAGEBOX_STYLE, Timeout: u32, pResponse: ?*MESSAGEBOX_RESULT, bWait: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSDisconnectSession( hServer: ?HANDLE, SessionId: u32, bWait: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSLogoffSession( hServer: ?HANDLE, SessionId: u32, bWait: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSShutdownSystem( hServer: ?HANDLE, ShutdownFlag: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSWaitSystemEvent( hServer: ?HANDLE, EventMask: u32, pEventFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSVirtualChannelOpen( hServer: ?HANDLE, SessionId: u32, pVirtualName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) HwtsVirtualChannelHandle; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSVirtualChannelOpenEx( SessionId: u32, pVirtualName: ?PSTR, flags: u32, ) callconv(@import("std").os.windows.WINAPI) HwtsVirtualChannelHandle; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSVirtualChannelClose( hChannelHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSVirtualChannelRead( hChannelHandle: ?HANDLE, TimeOut: u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?[*]u8, BufferSize: u32, pBytesRead: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSVirtualChannelWrite( hChannelHandle: ?HANDLE, // TODO: what to do with BytesParamIndex 2? Buffer: ?[*]u8, Length: u32, pBytesWritten: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSVirtualChannelPurgeInput( hChannelHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSVirtualChannelPurgeOutput( hChannelHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSVirtualChannelQuery( hChannelHandle: ?HANDLE, param1: WTS_VIRTUAL_CLASS, ppBuffer: ?*?*anyopaque, pBytesReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSFreeMemory( pMemory: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSRegisterSessionNotification( hWnd: ?HWND, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSUnRegisterSessionNotification( hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSRegisterSessionNotificationEx( hServer: ?HANDLE, hWnd: ?HWND, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSUnRegisterSessionNotificationEx( hServer: ?HANDLE, hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WTSAPI32" fn WTSQueryUserToken( SessionId: u32, phToken: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSFreeMemoryExW( WTSTypeClass: WTS_TYPE_CLASS, pMemory: ?*anyopaque, NumberOfEntries: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSFreeMemoryExA( WTSTypeClass: WTS_TYPE_CLASS, pMemory: ?*anyopaque, NumberOfEntries: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSEnumerateProcessesExW( hServer: ?HANDLE, pLevel: ?*u32, SessionId: u32, ppProcessInfo: ?*?PWSTR, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSEnumerateProcessesExA( hServer: ?HANDLE, pLevel: ?*u32, SessionId: u32, ppProcessInfo: ?*?PSTR, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSEnumerateListenersW( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListeners: ?[*]?*u16, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSEnumerateListenersA( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListeners: ?[*]?*i8, pCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSQueryListenerConfigW( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListenerName: ?PWSTR, pBuffer: ?*WTSLISTENERCONFIGW, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSQueryListenerConfigA( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListenerName: ?PSTR, pBuffer: ?*WTSLISTENERCONFIGA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSCreateListenerW( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListenerName: ?PWSTR, pBuffer: ?*WTSLISTENERCONFIGW, flag: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSCreateListenerA( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListenerName: ?PSTR, pBuffer: ?*WTSLISTENERCONFIGA, flag: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSSetListenerSecurityW( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListenerName: ?PWSTR, SecurityInformation: u32, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSSetListenerSecurityA( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListenerName: ?PSTR, SecurityInformation: u32, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSGetListenerSecurityW( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListenerName: ?PWSTR, SecurityInformation: u32, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, nLength: u32, lpnLengthNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "WTSAPI32" fn WTSGetListenerSecurityA( hServer: ?HANDLE, pReserved: ?*anyopaque, Reserved: u32, pListenerName: ?PSTR, SecurityInformation: u32, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, nLength: u32, lpnLengthNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "WTSAPI32" fn WTSEnableChildSessions( bEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "WTSAPI32" fn WTSIsChildSessionsEnabled( pbEnabled: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "WTSAPI32" fn WTSGetChildSessionId( pSessionId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "WTSAPI32" fn WTSSetRenderHint( pRenderHintID: ?*u64, hwndOwner: ?HWND, renderHintType: u32, cbHintDataLength: u32, // TODO: what to do with BytesParamIndex 3? pHintData: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "KERNEL32" fn ProcessIdToSessionId( dwProcessId: u32, pSessionId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "KERNEL32" fn WTSGetActiveConsoleSessionId( ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (34) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const WTS_SERVER_INFO = thismodule.WTS_SERVER_INFOA; pub const WTS_SESSION_INFO = thismodule.WTS_SESSION_INFOA; pub const WTS_SESSION_INFO_1 = thismodule.WTS_SESSION_INFO_1A; pub const WTS_PROCESS_INFO = thismodule.WTS_PROCESS_INFOA; pub const WTSCONFIGINFO = thismodule.WTSCONFIGINFOA; pub const WTSINFO = thismodule.WTSINFOA; pub const WTSINFOEX_LEVEL1_ = thismodule.WTSINFOEX_LEVEL1_A; pub const WTSINFOEX_LEVEL_ = thismodule.WTSINFOEX_LEVEL_A; pub const WTSINFOEX = thismodule.WTSINFOEXA; pub const WTSCLIENT = thismodule.WTSCLIENTA; pub const _WTS_PRODUCT_INFO = thismodule._WTS_PRODUCT_INFOA; pub const WTS_VALIDATION_INFORMATION = thismodule.WTS_VALIDATION_INFORMATIONA; pub const WTSUSERCONFIG = thismodule.WTSUSERCONFIGA; pub const WTS_PROCESS_INFO_EX = thismodule.WTS_PROCESS_INFO_EXA; pub const WTSLISTENERCONFIG = thismodule.WTSLISTENERCONFIGA; pub const WTSStartRemoteControlSession = thismodule.WTSStartRemoteControlSessionA; pub const WTSConnectSession = thismodule.WTSConnectSessionA; pub const WTSEnumerateServers = thismodule.WTSEnumerateServersA; pub const WTSOpenServer = thismodule.WTSOpenServerA; pub const WTSOpenServerEx = thismodule.WTSOpenServerExA; pub const WTSEnumerateSessions = thismodule.WTSEnumerateSessionsA; pub const WTSEnumerateSessionsEx = thismodule.WTSEnumerateSessionsExA; pub const WTSEnumerateProcesses = thismodule.WTSEnumerateProcessesA; pub const WTSQuerySessionInformation = thismodule.WTSQuerySessionInformationA; pub const WTSQueryUserConfig = thismodule.WTSQueryUserConfigA; pub const WTSSetUserConfig = thismodule.WTSSetUserConfigA; pub const WTSSendMessage = thismodule.WTSSendMessageA; pub const WTSFreeMemoryEx = thismodule.WTSFreeMemoryExA; pub const WTSEnumerateProcessesEx = thismodule.WTSEnumerateProcessesExA; pub const WTSEnumerateListeners = thismodule.WTSEnumerateListenersA; pub const WTSQueryListenerConfig = thismodule.WTSQueryListenerConfigA; pub const WTSCreateListener = thismodule.WTSCreateListenerA; pub const WTSSetListenerSecurity = thismodule.WTSSetListenerSecurityA; pub const WTSGetListenerSecurity = thismodule.WTSGetListenerSecurityA; }, .wide => struct { pub const WTS_SERVER_INFO = thismodule.WTS_SERVER_INFOW; pub const WTS_SESSION_INFO = thismodule.WTS_SESSION_INFOW; pub const WTS_SESSION_INFO_1 = thismodule.WTS_SESSION_INFO_1W; pub const WTS_PROCESS_INFO = thismodule.WTS_PROCESS_INFOW; pub const WTSCONFIGINFO = thismodule.WTSCONFIGINFOW; pub const WTSINFO = thismodule.WTSINFOW; pub const WTSINFOEX_LEVEL1_ = thismodule.WTSINFOEX_LEVEL1_W; pub const WTSINFOEX_LEVEL_ = thismodule.WTSINFOEX_LEVEL_W; pub const WTSINFOEX = thismodule.WTSINFOEXW; pub const WTSCLIENT = thismodule.WTSCLIENTW; pub const _WTS_PRODUCT_INFO = thismodule._WTS_PRODUCT_INFOW; pub const WTS_VALIDATION_INFORMATION = thismodule.WTS_VALIDATION_INFORMATIONW; pub const WTSUSERCONFIG = thismodule.WTSUSERCONFIGW; pub const WTS_PROCESS_INFO_EX = thismodule.WTS_PROCESS_INFO_EXW; pub const WTSLISTENERCONFIG = thismodule.WTSLISTENERCONFIGW; pub const WTSStartRemoteControlSession = thismodule.WTSStartRemoteControlSessionW; pub const WTSConnectSession = thismodule.WTSConnectSessionW; pub const WTSEnumerateServers = thismodule.WTSEnumerateServersW; pub const WTSOpenServer = thismodule.WTSOpenServerW; pub const WTSOpenServerEx = thismodule.WTSOpenServerExW; pub const WTSEnumerateSessions = thismodule.WTSEnumerateSessionsW; pub const WTSEnumerateSessionsEx = thismodule.WTSEnumerateSessionsExW; pub const WTSEnumerateProcesses = thismodule.WTSEnumerateProcessesW; pub const WTSQuerySessionInformation = thismodule.WTSQuerySessionInformationW; pub const WTSQueryUserConfig = thismodule.WTSQueryUserConfigW; pub const WTSSetUserConfig = thismodule.WTSSetUserConfigW; pub const WTSSendMessage = thismodule.WTSSendMessageW; pub const WTSFreeMemoryEx = thismodule.WTSFreeMemoryExW; pub const WTSEnumerateProcessesEx = thismodule.WTSEnumerateProcessesExW; pub const WTSEnumerateListeners = thismodule.WTSEnumerateListenersW; pub const WTSQueryListenerConfig = thismodule.WTSQueryListenerConfigW; pub const WTSCreateListener = thismodule.WTSCreateListenerW; pub const WTSSetListenerSecurity = thismodule.WTSSetListenerSecurityW; pub const WTSGetListenerSecurity = thismodule.WTSGetListenerSecurityW; }, .unspecified => if (@import("builtin").is_test) struct { pub const WTS_SERVER_INFO = *opaque{}; pub const WTS_SESSION_INFO = *opaque{}; pub const WTS_SESSION_INFO_1 = *opaque{}; pub const WTS_PROCESS_INFO = *opaque{}; pub const WTSCONFIGINFO = *opaque{}; pub const WTSINFO = *opaque{}; pub const WTSINFOEX_LEVEL1_ = *opaque{}; pub const WTSINFOEX_LEVEL_ = *opaque{}; pub const WTSINFOEX = *opaque{}; pub const WTSCLIENT = *opaque{}; pub const _WTS_PRODUCT_INFO = *opaque{}; pub const WTS_VALIDATION_INFORMATION = *opaque{}; pub const WTSUSERCONFIG = *opaque{}; pub const WTS_PROCESS_INFO_EX = *opaque{}; pub const WTSLISTENERCONFIG = *opaque{}; pub const WTSStartRemoteControlSession = *opaque{}; pub const WTSConnectSession = *opaque{}; pub const WTSEnumerateServers = *opaque{}; pub const WTSOpenServer = *opaque{}; pub const WTSOpenServerEx = *opaque{}; pub const WTSEnumerateSessions = *opaque{}; pub const WTSEnumerateSessionsEx = *opaque{}; pub const WTSEnumerateProcesses = *opaque{}; pub const WTSQuerySessionInformation = *opaque{}; pub const WTSQueryUserConfig = *opaque{}; pub const WTSSetUserConfig = *opaque{}; pub const WTSSendMessage = *opaque{}; pub const WTSFreeMemoryEx = *opaque{}; pub const WTSEnumerateProcessesEx = *opaque{}; pub const WTSEnumerateListeners = *opaque{}; pub const WTSQueryListenerConfig = *opaque{}; pub const WTSCreateListener = *opaque{}; pub const WTSSetListenerSecurity = *opaque{}; pub const WTSGetListenerSecurity = *opaque{}; } else struct { pub const WTS_SERVER_INFO = @compileError("'WTS_SERVER_INFO' requires that UNICODE be set to true or false in the root module"); pub const WTS_SESSION_INFO = @compileError("'WTS_SESSION_INFO' requires that UNICODE be set to true or false in the root module"); pub const WTS_SESSION_INFO_1 = @compileError("'WTS_SESSION_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const WTS_PROCESS_INFO = @compileError("'WTS_PROCESS_INFO' requires that UNICODE be set to true or false in the root module"); pub const WTSCONFIGINFO = @compileError("'WTSCONFIGINFO' requires that UNICODE be set to true or false in the root module"); pub const WTSINFO = @compileError("'WTSINFO' requires that UNICODE be set to true or false in the root module"); pub const WTSINFOEX_LEVEL1_ = @compileError("'WTSINFOEX_LEVEL1_' requires that UNICODE be set to true or false in the root module"); pub const WTSINFOEX_LEVEL_ = @compileError("'WTSINFOEX_LEVEL_' requires that UNICODE be set to true or false in the root module"); pub const WTSINFOEX = @compileError("'WTSINFOEX' requires that UNICODE be set to true or false in the root module"); pub const WTSCLIENT = @compileError("'WTSCLIENT' requires that UNICODE be set to true or false in the root module"); pub const _WTS_PRODUCT_INFO = @compileError("'_WTS_PRODUCT_INFO' requires that UNICODE be set to true or false in the root module"); pub const WTS_VALIDATION_INFORMATION = @compileError("'WTS_VALIDATION_INFORMATION' requires that UNICODE be set to true or false in the root module"); pub const WTSUSERCONFIG = @compileError("'WTSUSERCONFIG' requires that UNICODE be set to true or false in the root module"); pub const WTS_PROCESS_INFO_EX = @compileError("'WTS_PROCESS_INFO_EX' requires that UNICODE be set to true or false in the root module"); pub const WTSLISTENERCONFIG = @compileError("'WTSLISTENERCONFIG' requires that UNICODE be set to true or false in the root module"); pub const WTSStartRemoteControlSession = @compileError("'WTSStartRemoteControlSession' requires that UNICODE be set to true or false in the root module"); pub const WTSConnectSession = @compileError("'WTSConnectSession' requires that UNICODE be set to true or false in the root module"); pub const WTSEnumerateServers = @compileError("'WTSEnumerateServers' requires that UNICODE be set to true or false in the root module"); pub const WTSOpenServer = @compileError("'WTSOpenServer' requires that UNICODE be set to true or false in the root module"); pub const WTSOpenServerEx = @compileError("'WTSOpenServerEx' requires that UNICODE be set to true or false in the root module"); pub const WTSEnumerateSessions = @compileError("'WTSEnumerateSessions' requires that UNICODE be set to true or false in the root module"); pub const WTSEnumerateSessionsEx = @compileError("'WTSEnumerateSessionsEx' requires that UNICODE be set to true or false in the root module"); pub const WTSEnumerateProcesses = @compileError("'WTSEnumerateProcesses' requires that UNICODE be set to true or false in the root module"); pub const WTSQuerySessionInformation = @compileError("'WTSQuerySessionInformation' requires that UNICODE be set to true or false in the root module"); pub const WTSQueryUserConfig = @compileError("'WTSQueryUserConfig' requires that UNICODE be set to true or false in the root module"); pub const WTSSetUserConfig = @compileError("'WTSSetUserConfig' requires that UNICODE be set to true or false in the root module"); pub const WTSSendMessage = @compileError("'WTSSendMessage' requires that UNICODE be set to true or false in the root module"); pub const WTSFreeMemoryEx = @compileError("'WTSFreeMemoryEx' requires that UNICODE be set to true or false in the root module"); pub const WTSEnumerateProcessesEx = @compileError("'WTSEnumerateProcessesEx' requires that UNICODE be set to true or false in the root module"); pub const WTSEnumerateListeners = @compileError("'WTSEnumerateListeners' requires that UNICODE be set to true or false in the root module"); pub const WTSQueryListenerConfig = @compileError("'WTSQueryListenerConfig' requires that UNICODE be set to true or false in the root module"); pub const WTSCreateListener = @compileError("'WTSCreateListener' requires that UNICODE be set to true or false in the root module"); pub const WTSSetListenerSecurity = @compileError("'WTSSetListenerSecurity' requires that UNICODE be set to true or false in the root module"); pub const WTSGetListenerSecurity = @compileError("'WTSGetListenerSecurity' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (26) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const APO_CONNECTION_PROPERTY = @import("../media/audio/apo.zig").APO_CONNECTION_PROPERTY; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const BSTR = @import("../foundation.zig").BSTR; const CHAR = @import("../foundation.zig").CHAR; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HANDLE_PTR = @import("../foundation.zig").HANDLE_PTR; const HRESULT = @import("../foundation.zig").HRESULT; const HSTRING = @import("../system/win_rt.zig").HSTRING; const HWND = @import("../foundation.zig").HWND; const IDispatch = @import("../system/com.zig").IDispatch; const IPropertyBag = @import("../system/com/structured_storage.zig").IPropertyBag; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const MESSAGEBOX_RESULT = @import("../ui/windows_and_messaging.zig").MESSAGEBOX_RESULT; const MESSAGEBOX_STYLE = @import("../ui/windows_and_messaging.zig").MESSAGEBOX_STYLE; const PSID = @import("../foundation.zig").PSID; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const RECT = @import("../foundation.zig").RECT; const SAFEARRAY = @import("../system/com.zig").SAFEARRAY; const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR; const VARIANT = @import("../system/com.zig").VARIANT; 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(), "PCHANNEL_INIT_EVENT_FN")) { _ = PCHANNEL_INIT_EVENT_FN; } if (@hasDecl(@This(), "PCHANNEL_OPEN_EVENT_FN")) { _ = PCHANNEL_OPEN_EVENT_FN; } if (@hasDecl(@This(), "PVIRTUALCHANNELINIT")) { _ = PVIRTUALCHANNELINIT; } if (@hasDecl(@This(), "PVIRTUALCHANNELOPEN")) { _ = PVIRTUALCHANNELOPEN; } if (@hasDecl(@This(), "PVIRTUALCHANNELCLOSE")) { _ = PVIRTUALCHANNELCLOSE; } if (@hasDecl(@This(), "PVIRTUALCHANNELWRITE")) { _ = PVIRTUALCHANNELWRITE; } if (@hasDecl(@This(), "PVIRTUALCHANNELENTRY")) { _ = PVIRTUALCHANNELENTRY; } @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/system/remote_desktop.zig
pub const EXTENDED_BIT = @as(u32, 16777216); pub const DONTCARE_BIT = @as(u32, 33554432); pub const FAKE_KEYSTROKE = @as(u32, 33554432); pub const KBDBASE = @as(u32, 0); pub const KBDSHIFT = @as(u32, 1); pub const KBDCTRL = @as(u32, 2); pub const KBDALT = @as(u32, 4); pub const KBDKANA = @as(u32, 8); pub const KBDROYA = @as(u32, 16); pub const KBDLOYA = @as(u32, 32); pub const KBDGRPSELTAP = @as(u32, 128); pub const GRAVE = @as(u32, 768); pub const ACUTE = @as(u32, 769); pub const CIRCUMFLEX = @as(u32, 770); pub const TILDE = @as(u32, 771); pub const MACRON = @as(u32, 772); pub const OVERSCORE = @as(u32, 773); pub const BREVE = @as(u32, 774); pub const DOT_ABOVE = @as(u32, 775); pub const UMLAUT = @as(u32, 776); pub const DIARESIS = @as(u32, 776); pub const HOOK_ABOVE = @as(u32, 777); pub const RING = @as(u32, 778); pub const DOUBLE_ACUTE = @as(u32, 779); pub const HACEK = @as(u32, 780); pub const CEDILLA = @as(u32, 807); pub const OGONEK = @as(u32, 808); pub const TONOS = @as(u32, 900); pub const DIARESIS_TONOS = @as(u32, 901); pub const SHFT_INVALID = @as(u32, 15); pub const WCH_NONE = @as(u32, 61440); pub const WCH_DEAD = @as(u32, 61441); pub const WCH_LGTR = @as(u32, 61442); pub const CAPLOK = @as(u32, 1); pub const SGCAPS = @as(u32, 2); pub const CAPLOKALTGR = @as(u32, 4); pub const KANALOK = @as(u32, 8); pub const GRPSELTAP = @as(u32, 128); pub const DKF_DEAD = @as(u32, 1); pub const KBD_VERSION = @as(u32, 1); pub const KLLF_ALTGR = @as(u32, 1); pub const KLLF_SHIFTLOCK = @as(u32, 2); pub const KLLF_LRM_RLM = @as(u32, 4); pub const KLLF_GLOBAL_ATTRS = @as(u32, 2); pub const KBDTABLE_MULTI_MAX = @as(u32, 8); pub const KEYBOARD_TYPE_GENERIC_101 = @as(u32, 4); pub const KEYBOARD_TYPE_JAPAN = @as(u32, 7); pub const KEYBOARD_TYPE_KOREA = @as(u32, 8); pub const KEYBOARD_TYPE_UNKNOWN = @as(u32, 81); pub const NLSKBD_OEM_MICROSOFT = @as(u32, 0); pub const NLSKBD_OEM_AX = @as(u32, 1); pub const NLSKBD_OEM_EPSON = @as(u32, 4); pub const NLSKBD_OEM_FUJITSU = @as(u32, 5); pub const NLSKBD_OEM_IBM = @as(u32, 7); pub const NLSKBD_OEM_MATSUSHITA = @as(u32, 10); pub const NLSKBD_OEM_NEC = @as(u32, 13); pub const NLSKBD_OEM_TOSHIBA = @as(u32, 18); pub const NLSKBD_OEM_DEC = @as(u32, 24); pub const MICROSOFT_KBD_101_TYPE = @as(u32, 0); pub const MICROSOFT_KBD_AX_TYPE = @as(u32, 1); pub const MICROSOFT_KBD_106_TYPE = @as(u32, 2); pub const MICROSOFT_KBD_002_TYPE = @as(u32, 3); pub const MICROSOFT_KBD_001_TYPE = @as(u32, 4); pub const MICROSOFT_KBD_FUNC = @as(u32, 12); pub const AX_KBD_DESKTOP_TYPE = @as(u32, 1); pub const FMR_KBD_JIS_TYPE = @as(u32, 0); pub const FMR_KBD_OASYS_TYPE = @as(u32, 1); pub const FMV_KBD_OASYS_TYPE = @as(u32, 2); pub const NEC_KBD_NORMAL_TYPE = @as(u32, 1); pub const NEC_KBD_N_MODE_TYPE = @as(u32, 2); pub const NEC_KBD_H_MODE_TYPE = @as(u32, 3); pub const NEC_KBD_LAPTOP_TYPE = @as(u32, 4); pub const NEC_KBD_106_TYPE = @as(u32, 5); pub const TOSHIBA_KBD_DESKTOP_TYPE = @as(u32, 13); pub const TOSHIBA_KBD_LAPTOP_TYPE = @as(u32, 15); pub const DEC_KBD_ANSI_LAYOUT_TYPE = @as(u32, 1); pub const DEC_KBD_JIS_LAYOUT_TYPE = @as(u32, 2); pub const MICROSOFT_KBD_101A_TYPE = @as(u32, 0); pub const MICROSOFT_KBD_101B_TYPE = @as(u32, 4); pub const MICROSOFT_KBD_101C_TYPE = @as(u32, 5); pub const MICROSOFT_KBD_103_TYPE = @as(u32, 6); pub const NLSKBD_INFO_SEND_IME_NOTIFICATION = @as(u32, 1); pub const NLSKBD_INFO_ACCESSIBILITY_KEYMAP = @as(u32, 2); pub const NLSKBD_INFO_EMURATE_101_KEYBOARD = @as(u32, 16); pub const NLSKBD_INFO_EMURATE_106_KEYBOARD = @as(u32, 32); pub const KBDNLS_TYPE_NULL = @as(u32, 0); pub const KBDNLS_TYPE_NORMAL = @as(u32, 1); pub const KBDNLS_TYPE_TOGGLE = @as(u32, 2); pub const KBDNLS_INDEX_NORMAL = @as(u32, 1); pub const KBDNLS_INDEX_ALT = @as(u32, 2); pub const KBDNLS_NULL = @as(u32, 0); pub const KBDNLS_NOEVENT = @as(u32, 1); pub const KBDNLS_SEND_BASE_VK = @as(u32, 2); pub const KBDNLS_SEND_PARAM_VK = @as(u32, 3); pub const KBDNLS_KANALOCK = @as(u32, 4); pub const KBDNLS_ALPHANUM = @as(u32, 5); pub const KBDNLS_HIRAGANA = @as(u32, 6); pub const KBDNLS_KATAKANA = @as(u32, 7); pub const KBDNLS_SBCSDBCS = @as(u32, 8); pub const KBDNLS_ROMAN = @as(u32, 9); pub const KBDNLS_CODEINPUT = @as(u32, 10); pub const KBDNLS_HELP_OR_END = @as(u32, 11); pub const KBDNLS_HOME_OR_CLEAR = @as(u32, 12); pub const KBDNLS_NUMPAD = @as(u32, 13); pub const KBDNLS_KANAEVENT = @as(u32, 14); pub const KBDNLS_CONV_OR_NONCONV = @as(u32, 15); pub const KBD_TYPE = @as(u32, 4); pub const VK__none_ = @as(u32, 255); pub const VK_ABNT_C1 = @as(u32, 193); pub const VK_ABNT_C2 = @as(u32, 194); pub const SCANCODE_LSHIFT = @as(u32, 42); pub const SCANCODE_RSHIFT = @as(u32, 54); pub const SCANCODE_CTRL = @as(u32, 29); pub const SCANCODE_ALT = @as(u32, 56); pub const SCANCODE_NUMPAD_FIRST = @as(u32, 71); pub const SCANCODE_NUMPAD_LAST = @as(u32, 82); pub const SCANCODE_LWIN = @as(u32, 91); pub const SCANCODE_RWIN = @as(u32, 92); pub const SCANCODE_THAI_LAYOUT_TOGGLE = @as(u32, 41); pub const VK_DBE_ALPHANUMERIC = @as(u32, 240); pub const VK_DBE_KATAKANA = @as(u32, 241); pub const VK_DBE_HIRAGANA = @as(u32, 242); pub const VK_DBE_SBCSCHAR = @as(u32, 243); pub const VK_DBE_DBCSCHAR = @as(u32, 244); pub const VK_DBE_ROMAN = @as(u32, 245); pub const VK_DBE_NOROMAN = @as(u32, 246); pub const VK_DBE_ENTERWORDREGISTERMODE = @as(u32, 247); pub const VK_DBE_ENTERIMECONFIGMODE = @as(u32, 248); pub const VK_DBE_FLUSHSTRING = @as(u32, 249); pub const VK_DBE_CODEINPUT = @as(u32, 250); pub const VK_DBE_NOCODEINPUT = @as(u32, 251); pub const VK_DBE_DETERMINESTRING = @as(u32, 252); pub const VK_DBE_ENTERDLGCONVERSIONMODE = @as(u32, 253); //-------------------------------------------------------------------------------- // Section: Types (44) //-------------------------------------------------------------------------------- pub const HOT_KEY_MODIFIERS = enum(u32) { ALT = 1, CONTROL = 2, NOREPEAT = 16384, SHIFT = 4, WIN = 8, _, pub fn initFlags(o: struct { ALT: u1 = 0, CONTROL: u1 = 0, NOREPEAT: u1 = 0, SHIFT: u1 = 0, WIN: u1 = 0, }) HOT_KEY_MODIFIERS { return @intToEnum(HOT_KEY_MODIFIERS, (if (o.ALT == 1) @enumToInt(HOT_KEY_MODIFIERS.ALT) else 0) | (if (o.CONTROL == 1) @enumToInt(HOT_KEY_MODIFIERS.CONTROL) else 0) | (if (o.NOREPEAT == 1) @enumToInt(HOT_KEY_MODIFIERS.NOREPEAT) else 0) | (if (o.SHIFT == 1) @enumToInt(HOT_KEY_MODIFIERS.SHIFT) else 0) | (if (o.WIN == 1) @enumToInt(HOT_KEY_MODIFIERS.WIN) else 0) ); } }; pub const MOD_ALT = HOT_KEY_MODIFIERS.ALT; pub const MOD_CONTROL = HOT_KEY_MODIFIERS.CONTROL; pub const MOD_NOREPEAT = HOT_KEY_MODIFIERS.NOREPEAT; pub const MOD_SHIFT = HOT_KEY_MODIFIERS.SHIFT; pub const MOD_WIN = HOT_KEY_MODIFIERS.WIN; pub const ACTIVATE_KEYBOARD_LAYOUT_FLAGS = enum(u32) { REORDER = 8, RESET = 1073741824, SETFORPROCESS = 256, SHIFTLOCK = 65536, ACTIVATE = 1, NOTELLSHELL = 128, REPLACELANG = 16, SUBSTITUTE_OK = 2, }; pub const KLF_REORDER = ACTIVATE_KEYBOARD_LAYOUT_FLAGS.REORDER; pub const KLF_RESET = ACTIVATE_KEYBOARD_LAYOUT_FLAGS.RESET; pub const KLF_SETFORPROCESS = ACTIVATE_KEYBOARD_LAYOUT_FLAGS.SETFORPROCESS; pub const KLF_SHIFTLOCK = ACTIVATE_KEYBOARD_LAYOUT_FLAGS.SHIFTLOCK; pub const KLF_ACTIVATE = ACTIVATE_KEYBOARD_LAYOUT_FLAGS.ACTIVATE; pub const KLF_NOTELLSHELL = ACTIVATE_KEYBOARD_LAYOUT_FLAGS.NOTELLSHELL; pub const KLF_REPLACELANG = ACTIVATE_KEYBOARD_LAYOUT_FLAGS.REPLACELANG; pub const KLF_SUBSTITUTE_OK = ACTIVATE_KEYBOARD_LAYOUT_FLAGS.SUBSTITUTE_OK; pub const GET_MOUSE_MOVE_POINTS_EX_RESOLUTION = enum(u32) { DISPLAY_POINTS = 1, HIGH_RESOLUTION_POINTS = 2, }; pub const GMMP_USE_DISPLAY_POINTS = GET_MOUSE_MOVE_POINTS_EX_RESOLUTION.DISPLAY_POINTS; pub const GMMP_USE_HIGH_RESOLUTION_POINTS = GET_MOUSE_MOVE_POINTS_EX_RESOLUTION.HIGH_RESOLUTION_POINTS; pub const KEYBD_EVENT_FLAGS = enum(u32) { EXTENDEDKEY = 1, KEYUP = 2, SCANCODE = 8, UNICODE = 4, _, pub fn initFlags(o: struct { EXTENDEDKEY: u1 = 0, KEYUP: u1 = 0, SCANCODE: u1 = 0, UNICODE: u1 = 0, }) KEYBD_EVENT_FLAGS { return @intToEnum(KEYBD_EVENT_FLAGS, (if (o.EXTENDEDKEY == 1) @enumToInt(KEYBD_EVENT_FLAGS.EXTENDEDKEY) else 0) | (if (o.KEYUP == 1) @enumToInt(KEYBD_EVENT_FLAGS.KEYUP) else 0) | (if (o.SCANCODE == 1) @enumToInt(KEYBD_EVENT_FLAGS.SCANCODE) else 0) | (if (o.UNICODE == 1) @enumToInt(KEYBD_EVENT_FLAGS.UNICODE) else 0) ); } }; pub const KEYEVENTF_EXTENDEDKEY = KEYBD_EVENT_FLAGS.EXTENDEDKEY; pub const KEYEVENTF_KEYUP = KEYBD_EVENT_FLAGS.KEYUP; pub const KEYEVENTF_SCANCODE = KEYBD_EVENT_FLAGS.SCANCODE; pub const KEYEVENTF_UNICODE = KEYBD_EVENT_FLAGS.UNICODE; pub const MOUSE_EVENT_FLAGS = enum(u32) { ABSOLUTE = 32768, LEFTDOWN = 2, LEFTUP = 4, MIDDLEDOWN = 32, MIDDLEUP = 64, MOVE = 1, RIGHTDOWN = 8, RIGHTUP = 16, WHEEL = 2048, XDOWN = 128, XUP = 256, HWHEEL = 4096, MOVE_NOCOALESCE = 8192, VIRTUALDESK = 16384, _, pub fn initFlags(o: struct { ABSOLUTE: u1 = 0, LEFTDOWN: u1 = 0, LEFTUP: u1 = 0, MIDDLEDOWN: u1 = 0, MIDDLEUP: u1 = 0, MOVE: u1 = 0, RIGHTDOWN: u1 = 0, RIGHTUP: u1 = 0, WHEEL: u1 = 0, XDOWN: u1 = 0, XUP: u1 = 0, HWHEEL: u1 = 0, MOVE_NOCOALESCE: u1 = 0, VIRTUALDESK: u1 = 0, }) MOUSE_EVENT_FLAGS { return @intToEnum(MOUSE_EVENT_FLAGS, (if (o.ABSOLUTE == 1) @enumToInt(MOUSE_EVENT_FLAGS.ABSOLUTE) else 0) | (if (o.LEFTDOWN == 1) @enumToInt(MOUSE_EVENT_FLAGS.LEFTDOWN) else 0) | (if (o.LEFTUP == 1) @enumToInt(MOUSE_EVENT_FLAGS.LEFTUP) else 0) | (if (o.MIDDLEDOWN == 1) @enumToInt(MOUSE_EVENT_FLAGS.MIDDLEDOWN) else 0) | (if (o.MIDDLEUP == 1) @enumToInt(MOUSE_EVENT_FLAGS.MIDDLEUP) else 0) | (if (o.MOVE == 1) @enumToInt(MOUSE_EVENT_FLAGS.MOVE) else 0) | (if (o.RIGHTDOWN == 1) @enumToInt(MOUSE_EVENT_FLAGS.RIGHTDOWN) else 0) | (if (o.RIGHTUP == 1) @enumToInt(MOUSE_EVENT_FLAGS.RIGHTUP) else 0) | (if (o.WHEEL == 1) @enumToInt(MOUSE_EVENT_FLAGS.WHEEL) else 0) | (if (o.XDOWN == 1) @enumToInt(MOUSE_EVENT_FLAGS.XDOWN) else 0) | (if (o.XUP == 1) @enumToInt(MOUSE_EVENT_FLAGS.XUP) else 0) | (if (o.HWHEEL == 1) @enumToInt(MOUSE_EVENT_FLAGS.HWHEEL) else 0) | (if (o.MOVE_NOCOALESCE == 1) @enumToInt(MOUSE_EVENT_FLAGS.MOVE_NOCOALESCE) else 0) | (if (o.VIRTUALDESK == 1) @enumToInt(MOUSE_EVENT_FLAGS.VIRTUALDESK) else 0) ); } }; pub const MOUSEEVENTF_ABSOLUTE = MOUSE_EVENT_FLAGS.ABSOLUTE; pub const MOUSEEVENTF_LEFTDOWN = MOUSE_EVENT_FLAGS.LEFTDOWN; pub const MOUSEEVENTF_LEFTUP = MOUSE_EVENT_FLAGS.LEFTUP; pub const MOUSEEVENTF_MIDDLEDOWN = MOUSE_EVENT_FLAGS.MIDDLEDOWN; pub const MOUSEEVENTF_MIDDLEUP = MOUSE_EVENT_FLAGS.MIDDLEUP; pub const MOUSEEVENTF_MOVE = MOUSE_EVENT_FLAGS.MOVE; pub const MOUSEEVENTF_RIGHTDOWN = MOUSE_EVENT_FLAGS.RIGHTDOWN; pub const MOUSEEVENTF_RIGHTUP = MOUSE_EVENT_FLAGS.RIGHTUP; pub const MOUSEEVENTF_WHEEL = MOUSE_EVENT_FLAGS.WHEEL; pub const MOUSEEVENTF_XDOWN = MOUSE_EVENT_FLAGS.XDOWN; pub const MOUSEEVENTF_XUP = MOUSE_EVENT_FLAGS.XUP; pub const MOUSEEVENTF_HWHEEL = MOUSE_EVENT_FLAGS.HWHEEL; pub const MOUSEEVENTF_MOVE_NOCOALESCE = MOUSE_EVENT_FLAGS.MOVE_NOCOALESCE; pub const MOUSEEVENTF_VIRTUALDESK = MOUSE_EVENT_FLAGS.VIRTUALDESK; pub const INPUT_TYPE = enum(u32) { MOUSE = 0, KEYBOARD = 1, HARDWARE = 2, }; pub const INPUT_MOUSE = INPUT_TYPE.MOUSE; pub const INPUT_KEYBOARD = INPUT_TYPE.KEYBOARD; pub const INPUT_HARDWARE = INPUT_TYPE.HARDWARE; pub const TRACKMOUSEEVENT_FLAGS = enum(u32) { CANCEL = 2147483648, HOVER = 1, LEAVE = 2, NONCLIENT = 16, QUERY = 1073741824, _, pub fn initFlags(o: struct { CANCEL: u1 = 0, HOVER: u1 = 0, LEAVE: u1 = 0, NONCLIENT: u1 = 0, QUERY: u1 = 0, }) TRACKMOUSEEVENT_FLAGS { return @intToEnum(TRACKMOUSEEVENT_FLAGS, (if (o.CANCEL == 1) @enumToInt(TRACKMOUSEEVENT_FLAGS.CANCEL) else 0) | (if (o.HOVER == 1) @enumToInt(TRACKMOUSEEVENT_FLAGS.HOVER) else 0) | (if (o.LEAVE == 1) @enumToInt(TRACKMOUSEEVENT_FLAGS.LEAVE) else 0) | (if (o.NONCLIENT == 1) @enumToInt(TRACKMOUSEEVENT_FLAGS.NONCLIENT) else 0) | (if (o.QUERY == 1) @enumToInt(TRACKMOUSEEVENT_FLAGS.QUERY) else 0) ); } }; pub const TME_CANCEL = TRACKMOUSEEVENT_FLAGS.CANCEL; pub const TME_HOVER = TRACKMOUSEEVENT_FLAGS.HOVER; pub const TME_LEAVE = TRACKMOUSEEVENT_FLAGS.LEAVE; pub const TME_NONCLIENT = TRACKMOUSEEVENT_FLAGS.NONCLIENT; pub const TME_QUERY = TRACKMOUSEEVENT_FLAGS.QUERY; pub const VIRTUAL_KEY = enum(u16) { @"0" = 48, @"1" = 49, @"2" = 50, @"3" = 51, @"4" = 52, @"5" = 53, @"6" = 54, @"7" = 55, @"8" = 56, @"9" = 57, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, LBUTTON = 1, RBUTTON = 2, CANCEL = 3, MBUTTON = 4, XBUTTON1 = 5, XBUTTON2 = 6, BACK = 8, TAB = 9, CLEAR = 12, RETURN = 13, SHIFT = 16, CONTROL = 17, MENU = 18, PAUSE = 19, CAPITAL = 20, KANA = 21, // HANGEUL = 21, this enum value conflicts with KANA // HANGUL = 21, this enum value conflicts with KANA IME_ON = 22, JUNJA = 23, FINAL = 24, HANJA = 25, // KANJI = 25, this enum value conflicts with HANJA IME_OFF = 26, ESCAPE = 27, CONVERT = 28, NONCONVERT = 29, ACCEPT = 30, MODECHANGE = 31, SPACE = 32, PRIOR = 33, NEXT = 34, END = 35, HOME = 36, LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, SELECT = 41, PRINT = 42, EXECUTE = 43, SNAPSHOT = 44, INSERT = 45, DELETE = 46, HELP = 47, LWIN = 91, RWIN = 92, APPS = 93, SLEEP = 95, NUMPAD0 = 96, NUMPAD1 = 97, NUMPAD2 = 98, NUMPAD3 = 99, NUMPAD4 = 100, NUMPAD5 = 101, NUMPAD6 = 102, NUMPAD7 = 103, NUMPAD8 = 104, NUMPAD9 = 105, MULTIPLY = 106, ADD = 107, SEPARATOR = 108, SUBTRACT = 109, DECIMAL = 110, DIVIDE = 111, F1 = 112, F2 = 113, F3 = 114, F4 = 115, F5 = 116, F6 = 117, F7 = 118, F8 = 119, F9 = 120, F10 = 121, F11 = 122, F12 = 123, F13 = 124, F14 = 125, F15 = 126, F16 = 127, F17 = 128, F18 = 129, F19 = 130, F20 = 131, F21 = 132, F22 = 133, F23 = 134, F24 = 135, NAVIGATION_VIEW = 136, NAVIGATION_MENU = 137, NAVIGATION_UP = 138, NAVIGATION_DOWN = 139, NAVIGATION_LEFT = 140, NAVIGATION_RIGHT = 141, NAVIGATION_ACCEPT = 142, NAVIGATION_CANCEL = 143, NUMLOCK = 144, SCROLL = 145, OEM_NEC_EQUAL = 146, // OEM_FJ_JISHO = 146, this enum value conflicts with OEM_NEC_EQUAL OEM_FJ_MASSHOU = 147, OEM_FJ_TOUROKU = 148, OEM_FJ_LOYA = 149, OEM_FJ_ROYA = 150, LSHIFT = 160, RSHIFT = 161, LCONTROL = 162, RCONTROL = 163, LMENU = 164, RMENU = 165, BROWSER_BACK = 166, BROWSER_FORWARD = 167, BROWSER_REFRESH = 168, BROWSER_STOP = 169, BROWSER_SEARCH = 170, BROWSER_FAVORITES = 171, BROWSER_HOME = 172, VOLUME_MUTE = 173, VOLUME_DOWN = 174, VOLUME_UP = 175, MEDIA_NEXT_TRACK = 176, MEDIA_PREV_TRACK = 177, MEDIA_STOP = 178, MEDIA_PLAY_PAUSE = 179, LAUNCH_MAIL = 180, LAUNCH_MEDIA_SELECT = 181, LAUNCH_APP1 = 182, LAUNCH_APP2 = 183, OEM_1 = 186, OEM_PLUS = 187, OEM_COMMA = 188, OEM_MINUS = 189, OEM_PERIOD = 190, OEM_2 = 191, OEM_3 = 192, GAMEPAD_A = 195, GAMEPAD_B = 196, GAMEPAD_X = 197, GAMEPAD_Y = 198, GAMEPAD_RIGHT_SHOULDER = 199, GAMEPAD_LEFT_SHOULDER = 200, GAMEPAD_LEFT_TRIGGER = 201, GAMEPAD_RIGHT_TRIGGER = 202, GAMEPAD_DPAD_UP = 203, GAMEPAD_DPAD_DOWN = 204, GAMEPAD_DPAD_LEFT = 205, GAMEPAD_DPAD_RIGHT = 206, GAMEPAD_MENU = 207, GAMEPAD_VIEW = 208, GAMEPAD_LEFT_THUMBSTICK_BUTTON = 209, GAMEPAD_RIGHT_THUMBSTICK_BUTTON = 210, GAMEPAD_LEFT_THUMBSTICK_UP = 211, GAMEPAD_LEFT_THUMBSTICK_DOWN = 212, GAMEPAD_LEFT_THUMBSTICK_RIGHT = 213, GAMEPAD_LEFT_THUMBSTICK_LEFT = 214, GAMEPAD_RIGHT_THUMBSTICK_UP = 215, GAMEPAD_RIGHT_THUMBSTICK_DOWN = 216, GAMEPAD_RIGHT_THUMBSTICK_RIGHT = 217, GAMEPAD_RIGHT_THUMBSTICK_LEFT = 218, OEM_4 = 219, OEM_5 = 220, OEM_6 = 221, OEM_7 = 222, OEM_8 = 223, OEM_AX = 225, OEM_102 = 226, ICO_HELP = 227, ICO_00 = 228, PROCESSKEY = 229, ICO_CLEAR = 230, PACKET = 231, OEM_RESET = 233, OEM_JUMP = 234, OEM_PA1 = 235, OEM_PA2 = 236, OEM_PA3 = 237, OEM_WSCTRL = 238, OEM_CUSEL = 239, OEM_ATTN = 240, OEM_FINISH = 241, OEM_COPY = 242, OEM_AUTO = 243, OEM_ENLW = 244, OEM_BACKTAB = 245, ATTN = 246, CRSEL = 247, EXSEL = 248, EREOF = 249, PLAY = 250, ZOOM = 251, NONAME = 252, PA1 = 253, OEM_CLEAR = 254, }; pub const VK_0 = VIRTUAL_KEY.@"0"; pub const VK_1 = VIRTUAL_KEY.@"1"; pub const VK_2 = VIRTUAL_KEY.@"2"; pub const VK_3 = VIRTUAL_KEY.@"3"; pub const VK_4 = VIRTUAL_KEY.@"4"; pub const VK_5 = VIRTUAL_KEY.@"5"; pub const VK_6 = VIRTUAL_KEY.@"6"; pub const VK_7 = VIRTUAL_KEY.@"7"; pub const VK_8 = VIRTUAL_KEY.@"8"; pub const VK_9 = VIRTUAL_KEY.@"9"; pub const VK_A = VIRTUAL_KEY.A; pub const VK_B = VIRTUAL_KEY.B; pub const VK_C = VIRTUAL_KEY.C; pub const VK_D = VIRTUAL_KEY.D; pub const VK_E = VIRTUAL_KEY.E; pub const VK_F = VIRTUAL_KEY.F; pub const VK_G = VIRTUAL_KEY.G; pub const VK_H = VIRTUAL_KEY.H; pub const VK_I = VIRTUAL_KEY.I; pub const VK_J = VIRTUAL_KEY.J; pub const VK_K = VIRTUAL_KEY.K; pub const VK_L = VIRTUAL_KEY.L; pub const VK_M = VIRTUAL_KEY.M; pub const VK_N = VIRTUAL_KEY.N; pub const VK_O = VIRTUAL_KEY.O; pub const VK_P = VIRTUAL_KEY.P; pub const VK_Q = VIRTUAL_KEY.Q; pub const VK_R = VIRTUAL_KEY.R; pub const VK_S = VIRTUAL_KEY.S; pub const VK_T = VIRTUAL_KEY.T; pub const VK_U = VIRTUAL_KEY.U; pub const VK_V = VIRTUAL_KEY.V; pub const VK_W = VIRTUAL_KEY.W; pub const VK_X = VIRTUAL_KEY.X; pub const VK_Y = VIRTUAL_KEY.Y; pub const VK_Z = VIRTUAL_KEY.Z; pub const VK_LBUTTON = VIRTUAL_KEY.LBUTTON; pub const VK_RBUTTON = VIRTUAL_KEY.RBUTTON; pub const VK_CANCEL = VIRTUAL_KEY.CANCEL; pub const VK_MBUTTON = VIRTUAL_KEY.MBUTTON; pub const VK_XBUTTON1 = VIRTUAL_KEY.XBUTTON1; pub const VK_XBUTTON2 = VIRTUAL_KEY.XBUTTON2; pub const VK_BACK = VIRTUAL_KEY.BACK; pub const VK_TAB = VIRTUAL_KEY.TAB; pub const VK_CLEAR = VIRTUAL_KEY.CLEAR; pub const VK_RETURN = VIRTUAL_KEY.RETURN; pub const VK_SHIFT = VIRTUAL_KEY.SHIFT; pub const VK_CONTROL = VIRTUAL_KEY.CONTROL; pub const VK_MENU = VIRTUAL_KEY.MENU; pub const VK_PAUSE = VIRTUAL_KEY.PAUSE; pub const VK_CAPITAL = VIRTUAL_KEY.CAPITAL; pub const VK_KANA = VIRTUAL_KEY.KANA; pub const VK_HANGEUL = VIRTUAL_KEY.KANA; pub const VK_HANGUL = VIRTUAL_KEY.KANA; pub const VK_IME_ON = VIRTUAL_KEY.IME_ON; pub const VK_JUNJA = VIRTUAL_KEY.JUNJA; pub const VK_FINAL = VIRTUAL_KEY.FINAL; pub const VK_HANJA = VIRTUAL_KEY.HANJA; pub const VK_KANJI = VIRTUAL_KEY.HANJA; pub const VK_IME_OFF = VIRTUAL_KEY.IME_OFF; pub const VK_ESCAPE = VIRTUAL_KEY.ESCAPE; pub const VK_CONVERT = VIRTUAL_KEY.CONVERT; pub const VK_NONCONVERT = VIRTUAL_KEY.NONCONVERT; pub const VK_ACCEPT = VIRTUAL_KEY.ACCEPT; pub const VK_MODECHANGE = VIRTUAL_KEY.MODECHANGE; pub const VK_SPACE = VIRTUAL_KEY.SPACE; pub const VK_PRIOR = VIRTUAL_KEY.PRIOR; pub const VK_NEXT = VIRTUAL_KEY.NEXT; pub const VK_END = VIRTUAL_KEY.END; pub const VK_HOME = VIRTUAL_KEY.HOME; pub const VK_LEFT = VIRTUAL_KEY.LEFT; pub const VK_UP = VIRTUAL_KEY.UP; pub const VK_RIGHT = VIRTUAL_KEY.RIGHT; pub const VK_DOWN = VIRTUAL_KEY.DOWN; pub const VK_SELECT = VIRTUAL_KEY.SELECT; pub const VK_PRINT = VIRTUAL_KEY.PRINT; pub const VK_EXECUTE = VIRTUAL_KEY.EXECUTE; pub const VK_SNAPSHOT = VIRTUAL_KEY.SNAPSHOT; pub const VK_INSERT = VIRTUAL_KEY.INSERT; pub const VK_DELETE = VIRTUAL_KEY.DELETE; pub const VK_HELP = VIRTUAL_KEY.HELP; pub const VK_LWIN = VIRTUAL_KEY.LWIN; pub const VK_RWIN = VIRTUAL_KEY.RWIN; pub const VK_APPS = VIRTUAL_KEY.APPS; pub const VK_SLEEP = VIRTUAL_KEY.SLEEP; pub const VK_NUMPAD0 = VIRTUAL_KEY.NUMPAD0; pub const VK_NUMPAD1 = VIRTUAL_KEY.NUMPAD1; pub const VK_NUMPAD2 = VIRTUAL_KEY.NUMPAD2; pub const VK_NUMPAD3 = VIRTUAL_KEY.NUMPAD3; pub const VK_NUMPAD4 = VIRTUAL_KEY.NUMPAD4; pub const VK_NUMPAD5 = VIRTUAL_KEY.NUMPAD5; pub const VK_NUMPAD6 = VIRTUAL_KEY.NUMPAD6; pub const VK_NUMPAD7 = VIRTUAL_KEY.NUMPAD7; pub const VK_NUMPAD8 = VIRTUAL_KEY.NUMPAD8; pub const VK_NUMPAD9 = VIRTUAL_KEY.NUMPAD9; pub const VK_MULTIPLY = VIRTUAL_KEY.MULTIPLY; pub const VK_ADD = VIRTUAL_KEY.ADD; pub const VK_SEPARATOR = VIRTUAL_KEY.SEPARATOR; pub const VK_SUBTRACT = VIRTUAL_KEY.SUBTRACT; pub const VK_DECIMAL = VIRTUAL_KEY.DECIMAL; pub const VK_DIVIDE = VIRTUAL_KEY.DIVIDE; pub const VK_F1 = VIRTUAL_KEY.F1; pub const VK_F2 = VIRTUAL_KEY.F2; pub const VK_F3 = VIRTUAL_KEY.F3; pub const VK_F4 = VIRTUAL_KEY.F4; pub const VK_F5 = VIRTUAL_KEY.F5; pub const VK_F6 = VIRTUAL_KEY.F6; pub const VK_F7 = VIRTUAL_KEY.F7; pub const VK_F8 = VIRTUAL_KEY.F8; pub const VK_F9 = VIRTUAL_KEY.F9; pub const VK_F10 = VIRTUAL_KEY.F10; pub const VK_F11 = VIRTUAL_KEY.F11; pub const VK_F12 = VIRTUAL_KEY.F12; pub const VK_F13 = VIRTUAL_KEY.F13; pub const VK_F14 = VIRTUAL_KEY.F14; pub const VK_F15 = VIRTUAL_KEY.F15; pub const VK_F16 = VIRTUAL_KEY.F16; pub const VK_F17 = VIRTUAL_KEY.F17; pub const VK_F18 = VIRTUAL_KEY.F18; pub const VK_F19 = VIRTUAL_KEY.F19; pub const VK_F20 = VIRTUAL_KEY.F20; pub const VK_F21 = VIRTUAL_KEY.F21; pub const VK_F22 = VIRTUAL_KEY.F22; pub const VK_F23 = VIRTUAL_KEY.F23; pub const VK_F24 = VIRTUAL_KEY.F24; pub const VK_NAVIGATION_VIEW = VIRTUAL_KEY.NAVIGATION_VIEW; pub const VK_NAVIGATION_MENU = VIRTUAL_KEY.NAVIGATION_MENU; pub const VK_NAVIGATION_UP = VIRTUAL_KEY.NAVIGATION_UP; pub const VK_NAVIGATION_DOWN = VIRTUAL_KEY.NAVIGATION_DOWN; pub const VK_NAVIGATION_LEFT = VIRTUAL_KEY.NAVIGATION_LEFT; pub const VK_NAVIGATION_RIGHT = VIRTUAL_KEY.NAVIGATION_RIGHT; pub const VK_NAVIGATION_ACCEPT = VIRTUAL_KEY.NAVIGATION_ACCEPT; pub const VK_NAVIGATION_CANCEL = VIRTUAL_KEY.NAVIGATION_CANCEL; pub const VK_NUMLOCK = VIRTUAL_KEY.NUMLOCK; pub const VK_SCROLL = VIRTUAL_KEY.SCROLL; pub const VK_OEM_NEC_EQUAL = VIRTUAL_KEY.OEM_NEC_EQUAL; pub const VK_OEM_FJ_JISHO = VIRTUAL_KEY.OEM_NEC_EQUAL; pub const VK_OEM_FJ_MASSHOU = VIRTUAL_KEY.OEM_FJ_MASSHOU; pub const VK_OEM_FJ_TOUROKU = VIRTUAL_KEY.OEM_FJ_TOUROKU; pub const VK_OEM_FJ_LOYA = VIRTUAL_KEY.OEM_FJ_LOYA; pub const VK_OEM_FJ_ROYA = VIRTUAL_KEY.OEM_FJ_ROYA; pub const VK_LSHIFT = VIRTUAL_KEY.LSHIFT; pub const VK_RSHIFT = VIRTUAL_KEY.RSHIFT; pub const VK_LCONTROL = VIRTUAL_KEY.LCONTROL; pub const VK_RCONTROL = VIRTUAL_KEY.RCONTROL; pub const VK_LMENU = VIRTUAL_KEY.LMENU; pub const VK_RMENU = VIRTUAL_KEY.RMENU; pub const VK_BROWSER_BACK = VIRTUAL_KEY.BROWSER_BACK; pub const VK_BROWSER_FORWARD = VIRTUAL_KEY.BROWSER_FORWARD; pub const VK_BROWSER_REFRESH = VIRTUAL_KEY.BROWSER_REFRESH; pub const VK_BROWSER_STOP = VIRTUAL_KEY.BROWSER_STOP; pub const VK_BROWSER_SEARCH = VIRTUAL_KEY.BROWSER_SEARCH; pub const VK_BROWSER_FAVORITES = VIRTUAL_KEY.BROWSER_FAVORITES; pub const VK_BROWSER_HOME = VIRTUAL_KEY.BROWSER_HOME; pub const VK_VOLUME_MUTE = VIRTUAL_KEY.VOLUME_MUTE; pub const VK_VOLUME_DOWN = VIRTUAL_KEY.VOLUME_DOWN; pub const VK_VOLUME_UP = VIRTUAL_KEY.VOLUME_UP; pub const VK_MEDIA_NEXT_TRACK = VIRTUAL_KEY.MEDIA_NEXT_TRACK; pub const VK_MEDIA_PREV_TRACK = VIRTUAL_KEY.MEDIA_PREV_TRACK; pub const VK_MEDIA_STOP = VIRTUAL_KEY.MEDIA_STOP; pub const VK_MEDIA_PLAY_PAUSE = VIRTUAL_KEY.MEDIA_PLAY_PAUSE; pub const VK_LAUNCH_MAIL = VIRTUAL_KEY.LAUNCH_MAIL; pub const VK_LAUNCH_MEDIA_SELECT = VIRTUAL_KEY.LAUNCH_MEDIA_SELECT; pub const VK_LAUNCH_APP1 = VIRTUAL_KEY.LAUNCH_APP1; pub const VK_LAUNCH_APP2 = VIRTUAL_KEY.LAUNCH_APP2; pub const VK_OEM_1 = VIRTUAL_KEY.OEM_1; pub const VK_OEM_PLUS = VIRTUAL_KEY.OEM_PLUS; pub const VK_OEM_COMMA = VIRTUAL_KEY.OEM_COMMA; pub const VK_OEM_MINUS = VIRTUAL_KEY.OEM_MINUS; pub const VK_OEM_PERIOD = VIRTUAL_KEY.OEM_PERIOD; pub const VK_OEM_2 = VIRTUAL_KEY.OEM_2; pub const VK_OEM_3 = VIRTUAL_KEY.OEM_3; pub const VK_GAMEPAD_A = VIRTUAL_KEY.GAMEPAD_A; pub const VK_GAMEPAD_B = VIRTUAL_KEY.GAMEPAD_B; pub const VK_GAMEPAD_X = VIRTUAL_KEY.GAMEPAD_X; pub const VK_GAMEPAD_Y = VIRTUAL_KEY.GAMEPAD_Y; pub const VK_GAMEPAD_RIGHT_SHOULDER = VIRTUAL_KEY.GAMEPAD_RIGHT_SHOULDER; pub const VK_GAMEPAD_LEFT_SHOULDER = VIRTUAL_KEY.GAMEPAD_LEFT_SHOULDER; pub const VK_GAMEPAD_LEFT_TRIGGER = VIRTUAL_KEY.GAMEPAD_LEFT_TRIGGER; pub const VK_GAMEPAD_RIGHT_TRIGGER = VIRTUAL_KEY.GAMEPAD_RIGHT_TRIGGER; pub const VK_GAMEPAD_DPAD_UP = VIRTUAL_KEY.GAMEPAD_DPAD_UP; pub const VK_GAMEPAD_DPAD_DOWN = VIRTUAL_KEY.GAMEPAD_DPAD_DOWN; pub const VK_GAMEPAD_DPAD_LEFT = VIRTUAL_KEY.GAMEPAD_DPAD_LEFT; pub const VK_GAMEPAD_DPAD_RIGHT = VIRTUAL_KEY.GAMEPAD_DPAD_RIGHT; pub const VK_GAMEPAD_MENU = VIRTUAL_KEY.GAMEPAD_MENU; pub const VK_GAMEPAD_VIEW = VIRTUAL_KEY.GAMEPAD_VIEW; pub const VK_GAMEPAD_LEFT_THUMBSTICK_BUTTON = VIRTUAL_KEY.GAMEPAD_LEFT_THUMBSTICK_BUTTON; pub const VK_GAMEPAD_RIGHT_THUMBSTICK_BUTTON = VIRTUAL_KEY.GAMEPAD_RIGHT_THUMBSTICK_BUTTON; pub const VK_GAMEPAD_LEFT_THUMBSTICK_UP = VIRTUAL_KEY.GAMEPAD_LEFT_THUMBSTICK_UP; pub const VK_GAMEPAD_LEFT_THUMBSTICK_DOWN = VIRTUAL_KEY.GAMEPAD_LEFT_THUMBSTICK_DOWN; pub const VK_GAMEPAD_LEFT_THUMBSTICK_RIGHT = VIRTUAL_KEY.GAMEPAD_LEFT_THUMBSTICK_RIGHT; pub const VK_GAMEPAD_LEFT_THUMBSTICK_LEFT = VIRTUAL_KEY.GAMEPAD_LEFT_THUMBSTICK_LEFT; pub const VK_GAMEPAD_RIGHT_THUMBSTICK_UP = VIRTUAL_KEY.GAMEPAD_RIGHT_THUMBSTICK_UP; pub const VK_GAMEPAD_RIGHT_THUMBSTICK_DOWN = VIRTUAL_KEY.GAMEPAD_RIGHT_THUMBSTICK_DOWN; pub const VK_GAMEPAD_RIGHT_THUMBSTICK_RIGHT = VIRTUAL_KEY.GAMEPAD_RIGHT_THUMBSTICK_RIGHT; pub const VK_GAMEPAD_RIGHT_THUMBSTICK_LEFT = VIRTUAL_KEY.GAMEPAD_RIGHT_THUMBSTICK_LEFT; pub const VK_OEM_4 = VIRTUAL_KEY.OEM_4; pub const VK_OEM_5 = VIRTUAL_KEY.OEM_5; pub const VK_OEM_6 = VIRTUAL_KEY.OEM_6; pub const VK_OEM_7 = VIRTUAL_KEY.OEM_7; pub const VK_OEM_8 = VIRTUAL_KEY.OEM_8; pub const VK_OEM_AX = VIRTUAL_KEY.OEM_AX; pub const VK_OEM_102 = VIRTUAL_KEY.OEM_102; pub const VK_ICO_HELP = VIRTUAL_KEY.ICO_HELP; pub const VK_ICO_00 = VIRTUAL_KEY.ICO_00; pub const VK_PROCESSKEY = VIRTUAL_KEY.PROCESSKEY; pub const VK_ICO_CLEAR = VIRTUAL_KEY.ICO_CLEAR; pub const VK_PACKET = VIRTUAL_KEY.PACKET; pub const VK_OEM_RESET = VIRTUAL_KEY.OEM_RESET; pub const VK_OEM_JUMP = VIRTUAL_KEY.OEM_JUMP; pub const VK_OEM_PA1 = VIRTUAL_KEY.OEM_PA1; pub const VK_OEM_PA2 = VIRTUAL_KEY.OEM_PA2; pub const VK_OEM_PA3 = VIRTUAL_KEY.OEM_PA3; pub const VK_OEM_WSCTRL = VIRTUAL_KEY.OEM_WSCTRL; pub const VK_OEM_CUSEL = VIRTUAL_KEY.OEM_CUSEL; pub const VK_OEM_ATTN = VIRTUAL_KEY.OEM_ATTN; pub const VK_OEM_FINISH = VIRTUAL_KEY.OEM_FINISH; pub const VK_OEM_COPY = VIRTUAL_KEY.OEM_COPY; pub const VK_OEM_AUTO = VIRTUAL_KEY.OEM_AUTO; pub const VK_OEM_ENLW = VIRTUAL_KEY.OEM_ENLW; pub const VK_OEM_BACKTAB = VIRTUAL_KEY.OEM_BACKTAB; pub const VK_ATTN = VIRTUAL_KEY.ATTN; pub const VK_CRSEL = VIRTUAL_KEY.CRSEL; pub const VK_EXSEL = VIRTUAL_KEY.EXSEL; pub const VK_EREOF = VIRTUAL_KEY.EREOF; pub const VK_PLAY = VIRTUAL_KEY.PLAY; pub const VK_ZOOM = VIRTUAL_KEY.ZOOM; pub const VK_NONAME = VIRTUAL_KEY.NONAME; pub const VK_PA1 = VIRTUAL_KEY.PA1; pub const VK_OEM_CLEAR = VIRTUAL_KEY.OEM_CLEAR; pub const VK_TO_BIT = extern struct { Vk: u8, ModBits: u8, }; pub const MODIFIERS = extern struct { pVkToBit: ?*VK_TO_BIT, wMaxModBits: u16, ModNumber: [1]u8, }; pub const VSC_VK = extern struct { Vsc: u8, Vk: u16, }; pub const VK_VSC = extern struct { Vk: u8, Vsc: u8, }; pub const VK_TO_WCHARS1 = extern struct { VirtualKey: u8, Attributes: u8, wch: [1]u16, }; pub const VK_TO_WCHARS2 = extern struct { VirtualKey: u8, Attributes: u8, wch: [2]u16, }; pub const VK_TO_WCHARS3 = extern struct { VirtualKey: u8, Attributes: u8, wch: [3]u16, }; pub const VK_TO_WCHARS4 = extern struct { VirtualKey: u8, Attributes: u8, wch: [4]u16, }; pub const VK_TO_WCHARS5 = extern struct { VirtualKey: u8, Attributes: u8, wch: [5]u16, }; pub const VK_TO_WCHARS6 = extern struct { VirtualKey: u8, Attributes: u8, wch: [6]u16, }; pub const VK_TO_WCHARS7 = extern struct { VirtualKey: u8, Attributes: u8, wch: [7]u16, }; pub const VK_TO_WCHARS8 = extern struct { VirtualKey: u8, Attributes: u8, wch: [8]u16, }; pub const VK_TO_WCHARS9 = extern struct { VirtualKey: u8, Attributes: u8, wch: [9]u16, }; pub const VK_TO_WCHARS10 = extern struct { VirtualKey: u8, Attributes: u8, wch: [10]u16, }; pub const VK_TO_WCHAR_TABLE = extern struct { pVkToWchars: ?*VK_TO_WCHARS1, nModifications: u8, cbSize: u8, }; pub const DEADKEY = extern struct { dwBoth: u32, wchComposed: u16, uFlags: u16, }; pub const LIGATURE1 = extern struct { VirtualKey: u8, ModificationNumber: u16, wch: [1]u16, }; pub const LIGATURE2 = extern struct { VirtualKey: u8, ModificationNumber: u16, wch: [2]u16, }; pub const LIGATURE3 = extern struct { VirtualKey: u8, ModificationNumber: u16, wch: [3]u16, }; pub const LIGATURE4 = extern struct { VirtualKey: u8, ModificationNumber: u16, wch: [4]u16, }; pub const LIGATURE5 = extern struct { VirtualKey: u8, ModificationNumber: u16, wch: [5]u16, }; pub const VSC_LPWSTR = extern struct { vsc: u8, pwsz: ?PWSTR, }; pub const tagKbdLayer = extern struct { pCharModifiers: ?*MODIFIERS, pVkToWcharTable: ?*VK_TO_WCHAR_TABLE, pDeadKey: ?*DEADKEY, pKeyNames: ?*VSC_LPWSTR, pKeyNamesExt: ?*VSC_LPWSTR, pKeyNamesDead: ?*?*u16, pusVSCtoVK: ?*u16, bMaxVSCtoVK: u8, pVSCtoVK_E0: ?*VSC_VK, pVSCtoVK_E1: ?*VSC_VK, fLocaleFlags: u32, nLgMax: u8, cbLgEntry: u8, pLigature: ?*LIGATURE1, dwType: u32, dwSubType: u32, }; pub const _VK_FUNCTION_PARAM = extern struct { NLSFEProcIndex: u8, NLSFEProcParam: u32, }; pub const _VK_TO_FUNCTION_TABLE = extern struct { Vk: u8, NLSFEProcType: u8, NLSFEProcCurrent: u8, NLSFEProcSwitch: u8, NLSFEProc: [8]_VK_FUNCTION_PARAM, NLSFEProcAlt: [8]_VK_FUNCTION_PARAM, }; pub const tagKbdNlsLayer = extern struct { OEMIdentifier: u16, LayoutInformation: u16, NumOfVkToF: u32, pVkToF: ?*_VK_TO_FUNCTION_TABLE, NumOfMouseVKey: i32, pusMouseVKey: ?*u16, }; pub const KBDTABLE_DESC = extern struct { wszDllName: [32]u16, dwType: u32, dwSubType: u32, }; pub const KBDTABLE_MULTI = extern struct { nTables: u32, aKbdTables: [8]KBDTABLE_DESC, }; pub const KBD_TYPE_INFO = extern struct { dwVersion: u32, dwType: u32, dwSubType: u32, }; pub const MOUSEMOVEPOINT = extern struct { x: i32, y: i32, time: u32, dwExtraInfo: usize, }; pub const TRACKMOUSEEVENT = extern struct { cbSize: u32, dwFlags: TRACKMOUSEEVENT_FLAGS, hwndTrack: ?HWND, dwHoverTime: u32, }; pub const MOUSEINPUT = extern struct { dx: i32, dy: i32, mouseData: u32, dwFlags: MOUSE_EVENT_FLAGS, time: u32, dwExtraInfo: usize, }; pub const KEYBDINPUT = extern struct { wVk: VIRTUAL_KEY, wScan: u16, dwFlags: KEYBD_EVENT_FLAGS, time: u32, dwExtraInfo: usize, }; pub const HARDWAREINPUT = extern struct { uMsg: u32, wParamL: u16, wParamH: u16, }; pub const INPUT = extern struct { type: INPUT_TYPE, Anonymous: extern union { mi: MOUSEINPUT, ki: KEYBDINPUT, hi: HARDWAREINPUT, }, }; pub const LASTINPUTINFO = extern struct { cbSize: u32, dwTime: u32, }; //-------------------------------------------------------------------------------- // Section: Functions (52) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "COMCTL32" fn _TrackMouseEvent( lpEventTrack: ?*TRACKMOUSEEVENT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn LoadKeyboardLayoutA( pwszKLID: ?[*:0]const u8, Flags: ACTIVATE_KEYBOARD_LAYOUT_FLAGS, ) callconv(@import("std").os.windows.WINAPI) ?HKL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn LoadKeyboardLayoutW( pwszKLID: ?[*:0]const u16, Flags: ACTIVATE_KEYBOARD_LAYOUT_FLAGS, ) callconv(@import("std").os.windows.WINAPI) ?HKL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ActivateKeyboardLayout( hkl: ?HKL, Flags: ACTIVATE_KEYBOARD_LAYOUT_FLAGS, ) callconv(@import("std").os.windows.WINAPI) ?HKL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ToUnicodeEx( wVirtKey: u32, wScanCode: u32, lpKeyState: *[256]u8, pwszBuff: [*:0]u16, cchBuff: i32, wFlags: u32, dwhkl: ?HKL, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn UnloadKeyboardLayout( hkl: ?HKL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyboardLayoutNameA( pwszKLID: *[9]u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyboardLayoutNameW( pwszKLID: *[9]u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyboardLayoutList( nBuff: i32, lpList: ?[*]?HKL, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyboardLayout( idThread: u32, ) callconv(@import("std").os.windows.WINAPI) ?HKL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetMouseMovePointsEx( cbSize: u32, lppt: ?*MOUSEMOVEPOINT, lpptBuf: [*]MOUSEMOVEPOINT, nBufPoints: i32, resolution: GET_MOUSE_MOVE_POINTS_EX_RESOLUTION, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn TrackMouseEvent( lpEventTrack: ?*TRACKMOUSEEVENT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn RegisterHotKey( hWnd: ?HWND, id: i32, fsModifiers: HOT_KEY_MODIFIERS, vk: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn UnregisterHotKey( hWnd: ?HWND, id: i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SwapMouseButton( fSwap: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetDoubleClickTime( ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SetDoubleClickTime( param0: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SetFocus( hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) ?HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetActiveWindow( ) callconv(@import("std").os.windows.WINAPI) ?HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetFocus( ) callconv(@import("std").os.windows.WINAPI) ?HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKBCodePage( ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyState( nVirtKey: i32, ) callconv(@import("std").os.windows.WINAPI) i16; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetAsyncKeyState( vKey: i32, ) callconv(@import("std").os.windows.WINAPI) i16; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyboardState( lpKeyState: *[256]u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SetKeyboardState( lpKeyState: *[256]u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyNameTextA( lParam: i32, lpString: [*:0]u8, cchSize: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyNameTextW( lParam: i32, lpString: [*:0]u16, cchSize: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetKeyboardType( nTypeFlag: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ToAscii( uVirtKey: u32, uScanCode: u32, lpKeyState: ?*[256]u8, lpChar: ?*u16, uFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ToAsciiEx( uVirtKey: u32, uScanCode: u32, lpKeyState: ?*[256]u8, lpChar: ?*u16, uFlags: u32, dwhkl: ?HKL, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ToUnicode( wVirtKey: u32, wScanCode: u32, lpKeyState: ?*[256]u8, pwszBuff: [*:0]u16, cchBuff: i32, wFlags: u32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn OemKeyScan( wOemChar: u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn VkKeyScanA( ch: CHAR, ) callconv(@import("std").os.windows.WINAPI) i16; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn VkKeyScanW( ch: u16, ) callconv(@import("std").os.windows.WINAPI) i16; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn VkKeyScanExA( ch: CHAR, dwhkl: ?HKL, ) callconv(@import("std").os.windows.WINAPI) i16; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn VkKeyScanExW( ch: u16, dwhkl: ?HKL, ) callconv(@import("std").os.windows.WINAPI) i16; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn keybd_event( bVk: u8, bScan: u8, dwFlags: KEYBD_EVENT_FLAGS, dwExtraInfo: usize, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn mouse_event( dwFlags: MOUSE_EVENT_FLAGS, dx: i32, dy: i32, dwData: u32, dwExtraInfo: usize, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SendInput( cInputs: u32, pInputs: [*]INPUT, cbSize: i32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetLastInputInfo( plii: ?*LASTINPUTINFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn MapVirtualKeyA( uCode: u32, uMapType: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn MapVirtualKeyW( uCode: u32, uMapType: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn MapVirtualKeyExA( uCode: u32, uMapType: u32, dwhkl: ?HKL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn MapVirtualKeyExW( uCode: u32, uMapType: u32, dwhkl: ?HKL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetCapture( ) callconv(@import("std").os.windows.WINAPI) ?HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SetCapture( hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) ?HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ReleaseCapture( ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn EnableWindow( hWnd: ?HWND, bEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn IsWindowEnabled( hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DragDetect( hwnd: ?HWND, pt: POINT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SetActiveWindow( hWnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) ?HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn BlockInput( fBlockIt: BOOL, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (7) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { pub const LoadKeyboardLayout = thismodule.LoadKeyboardLayoutA; pub const GetKeyboardLayoutName = thismodule.GetKeyboardLayoutNameA; pub const GetKeyNameText = thismodule.GetKeyNameTextA; pub const VkKeyScan = thismodule.VkKeyScanA; pub const VkKeyScanEx = thismodule.VkKeyScanExA; pub const MapVirtualKey = thismodule.MapVirtualKeyA; pub const MapVirtualKeyEx = thismodule.MapVirtualKeyExA; }, .wide => struct { pub const LoadKeyboardLayout = thismodule.LoadKeyboardLayoutW; pub const GetKeyboardLayoutName = thismodule.GetKeyboardLayoutNameW; pub const GetKeyNameText = thismodule.GetKeyNameTextW; pub const VkKeyScan = thismodule.VkKeyScanW; pub const VkKeyScanEx = thismodule.VkKeyScanExW; pub const MapVirtualKey = thismodule.MapVirtualKeyW; pub const MapVirtualKeyEx = thismodule.MapVirtualKeyExW; }, .unspecified => if (@import("builtin").is_test) struct { pub const LoadKeyboardLayout = *opaque{}; pub const GetKeyboardLayoutName = *opaque{}; pub const GetKeyNameText = *opaque{}; pub const VkKeyScan = *opaque{}; pub const VkKeyScanEx = *opaque{}; pub const MapVirtualKey = *opaque{}; pub const MapVirtualKeyEx = *opaque{}; } else struct { pub const LoadKeyboardLayout = @compileError("'LoadKeyboardLayout' requires that UNICODE be set to true or false in the root module"); pub const GetKeyboardLayoutName = @compileError("'GetKeyboardLayoutName' requires that UNICODE be set to true or false in the root module"); pub const GetKeyNameText = @compileError("'GetKeyNameText' requires that UNICODE be set to true or false in the root module"); pub const VkKeyScan = @compileError("'VkKeyScan' requires that UNICODE be set to true or false in the root module"); pub const VkKeyScanEx = @compileError("'VkKeyScanEx' requires that UNICODE be set to true or false in the root module"); pub const MapVirtualKey = @compileError("'MapVirtualKey' requires that UNICODE be set to true or false in the root module"); pub const MapVirtualKeyEx = @compileError("'MapVirtualKeyEx' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (7) //-------------------------------------------------------------------------------- const BOOL = @import("../../foundation.zig").BOOL; const CHAR = @import("../../foundation.zig").CHAR; const HKL = @import("../../ui/text_services.zig").HKL; const HWND = @import("../../foundation.zig").HWND; const POINT = @import("../../foundation.zig").POINT; const PSTR = @import("../../foundation.zig").PSTR; const PWSTR = @import("../../foundation.zig").PWSTR; 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; } } }
win32/ui/input/keyboard_and_mouse.zig
const std = @import("std"); const utils = @import("utils.zig"); const position_is_valid = utils.position_is_valid; pub const PieceMove = struct { score: i32, // 32 bits action: Action, pub fn move(from: Piece, x: i32, y: i32) @This() { const action = Action{ .move = .{ .from = from, .to = from.moved(x, y) } }; return .{ .score = 0, .action = action }; } pub fn capture(piece: Piece, target: Piece) @This() { const action = Action{ .capture = .{ .piece = piece, .target = target } }; return .{ .score = 0, .action = action }; } pub fn promote(piece: Piece, x: i32, y: i32) @This() { const action = Action{ .promote = .{ .old_piece = piece, .new_piece = .{ .t = .Queen, .position = Position.init(x, y), .color = piece.color, .index = piece.index } } }; return .{ .score = 0, .action = action }; } pub fn capture_and_promote(piece: Piece, target: Piece) @This() { const action = Action{ .capture_and_promote = .{ .piece = piece, .target = target } }; return .{ .score = 0, .action = action }; } }; pub const PieceType = enum(u3) { Pawn, Rook, Knight, Bishop, Queen, King }; const PieceIndex = u4; // each player has at most 16 = 2^4 pieces pub const Action = union(enum) { const Capture = struct { piece: Piece, target: Piece }; const Move = struct { from: Piece, to: Piece }; const Promote = struct { old_piece: Piece, new_piece: Piece }; const CaptureAndPromote = struct { piece: Piece, target: Piece }; // only a pawn can promote, always promote to queen capture: Capture, move: Move, promote: Promote, capture_and_promote: CaptureAndPromote, }; pub const Position = struct { x: u3, y: u3, fn init(x: i32, y: i32) Position { return .{ .x = @intCast(u3, x), .y = @intCast(u3, y) }; } }; pub const Color = enum(u1) { White, Black }; pub const Piece = struct { t: PieceType, position: Position, color: Color, index: PieceIndex, fn moved(self: Piece, x: i32, y: i32) Piece { return .{ .t = self.t, .position = Position.init(x, y), .color = self.color, .index = self.index }; } }; pub const Board = struct { white_pieces: [16]?Piece = [1]?Piece{null} ** 16, black_pieces: [16]?Piece = [1]?Piece{null} ** 16, used_white_pieces: usize = 0, used_black_pieces: usize = 0, moves_for_white_pawns: [8][8][]Position = undefined, moves_for_black_pawns: [8][8][]Position = undefined, moves_for_rooks: [8][8][4][]Position = undefined, // 4 directions, for skipping moves when encountering a piece moves_for_knights: [8][8][]Position = undefined, moves_for_bishops: [8][8][4][]Position = undefined, moves_for_queens: [8][8][8][]Position = undefined, moves_for_kings: [8][8][]Position = undefined, all_moves_buffer: [utils.MAX_MOVES]Position = undefined, cells: [8][8]?Piece = [1][8]?Piece{[1]?Piece{null} ** 8} ** 8, move_stack: [1024]PieceMove = undefined, stack_depth: usize = 0, pub fn init_empty(_: std.mem.Allocator) Board { return .{}; } pub fn create_classic_game(allocator: std.mem.Allocator) Board { var board = init_empty(allocator); var x: i32 = 0; while (x < 8) : (x += 1) { board.add_new_piece(.Pawn, .White, x, 1); board.add_new_piece(.Pawn, .Black, x, 6); } return board; } pub fn turn(self: Board) Color { return if (self.stack_depth % 2 == 0) .White else .Black; } pub fn deinit(_: *Board) void { } pub fn make_move(self: *Board, move: PieceMove) void { switch (move.action) { .move => |m| { self.remove_piece(m.from); self.place_piece(m.to); }, .promote => |m| { self.remove_piece(m.old_piece); self.place_piece(m.new_piece); }, .capture => |m| { self.remove_piece(m.target); self.remove_piece(m.piece); self.place_piece(m.piece.moved(m.target.position.x, m.target.position.y)); }, .capture_and_promote => |m| { self.remove_piece(m.target); self.remove_piece(m.piece); const promoted = Piece { .t = .Queen, .position = m.target.position, .color = m.piece.color, .index = m.piece.index }; self.place_piece(promoted); } } } pub fn unmake_move(self: *Board, move: PieceMove) void { switch (move.action) { .move => |m| { self.remove_piece(m.to); self.place_piece(m.from); }, .promote => |m| { self.remove_piece(m.new_piece); self.place_piece(m.old_piece); }, .capture => |m| { self.remove_piece(m.piece.moved(m.target.position.x, m.target.position.y)); self.place_piece(m.piece); self.place_piece(m.target); }, .capture_and_promote => |m| { const promoted = Piece { .t = .Queen, .position = m.target.position, .color = m.piece.color, .index = m.piece.index }; self.remove_piece(promoted); self.place_piece(m.piece); self.place_piece(m.target); } } } pub fn push_move(self: *Board, move: PieceMove) void { self.move_stack[self.stack_depth] = move; self.stack_depth += 1; self.make_move(move); } pub fn pop_move(self: *Board) PieceMove { self.stack_depth -= 1; const move = self.move_stack[self.stack_depth]; self.unmake_move(move); return move; } pub fn cell_is_empty(self: Board, x: i32, y: i32) bool { return self.cells[@intCast(usize, x)][@intCast(usize, y)] == null; } pub fn cell_is_enemy(self: Board, x: i32, y: i32, my_color: Color) bool { return !self.cell_is_empty(x, y) and self.cells[@intCast(usize, x)][@intCast(usize, y)].?.color != my_color; } pub fn piece_at(self: Board, x: i32, y: i32) ?Piece { return self.cells[@intCast(usize, x)][@intCast(usize, y)]; } pub fn place_piece(self: *Board, piece: Piece) void { const x = piece.position.x; const y = piece.position.y; self.cells[@intCast(usize, x)][@intCast(usize, y)] = piece; if (piece.color == .White) { self.white_pieces[@intCast(usize, piece.index)] = piece; } else { self.black_pieces[@intCast(usize, piece.index)] = piece; } } pub fn remove_piece(self: *Board, piece: Piece) void { const x = piece.position.x; const y = piece.position.y; self.cells[@intCast(usize, x)][@intCast(usize, y)] = null; if (piece.color == .White) { self.white_pieces[@intCast(usize, piece.index)] = null; } else { self.black_pieces[@intCast(usize, piece.index)] = null; } } pub fn add_new_piece(self: *Board, piece_type: PieceType, color: Color, x: i32, y: i32) void { if (color == .White) { const piece = Piece{ .t = piece_type, .position = Position.init(x, y), .color = color, .index = @intCast(u4, self.used_white_pieces) }; self.white_pieces[self.used_white_pieces] = piece; self.cells[piece.position.x][piece.position.y] = piece; self.used_white_pieces += 1; } else if (color == .Black) { const piece = Piece{ .t = piece_type, .position = Position.init(x, y), .color = color, .index = @intCast(u4, self.used_black_pieces) }; self.black_pieces[self.used_black_pieces] = piece; self.cells[piece.position.x][piece.position.y] = piece; self.used_black_pieces += 1; } } pub fn collect_all_moves(self: *Board, moves: []PieceMove) usize { var index: usize = 0; if (self.turn() == .White) { for (self.white_pieces) |piece| { if (piece) |p| { switch (p.t) { .Pawn => { index = self.collect_white_pawn_moves(p, moves, index); }, else => {}, } } } } else { for (self.black_pieces) |piece| { if (piece) |p| { switch (p.t) { .Pawn => { index = self.collect_black_pawn_moves(p, moves, index); }, else => {}, } } } } return index; } pub fn collect_white_pawn_moves(self: *Board, pawn: Piece, moves: []PieceMove, index_in: usize) usize { const x = @intCast(i32, pawn.position.x); const y = @intCast(i32, pawn.position.y); var index = index_in; if (y == 1) { if (self.cell_is_empty(x, y + 1)) { if (self.cell_is_empty(x, y + 2)) { moves[index] = PieceMove.move(pawn, x, y + 2); index += 1; } } } if (y < 6) { if (self.cell_is_empty(x, y + 1)) { moves[index] = PieceMove.move(pawn, x, y + 1); index += 1; } if (x > 0 and self.cell_is_enemy(x - 1, y + 1, .White)) { moves[index] = PieceMove.capture(pawn, self.piece_at(x - 1, y + 1).?); index += 1; } if (x < 7 and self.cell_is_enemy(x + 1, y + 1, .White)) { moves[index] = PieceMove.capture(pawn, self.piece_at(x + 1, y + 1).?); index += 1; } } else if (y == 6) { if (self.cell_is_empty(x, y + 1)) { moves[index] = PieceMove.promote(pawn, x, y + 1); index += 1; } if (x > 0 and self.cell_is_enemy(x - 1, y + 1, .White)) { moves[index] = PieceMove.capture_and_promote(pawn, self.piece_at(x - 1, y + 1).?); index += 1; } if (x < 7 and self.cell_is_enemy(x + 1, y + 1, .White)) { moves[index] = PieceMove.capture_and_promote(pawn, self.piece_at(x + 1, y + 1).?); index += 1; } } return index; } pub fn collect_black_pawn_moves(self: *Board, pawn: Piece, moves: []PieceMove, index_in: usize) usize { const x = @intCast(i32, pawn.position.x); const y = @intCast(i32, pawn.position.y); var index = index_in; if (y == 6) { if (self.cell_is_empty(x, y - 1)) { if (self.cell_is_empty(x, y - 2)) { moves[index] = PieceMove.move(pawn, x, y - 2); index += 1; } } } if (y > 1) { if (self.cell_is_empty(x, y - 1)) { moves[index] = PieceMove.move(pawn, x, y - 1); index += 1; } if (x > 0 and self.cell_is_enemy(x - 1, y - 1, .Black)) { moves[index] = PieceMove.capture(pawn, self.piece_at(x - 1, y - 1).?); index += 1; } if (x < 7 and self.cell_is_enemy(x + 1, y - 1, .Black)) { moves[index] = PieceMove.capture(pawn, self.piece_at(x + 1, y - 1).?); index += 1; } } else if (y == 1) { if (self.cell_is_empty(x, y - 1)) { moves[index] = PieceMove.promote(pawn, x, y - 1); index += 1; } if (x > 0 and self.cell_is_enemy(x - 1, y - 1, .Black)) { moves[index] = PieceMove.capture_and_promote(pawn, self.piece_at(x - 1, y - 1).?); index += 1; } if (x < 7 and self.cell_is_enemy(x + 1, y - 1, .Black)) { moves[index] = PieceMove.capture_and_promote(pawn, self.piece_at(x + 1, y - 1).?); index += 1; } } return index; } pub fn precompute_all_moves(self: *Board) void { var moves_buffer = self.precompute_pawn_moves(self.all_moves_buffer[0..]); moves_buffer = self.precompute_pawn_moves(moves_buffer); moves_buffer = self.precompute_rook_moves(moves_buffer); moves_buffer = self.precompute_king_moves(moves_buffer); std.log.debug("moves_buffer.len = {}", .{moves_buffer.len}); } fn precompute_pawn_moves(self: *Board, in_moves_buffer: []Position) []Position { var moves_buffer = in_moves_buffer; // white pawns for ([_]i32{ 1, 2, 3, 4, 5, 6 }) |y| { // pawns cannot be on y == 0, and no move is possible on y == 7 for ([_]i32{ 0, 1, 2, 3, 4, 5, 6, 7 }) |x| { var offset: usize = 0; if (y == 1) { moves_buffer[offset] = Position.init(x, 3); offset += 1; } if (x > 0) { moves_buffer[offset] = Position.init(x - 1, y + 1); offset += 1; } if (x < 7) { moves_buffer[offset] = Position.init(x + 1, y + 1); offset += 1; } moves_buffer[offset] = Position.init(x, y + 1); offset += 1; self.moves_for_white_pawns[@intCast(usize, x)][@intCast(usize, y)] = moves_buffer[0..offset]; moves_buffer = moves_buffer[offset..]; } } // black pawns for ([_]i32{ 1, 2, 3, 4, 5, 6 }) |y| { for ([_]i32{ 0, 1, 2, 3, 4, 5, 6, 7 }) |x| { var offset: usize = 0; if (y == 6) { moves_buffer[offset] = Position.init(x, 4); offset += 1; } if (x > 0) { moves_buffer[offset] = Position.init(x - 1, y - 1); offset += 1; } if (x < 7) { moves_buffer[offset] = Position.init(x + 1, y - 1); offset += 1; } moves_buffer[offset] = Position.init(x, y - 1); offset += 1; self.moves_for_black_pawns[@intCast(usize, x)][@intCast(usize, y)] = moves_buffer[0..offset]; moves_buffer = moves_buffer[offset..]; } } return moves_buffer; } fn precompute_rook_moves(self: *Board, in_moves_buffer: []Position) []Position { var moves_buffer = in_moves_buffer; for ([_]i32{ 0, 1, 2, 3, 4, 5, 6, 7 }) |y| { for ([_]i32{ 0, 1, 2, 3, 4, 5, 6, 7 }) |x| { { // go left var offset: usize = 0; var tx = x - 1; while (tx >= 0) : (tx -= 1) { moves_buffer[offset] = Position.init(tx, y); offset += 1; } self.moves_for_rooks[@intCast(usize, x)][@intCast(usize, y)][0] = moves_buffer[0..offset]; moves_buffer = moves_buffer[offset..]; } { // go up var offset: usize = 0; var ty = y + 1; while (ty <= 7) : (ty += 1) { moves_buffer[offset] = Position.init(x, ty); offset += 1; } self.moves_for_rooks[@intCast(usize, x)][@intCast(usize, y)][1] = moves_buffer[0..offset]; moves_buffer = moves_buffer[offset..]; } { // go right var offset: usize = 0; var tx = x + 1; while (tx <= 7) : (tx += 1) { moves_buffer[offset] = Position.init(tx, y); offset += 1; } self.moves_for_rooks[@intCast(usize, x)][@intCast(usize, y)][2] = moves_buffer[0..offset]; moves_buffer = moves_buffer[offset..]; } { // go down var offset: usize = 0; var ty = y - 1; while (ty >= 0) : (ty -= 1) { moves_buffer[offset] = Position.init(x, ty); offset += 1; } self.moves_for_rooks[@intCast(usize, x)][@intCast(usize, y)][3] = moves_buffer[0..offset]; moves_buffer = moves_buffer[offset..]; } } } return moves_buffer; } fn precompute_king_moves(self: *Board, in_moves_buffer: []Position) []Position { var moves_buffer = in_moves_buffer; const dx = utils.KingMoves.dx; const dy = utils.KingMoves.dy; for ([_]i32{ 0, 1, 2, 3, 4, 5, 6, 7 }) |y| { for ([_]i32{ 0, 1, 2, 3, 4, 5, 6, 7 }) |x| { var offset: usize = 0; for ([_]usize{ 0, 1, 2, 3, 4, 5, 6, 7 }) |k| { if (position_is_valid(x + dx[k], y + dy[k])) { moves_buffer[offset] = Position.init(x + dx[k], y + dy[k]); offset += 1; } } self.moves_for_kings[@intCast(usize, x)][@intCast(usize, y)] = moves_buffer[0..offset]; moves_buffer = moves_buffer[offset..]; } } return moves_buffer; } };
src/board.zig
const ImageReader = zigimg.ImageReader; const ImageSeekStream = zigimg.ImageSeekStream; const PixelFormat = zigimg.PixelFormat; const assert = std.debug.assert; const color = zigimg.color; const errors = zigimg.errors; const png = zigimg.png; const std = @import("std"); const testing = std.testing; const zigimg = @import("zigimg"); const helpers = @import("../helpers.zig"); test "Read bgai4a08 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgai4a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() == null); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Grayscale8Alpha); try helpers.expectEq(pixels.Grayscale8Alpha[0].value, 255); try helpers.expectEq(pixels.Grayscale8Alpha[0].alpha, 0); try helpers.expectEq(pixels.Grayscale8Alpha[31].value, 255); try helpers.expectEq(pixels.Grayscale8Alpha[31].alpha, 255); try helpers.expectEq(pixels.Grayscale8Alpha[15 * 32 + 15].value, 131); try helpers.expectEq(pixels.Grayscale8Alpha[15 * 32 + 15].alpha, 123); try helpers.expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].value, 0); try helpers.expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].alpha, 255); } } test "Read bgbn4a08 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgbn4a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() != null); if (pngFile.getBackgroundColorChunk()) |bkgd_chunk| { try testing.expect(bkgd_chunk.color == .Grayscale); try helpers.expectEq(bkgd_chunk.grayscale, 0); } try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Grayscale8Alpha); try helpers.expectEq(pixels.Grayscale8Alpha[0].value, 255); try helpers.expectEq(pixels.Grayscale8Alpha[0].alpha, 0); try helpers.expectEq(pixels.Grayscale8Alpha[31].value, 255); try helpers.expectEq(pixels.Grayscale8Alpha[31].alpha, 255); try helpers.expectEq(pixels.Grayscale8Alpha[15 * 32 + 15].value, 131); try helpers.expectEq(pixels.Grayscale8Alpha[15 * 32 + 15].alpha, 123); try helpers.expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].value, 0); try helpers.expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].alpha, 255); } } test "Read bgai4a16 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgai4a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() == null); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Grayscale16Alpha); try helpers.expectEq(pixels.Grayscale16Alpha[0].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[0].alpha, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31].alpha, 0); try helpers.expectEq(pixels.Grayscale16Alpha[15 * 32 + 15].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[15 * 32 + 15].alpha, 63421); try helpers.expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].alpha, 0); } } test "Read bggn4a16 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bggn4a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() != null); if (pngFile.getBackgroundColorChunk()) |bkgd_chunk| { try testing.expect(bkgd_chunk.color == .Grayscale); try helpers.expectEq(bkgd_chunk.grayscale, 43908); } try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Grayscale16Alpha); try helpers.expectEq(pixels.Grayscale16Alpha[0].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[0].alpha, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31].alpha, 0); try helpers.expectEq(pixels.Grayscale16Alpha[15 * 32 + 15].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[15 * 32 + 15].alpha, 63421); try helpers.expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].alpha, 0); } } test "Read bgan6a08 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgan6a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() == null); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Rgba32); try helpers.expectEq(pixels.Rgba32[0].R, 255); try helpers.expectEq(pixels.Rgba32[0].G, 0); try helpers.expectEq(pixels.Rgba32[0].B, 8); try helpers.expectEq(pixels.Rgba32[0].A, 0); try helpers.expectEq(pixels.Rgba32[31].R, 255); try helpers.expectEq(pixels.Rgba32[31].G, 0); try helpers.expectEq(pixels.Rgba32[31].B, 8); try helpers.expectEq(pixels.Rgba32[31].A, 255); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].R, 32); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].G, 255); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].B, 4); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].A, 123); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].R, 0); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].G, 32); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].B, 255); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].A, 255); } } test "Read bgwn6a08 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgwn6a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() != null); if (pngFile.getBackgroundColorChunk()) |bkgd_chunk| { try testing.expect(bkgd_chunk.color == .TrueColor); try helpers.expectEq(bkgd_chunk.red, 255); try helpers.expectEq(bkgd_chunk.green, 255); try helpers.expectEq(bkgd_chunk.blue, 255); } try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Rgba32); try helpers.expectEq(pixels.Rgba32[0].R, 255); try helpers.expectEq(pixels.Rgba32[0].G, 0); try helpers.expectEq(pixels.Rgba32[0].B, 8); try helpers.expectEq(pixels.Rgba32[0].A, 0); try helpers.expectEq(pixels.Rgba32[31].R, 255); try helpers.expectEq(pixels.Rgba32[31].G, 0); try helpers.expectEq(pixels.Rgba32[31].B, 8); try helpers.expectEq(pixels.Rgba32[31].A, 255); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].R, 32); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].G, 255); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].B, 4); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].A, 123); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].R, 0); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].G, 32); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].B, 255); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].A, 255); } } test "Read bgan6a16 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgan6a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() == null); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Rgba64); try helpers.expectEq(pixels.Rgba64[0].R, 65535); try helpers.expectEq(pixels.Rgba64[0].G, 65535); try helpers.expectEq(pixels.Rgba64[0].B, 0); try helpers.expectEq(pixels.Rgba64[0].A, 0); try helpers.expectEq(pixels.Rgba64[31].R, 0); try helpers.expectEq(pixels.Rgba64[31].G, 65535); try helpers.expectEq(pixels.Rgba64[31].B, 0); try helpers.expectEq(pixels.Rgba64[31].A, 0); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].R, 65535); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].G, 65535); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].B, 0); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].A, 63421); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].R, 0); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].G, 0); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].B, 65535); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].A, 0); } } test "Read bgyn6a16 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgyn6a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() != null); if (pngFile.getBackgroundColorChunk()) |bkgd_chunk| { try testing.expect(bkgd_chunk.color == .TrueColor); try helpers.expectEq(bkgd_chunk.red, 65535); try helpers.expectEq(bkgd_chunk.green, 65535); try helpers.expectEq(bkgd_chunk.blue, 0); } try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Rgba64); try helpers.expectEq(pixels.Rgba64[0].R, 65535); try helpers.expectEq(pixels.Rgba64[0].G, 65535); try helpers.expectEq(pixels.Rgba64[0].B, 0); try helpers.expectEq(pixels.Rgba64[0].A, 0); try helpers.expectEq(pixels.Rgba64[31].R, 0); try helpers.expectEq(pixels.Rgba64[31].G, 65535); try helpers.expectEq(pixels.Rgba64[31].B, 0); try helpers.expectEq(pixels.Rgba64[31].A, 0); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].R, 65535); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].G, 65535); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].B, 0); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].A, 63421); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].R, 0); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].G, 0); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].B, 65535); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].A, 0); } }
tests/formats/png_bkgd_test.zig
const print = @import("std").debug.print; pub fn main() void { // The main() function can not be async. But we know // getBeef() will not suspend with this particular // invocation. Please make this okay: var my_beef = nosuspend getBeef(0xDEAD); print("beef? {X}!\n", .{my_beef}); } fn getBeef(input: u32) u32 { if (input == 0xDEAD) { suspend {} } return 0xBEEF; } // // Going Deeper Into... // ...uNdeFiNEd beHAVi0r! // // We haven't discussed it yet, but runtime "safety" features // require some extra instructions in your compiled program. // Most of the time, you're going to want to keep these in. // // But in some programs, when data integrity is less important // than raw speed (some games, for example), you can compile // without these safety features. // // Instead of a safe panic when something goes wrong, your // program will now exhibit Undefined Behavior (UB), which simply // means that the Zig language does not (cannot) define what will // happen. The best case is that it will crash, but in the worst // case, it will continue to run with the wrong results and // corrupt your data or expose you to security risks. // // This program is a great way to explore UB. Once you get it // working, try calling the getBeef() function with the value // 0xDEAD so that it will invoke the 'suspend' keyword: // // getBeef(0xDEAD) // // Now when you run the program, it will panic and give you a // nice stack trace to help debug the problem. // // zig run exercises/090_async7.zig // thread 328 panic: async function called... // ... // // But see what happens when you turn off safety checks by using // ReleaseFast mode: // // zig run -O ReleaseFast exercises/090_async7.zig // beef? 0! // // This is the wrong result. On your computer, you may get a // different answer or it might crash! What exactly will happen // is UNDEFINED. Your computer is now like a wild animal, // reacting to bits and bytes of raw memory with the base // instincts of the CPU. It is both terrifying and exhilarating. //
exercises/090_async7.zig
const std = @import("std"); const sdl = @import("sdl"); const gk = @import("gamekit.zig"); const math = gk.math; pub const input_types = @import("input_types.zig"); pub usingnamespace input_types; const FixedList = gk.utils.FixedList; const released: u3 = 1; // true only the frame the key is released const down: u3 = 2; // true the entire time the key is down const pressed: u3 = 3; // only true if down this frame and not down the previous frame pub const MouseButton = enum(usize) { left = 1, middle = 2, right = 3, }; pub const Input = struct { keys: [@intCast(usize, @enumToInt(input_types.Keys.num_keys))]u2 = [_]u2{0} ** @intCast(usize, @enumToInt(input_types.Keys.num_keys)), dirty_keys: FixedList(i32, 10), mouse_buttons: [4]u2 = [_]u2{0} ** 4, dirty_mouse_buttons: FixedList(u2, 3), mouse_wheel_y: i32 = 0, mouse_rel_x: i32 = 0, mouse_rel_y: i32 = 0, window_scale: i32 = 0, text_edit_buffer: [32]u8 = [_]u8{0} ** 32, text_input_buffer: [32]u8 = [_]u8{0} ** 32, text_edit: ?[]u8 = null, text_input: ?[]u8 = null, pub fn init(win_scale: f32) Input { return .{ .dirty_keys = FixedList(i32, 10).init(), .dirty_mouse_buttons = FixedList(u2, 3).init(), .window_scale = @floatToInt(i32, win_scale), }; } /// clears any released keys pub fn newFrame(self: *Input) void { if (self.dirty_keys.len > 0) { var iter = self.dirty_keys.iter(); while (iter.next()) |key| { const ukey = @intCast(usize, key); // guard against double key presses if (self.keys[ukey] > 0) self.keys[ukey] -= 1; } self.dirty_keys.clear(); } if (self.dirty_mouse_buttons.len > 0) { var iter = self.dirty_mouse_buttons.iter(); while (iter.next()) |button| { // guard against double mouse presses if (self.mouse_buttons[button] > 0) self.mouse_buttons[button] -= 1; } self.dirty_mouse_buttons.clear(); } self.mouse_wheel_y = 0; self.mouse_rel_x = 0; self.mouse_rel_y = 0; self.text_edit = null; self.text_input = null; } pub fn handleEvent(self: *Input, event: *sdl.SDL_Event) void { switch (event.type) { sdl.SDL_KEYDOWN, sdl.SDL_KEYUP => self.handleKeyboardEvent(&event.key), sdl.SDL_MOUSEBUTTONDOWN, sdl.SDL_MOUSEBUTTONUP => self.handleMouseEvent(&event.button), sdl.SDL_MOUSEWHEEL => self.mouse_wheel_y = event.wheel.y, sdl.SDL_MOUSEMOTION => { self.mouse_rel_x = event.motion.xrel; self.mouse_rel_y = event.motion.yrel; }, sdl.SDL_CONTROLLERAXISMOTION => std.log.warn("SDL_CONTROLLERAXISMOTION\n", .{}), sdl.SDL_CONTROLLERBUTTONDOWN, sdl.SDL_CONTROLLERBUTTONUP => std.log.warn("SDL_CONTROLLERBUTTONUP/DOWN\n", .{}), sdl.SDL_CONTROLLERDEVICEADDED, sdl.SDL_CONTROLLERDEVICEREMOVED => std.log.warn("SDL_CONTROLLERDEVICEADDED/REMOVED\n", .{}), sdl.SDL_CONTROLLERDEVICEREMAPPED => std.log.warn("SDL_CONTROLLERDEVICEREMAPPED\n", .{}), sdl.SDL_TEXTEDITING, sdl.SDL_TEXTINPUT => { self.text_input_buffer = event.text.text; const end = std.mem.indexOfScalar(u8, &self.text_input_buffer, 0).?; self.text_input = self.text_input_buffer[0..end]; }, else => {}, } } fn handleKeyboardEvent(self: *Input, evt: *sdl.SDL_KeyboardEvent) void { const scancode = @enumToInt(evt.keysym.scancode); self.dirty_keys.append(scancode); if (evt.state == 0) { self.keys[@intCast(usize, scancode)] = released; } else { self.keys[@intCast(usize, scancode)] = pressed; } // std.debug.warn("kb: {s}: {}\n", .{ sdl.SDL_GetKeyName(evt.keysym.sym), evt }); } fn handleMouseEvent(self: *Input, evt: *sdl.SDL_MouseButtonEvent) void { self.dirty_mouse_buttons.append(@intCast(u2, evt.button)); if (evt.state == 0) { self.mouse_buttons[@intCast(usize, evt.button)] = released; } else { self.mouse_buttons[@intCast(usize, evt.button)] = pressed; } // std.debug.warn("mouse: {}\n", .{evt}); } /// only true if down this frame and not down the previous frame pub fn keyPressed(self: Input, key: input_types.Keys) bool { return self.keys[@intCast(usize, @enumToInt(key))] == pressed; } /// true the entire time the key is down pub fn keyDown(self: Input, key: input_types.Keys) bool { return self.keys[@intCast(usize, @enumToInt(key))] > released; } /// true only the frame the key is released pub fn keyUp(self: Input, key: input_types.Keys) bool { return self.keys[@intCast(usize, @enumToInt(key))] == released; } /// slice is only valid for the current frame pub fn textEdit(self: Input) ?[]const u8 { return self.text_edit orelse null; } /// slice is only valid for the current frame pub fn textInput(self: Input) ?[]const u8 { return self.text_input orelse null; } /// only true if down this frame and not down the previous frame pub fn mousePressed(self: Input, button: MouseButton) bool { return self.mouse_buttons[@enumToInt(button)] == pressed; } /// true the entire time the button is down pub fn mouseDown(self: Input, button: MouseButton) bool { return self.mouse_buttons[@enumToInt(button)] > released; } /// true only the frame the button is released pub fn mouseUp(self: Input, button: MouseButton) bool { return self.mouse_buttons[@enumToInt(button)] == released; } pub fn mouseWheel(self: Input) i32 { return self.mouse_wheel_y; } pub fn mousePos(self: Input) math.Vec2 { var xc: c_int = undefined; var yc: c_int = undefined; _ = sdl.SDL_GetMouseState(&xc, &yc); return .{ .x = @intToFloat(f32, xc * self.window_scale), .y = @intToFloat(f32, yc * self.window_scale) }; } // gets the scaled mouse position based on the currently bound render texture scale and offset // as calcuated in OffscreenPass. scale should be scale and offset_n is the calculated x, y value. pub fn mousePosScaled(self: Input) math.Vec2 { const p = self.mousePos(); const xf = p.x - @intToFloat(f32, self.res_scaler.x); const yf = p.y - @intToFloat(f32, self.res_scaler.y); return .{ .x = xf / self.res_scaler.scale, .y = yf / self.res_scaler.scale }; } pub fn mousePosScaledVec(self: Input) math.Vec2 { var x: i32 = undefined; var y: i32 = undefined; self.mousePosScaled(&x, &y); return .{ .x = @intToFloat(f32, x), .y = @intToFloat(f32, y) }; } pub fn mouseRelMotion(self: Input, x: *i32, y: *i32) void { x.* = self.mouse_rel_x; y.* = self.mouse_rel_y; } }; test "test input" { var input = Input.init(1); _ = input.keyPressed(.a); _ = input.mousePressed(.left); _ = input.mouseWheel(); var x: i32 = undefined; var y: i32 = undefined; _ = input.mousePosScaled(&x, &y); _ = input.mousePosScaledVec(); input.mouseRelMotion(&x, &y); }
gamekit/input.zig
const clap = @import("clap"); const format = @import("format"); const std = @import("std"); const ston = @import("ston"); const util = @import("util"); 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 Program = @This(); allocator: mem.Allocator, pokemons: Pokemons = Pokemons{}, pub const main = util.generateMain(Program); pub const version = "0.0.0"; pub const description = \\Replace trade evolutions with non trade versions. \\ \\Here is how each trade evolution is replaced: \\* Trade -> Level up 36 \\* Trade holding <item> -> Level up holding <item> during daytime \\* Trade with <pokemon> -> Level up with other <pokemon> in party \\ \\Certain level up methods might not exist in some game. \\Supported methods are found by looking over all methods used in the game. \\If one method doesn't exist, 'Level up 36' is used as a fallback. \\ ; pub const params = &[_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help text and exit.") catch unreachable, clap.parseParam("-v, --version Output version information and exit.") catch unreachable, }; pub fn init(allocator: mem.Allocator, args: anytype) error{}!Program { _ = args; return Program{ .allocator = allocator }; } 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); program.removeTradeEvolutions(); try program.output(stdio.out); } fn output(program: *Program, writer: anytype) !void { try ston.serialize(writer, .{ .pokemons = program.pokemons }); } fn useGame(program: *Program, parsed: format.Game) !void { const allocator = program.allocator; switch (parsed) { .pokemons => |pokemons| { const pokemon = (try program.pokemons.getOrPutValue(allocator, pokemons.index, .{})) .value_ptr; switch (pokemons.value) { .evos => |evos| { const evo = (try pokemon.evos.getOrPutValue(allocator, evos.index, .{})) .value_ptr; switch (evos.value) { .param => |param| evo.param = param, .method => |method| evo.method = method, .target => return error.DidNotConsumeData, } }, .stats, .types, .catch_rate, .base_exp_yield, .ev_yield, .items, .gender_ratio, .egg_cycles, .base_friendship, .growth_rate, .egg_groups, .abilities, .color, .moves, .tms, .hms, .name, .pokedex_entry, => return error.DidNotConsumeData, } }, .version, .game_title, .gamecode, .instant_text, .starters, .text_delays, .trainers, .moves, .abilities, .types, .tms, .hms, .items, .pokedex, .maps, .wild_pokemons, .static_pokemons, .given_pokemons, .pokeball_items, .hidden_hollows, .text, => return error.DidNotConsumeData, } } fn removeTradeEvolutions(program: *Program) void { // Find methods that exists in the game. var has_level_up = false; var has_level_up_holding = false; var has_level_up_party = false; for (program.pokemons.values()) |pokemon| { for (pokemon.evos.values()) |evo| { if (evo.method == .unused) continue; has_level_up = has_level_up or evo.method == .level_up; has_level_up_holding = has_level_up_holding or evo.method == .level_up_holding_item_during_daytime; has_level_up_party = has_level_up_party or evo.method == .level_up_with_other_pokemon_in_party; } } const M = format.Evolution.Method; const trade_method_replace: ?M = if (has_level_up) .level_up else null; const trade_method_holding_replace: ?M = if (has_level_up_holding) .level_up_holding_item_during_daytime else trade_method_replace; const trade_param_replace: ?u16 = if (has_level_up) @as(usize, 36) else null; const trade_param_holding_replace: ?u16 = if (has_level_up_holding) null else trade_param_replace; for (program.pokemons.values()) |pokemon| { for (pokemon.evos.values()) |*evo| { if (evo.method == .unused) continue; const method = evo.method; const param = evo.param; switch (evo.method) { .trade, .trade_with_pokemon => { evo.method = trade_method_replace orelse method; evo.param = trade_param_replace orelse param; }, .trade_holding_item => { evo.method = trade_method_holding_replace orelse method; evo.param = trade_param_holding_replace orelse param; }, .attack_eql_defense, .attack_gth_defense, .attack_lth_defense, .beauty, .friend_ship, .friend_ship_during_day, .friend_ship_during_night, .level_up, .level_up_female, .level_up_holding_item_during_daytime, .level_up_holding_item_during_the_night, .level_up_in_special_magnetic_field, .level_up_knowning_move, .level_up_male, .level_up_may_spawn_pokemon, .level_up_near_ice_rock, .level_up_near_moss_rock, .level_up_spawn_if_cond, .level_up_with_other_pokemon_in_party, .personality_value1, .personality_value2, .unknown_0x02, .unknown_0x03, .unused, .use_item, .use_item_on_female, .use_item_on_male, => {}, } } } } const Evolutions = std.AutoArrayHashMapUnmanaged(u8, Evolution); const Pokemons = std.AutoArrayHashMapUnmanaged(u16, Pokemon); const Pokemon = struct { evos: Evolutions = Evolutions{}, }; const Evolution = struct { param: ?u16 = null, method: format.Evolution.Method = .unused, }; test "tm35-no-trade-evolutions" { const H = struct { fn evo( comptime id: []const u8, comptime method: []const u8, comptime param: []const u8, ) []const u8 { return ".pokemons[0].evos[" ++ id ++ "].param=" ++ param ++ "\n" ++ ".pokemons[0].evos[" ++ id ++ "].method=" ++ method ++ "\n"; } }; const test_string = H.evo("0", "level_up", "12") ++ H.evo("1", "trade", "1") ++ H.evo("2", "trade_holding_item", "1") ++ H.evo("3", "trade_with_pokemon", "1"); try util.testing.testProgram( Program, &[_][]const u8{}, test_string, H.evo("0", "level_up", "12") ++ H.evo("1", "level_up", "36") ++ H.evo("2", "level_up", "36") ++ H.evo("3", "level_up", "36"), ); try util.testing.testProgram( Program, &[_][]const u8{}, test_string ++ H.evo("4", "level_up_holding_item_during_daytime", "1"), H.evo("0", "level_up", "12") ++ H.evo("1", "level_up", "36") ++ H.evo("2", "level_up_holding_item_during_daytime", "1") ++ H.evo("3", "level_up", "36") ++ H.evo("4", "level_up_holding_item_during_daytime", "1"), ); try util.testing.testProgram( Program, &[_][]const u8{}, test_string ++ H.evo("4", "level_up_with_other_pokemon_in_party", "1"), H.evo("0", "level_up", "12") ++ H.evo("1", "level_up", "36") ++ H.evo("2", "level_up", "36") ++ H.evo("3", "level_up", "36") ++ H.evo("4", "level_up_with_other_pokemon_in_party", "1"), ); }
src/other/tm35-no-trade-evolutions.zig
const utils = @import("utils"); const georgios = @import("georgios.zig"); const ErrorCode = enum(u32) { Unknown = 1, OutOfBounds = 2, NotEnoughSource = 3, NotEnoughDestination = 4, OutOfMemory = 5, ZeroSizedAlloc = 6, InvalidFree = 7, FileNotFound = 8, NotADirectory = 9, NotAFile = 10, InvalidFilesystem = 11, Unsupported = 12, Internal = 13, InvalidFileId = 14, InvalidElfFile = 15, InvalidElfObjectType = 16, InvalidElfPlatform = 17, NoCurrentProcess = 18, _, }; pub fn ValueOrError(comptime ValueType: type, comptime ErrorType: type) type { return union (enum) { const Self = @This(); value: ValueType, error_code: ErrorCode, pub fn set_value(self: *Self, value: ValueType) void { self.* = Self{.value = value}; } pub fn set_error(self: *Self, err: ErrorType) void { self.* = Self{.error_code = switch (ErrorType) { georgios.ExecError => switch (err) { georgios.ExecError.FileNotFound => ErrorCode.FileNotFound, georgios.ExecError.NotADirectory => ErrorCode.NotADirectory, georgios.ExecError.NotAFile => ErrorCode.NotAFile, georgios.ExecError.InvalidFilesystem => ErrorCode.InvalidFilesystem, georgios.ExecError.Unsupported => ErrorCode.Unsupported, georgios.ExecError.Internal => ErrorCode.Internal, georgios.ExecError.InvalidFileId => ErrorCode.InvalidFileId, georgios.ExecError.Unknown => ErrorCode.Unknown, georgios.ExecError.OutOfBounds => ErrorCode.OutOfBounds, georgios.ExecError.NotEnoughSource => ErrorCode.NotEnoughSource, georgios.ExecError.NotEnoughDestination => ErrorCode.NotEnoughDestination, georgios.ExecError.OutOfMemory => ErrorCode.OutOfMemory, georgios.ExecError.ZeroSizedAlloc => ErrorCode.ZeroSizedAlloc, georgios.ExecError.InvalidFree => ErrorCode.InvalidFree, georgios.ExecError.NoCurrentProcess => ErrorCode.NoCurrentProcess, georgios.ExecError.InvalidElfFile => ErrorCode.InvalidElfFile, georgios.ExecError.InvalidElfObjectType => ErrorCode.InvalidElfObjectType, georgios.ExecError.InvalidElfPlatform => ErrorCode.InvalidElfPlatform, }, georgios.fs.Error => switch (err) { georgios.fs.Error.FileNotFound => ErrorCode.FileNotFound, georgios.fs.Error.NotADirectory => ErrorCode.NotADirectory, georgios.fs.Error.NotAFile => ErrorCode.NotAFile, georgios.fs.Error.InvalidFilesystem => ErrorCode.InvalidFilesystem, georgios.fs.Error.Unsupported => ErrorCode.Unsupported, georgios.fs.Error.Internal => ErrorCode.Internal, georgios.fs.Error.InvalidFileId => ErrorCode.InvalidFileId, georgios.fs.Error.Unknown => ErrorCode.Unknown, georgios.fs.Error.OutOfBounds => ErrorCode.OutOfBounds, georgios.fs.Error.NotEnoughSource => ErrorCode.NotEnoughSource, georgios.fs.Error.NotEnoughDestination => ErrorCode.NotEnoughDestination, georgios.fs.Error.OutOfMemory => ErrorCode.OutOfMemory, georgios.fs.Error.ZeroSizedAlloc => ErrorCode.ZeroSizedAlloc, georgios.fs.Error.InvalidFree => ErrorCode.InvalidFree, }, georgios.io.FileError => switch (err) { georgios.io.FileError.Unsupported => ErrorCode.Unsupported, georgios.io.FileError.Internal => ErrorCode.Internal, georgios.io.FileError.InvalidFileId => ErrorCode.InvalidFileId, georgios.io.FileError.Unknown => ErrorCode.Unknown, georgios.io.FileError.OutOfBounds => ErrorCode.OutOfBounds, georgios.io.FileError.NotEnoughSource => ErrorCode.NotEnoughSource, georgios.io.FileError.NotEnoughDestination => ErrorCode.NotEnoughDestination, georgios.io.FileError.OutOfMemory => ErrorCode.OutOfMemory, georgios.io.FileError.ZeroSizedAlloc => ErrorCode.ZeroSizedAlloc, georgios.io.FileError.InvalidFree => ErrorCode.InvalidFree, }, georgios.threading.Error => switch (err) { georgios.threading.Error.NoCurrentProcess => ErrorCode.NoCurrentProcess, georgios.threading.Error.Unknown => ErrorCode.Unknown, georgios.threading.Error.OutOfBounds => ErrorCode.OutOfBounds, georgios.threading.Error.NotEnoughSource => ErrorCode.NotEnoughSource, georgios.threading.Error.NotEnoughDestination => ErrorCode.NotEnoughDestination, georgios.threading.Error.OutOfMemory => ErrorCode.OutOfMemory, georgios.threading.Error.ZeroSizedAlloc => ErrorCode.ZeroSizedAlloc, georgios.threading.Error.InvalidFree => ErrorCode.InvalidFree, }, georgios.ThreadingOrFsError => switch (err) { georgios.ThreadingOrFsError.FileNotFound => ErrorCode.FileNotFound, georgios.ThreadingOrFsError.NotADirectory => ErrorCode.NotADirectory, georgios.ThreadingOrFsError.NotAFile => ErrorCode.NotAFile, georgios.ThreadingOrFsError.InvalidFilesystem => ErrorCode.InvalidFilesystem, georgios.ThreadingOrFsError.Unsupported => ErrorCode.Unsupported, georgios.ThreadingOrFsError.Internal => ErrorCode.Internal, georgios.ThreadingOrFsError.InvalidFileId => ErrorCode.InvalidFileId, georgios.ThreadingOrFsError.Unknown => ErrorCode.Unknown, georgios.ThreadingOrFsError.OutOfBounds => ErrorCode.OutOfBounds, georgios.ThreadingOrFsError.NotEnoughSource => ErrorCode.NotEnoughSource, georgios.ThreadingOrFsError.NotEnoughDestination => ErrorCode.NotEnoughDestination, georgios.ThreadingOrFsError.OutOfMemory => ErrorCode.OutOfMemory, georgios.ThreadingOrFsError.ZeroSizedAlloc => ErrorCode.ZeroSizedAlloc, georgios.ThreadingOrFsError.InvalidFree => ErrorCode.InvalidFree, georgios.ThreadingOrFsError.NoCurrentProcess => ErrorCode.NoCurrentProcess, }, else => @compileError( "Invalid ErrorType for " ++ @typeName(Self) ++ ".set_error: " ++ @typeName(ErrorType)), }}; } pub fn get(self: *const Self) ErrorType!ValueType { return switch (self.*) { Self.value => |value| return value, Self.error_code => |error_code| switch (ErrorType) { georgios.ExecError => switch (error_code) { .FileNotFound => georgios.ExecError.FileNotFound, .NotADirectory => georgios.ExecError.NotADirectory, .NotAFile => georgios.ExecError.NotAFile, .InvalidFilesystem => georgios.ExecError.InvalidFilesystem, .Unsupported => georgios.ExecError.Unsupported, .Internal => georgios.ExecError.Internal, .InvalidFileId => georgios.ExecError.InvalidFileId, .Unknown => georgios.ExecError.Unknown, .OutOfBounds => georgios.ExecError.OutOfBounds, .NotEnoughSource => georgios.ExecError.NotEnoughSource, .NotEnoughDestination => georgios.ExecError.NotEnoughDestination, .OutOfMemory => georgios.ExecError.OutOfMemory, .ZeroSizedAlloc => georgios.ExecError.ZeroSizedAlloc, .InvalidFree => georgios.ExecError.InvalidFree, .NoCurrentProcess => georgios.ExecError.NoCurrentProcess, .InvalidElfFile => georgios.ExecError.InvalidElfFile, .InvalidElfObjectType => georgios.ExecError.InvalidElfObjectType, .InvalidElfPlatform => georgios.ExecError.InvalidElfPlatform, _ => utils.Error.Unknown, }, georgios.fs.Error => switch (error_code) { .FileNotFound => georgios.fs.Error.FileNotFound, .NotADirectory => georgios.fs.Error.NotADirectory, .NotAFile => georgios.fs.Error.NotAFile, .InvalidFilesystem => georgios.fs.Error.InvalidFilesystem, .Unsupported => georgios.fs.Error.Unsupported, .Internal => georgios.fs.Error.Internal, .InvalidFileId => georgios.fs.Error.InvalidFileId, .Unknown => georgios.fs.Error.Unknown, .OutOfBounds => georgios.fs.Error.OutOfBounds, .NotEnoughSource => georgios.fs.Error.NotEnoughSource, .NotEnoughDestination => georgios.fs.Error.NotEnoughDestination, .OutOfMemory => georgios.fs.Error.OutOfMemory, .ZeroSizedAlloc => georgios.fs.Error.ZeroSizedAlloc, .InvalidFree => georgios.fs.Error.InvalidFree, else => utils.Error.Unknown, }, georgios.io.FileError => switch (error_code) { .Unsupported => georgios.io.FileError.Unsupported, .Internal => georgios.io.FileError.Internal, .InvalidFileId => georgios.io.FileError.InvalidFileId, .Unknown => georgios.io.FileError.Unknown, .OutOfBounds => georgios.io.FileError.OutOfBounds, .NotEnoughSource => georgios.io.FileError.NotEnoughSource, .NotEnoughDestination => georgios.io.FileError.NotEnoughDestination, .OutOfMemory => georgios.io.FileError.OutOfMemory, .ZeroSizedAlloc => georgios.io.FileError.ZeroSizedAlloc, .InvalidFree => georgios.io.FileError.InvalidFree, else => utils.Error.Unknown, }, georgios.threading.Error => switch (error_code) { .NoCurrentProcess => georgios.threading.Error.NoCurrentProcess, .Unknown => georgios.threading.Error.Unknown, .OutOfBounds => georgios.threading.Error.OutOfBounds, .NotEnoughSource => georgios.threading.Error.NotEnoughSource, .NotEnoughDestination => georgios.threading.Error.NotEnoughDestination, .OutOfMemory => georgios.threading.Error.OutOfMemory, .ZeroSizedAlloc => georgios.threading.Error.ZeroSizedAlloc, .InvalidFree => georgios.threading.Error.InvalidFree, else => utils.Error.Unknown, }, georgios.ThreadingOrFsError => switch (error_code) { .FileNotFound => georgios.ThreadingOrFsError.FileNotFound, .NotADirectory => georgios.ThreadingOrFsError.NotADirectory, .NotAFile => georgios.ThreadingOrFsError.NotAFile, .InvalidFilesystem => georgios.ThreadingOrFsError.InvalidFilesystem, .Unsupported => georgios.ThreadingOrFsError.Unsupported, .Internal => georgios.ThreadingOrFsError.Internal, .InvalidFileId => georgios.ThreadingOrFsError.InvalidFileId, .Unknown => georgios.ThreadingOrFsError.Unknown, .OutOfBounds => georgios.ThreadingOrFsError.OutOfBounds, .NotEnoughSource => georgios.ThreadingOrFsError.NotEnoughSource, .NotEnoughDestination => georgios.ThreadingOrFsError.NotEnoughDestination, .OutOfMemory => georgios.ThreadingOrFsError.OutOfMemory, .ZeroSizedAlloc => georgios.ThreadingOrFsError.ZeroSizedAlloc, .InvalidFree => georgios.ThreadingOrFsError.InvalidFree, .NoCurrentProcess => georgios.ThreadingOrFsError.NoCurrentProcess, else => utils.Error.Unknown, }, else => @compileError( "Invalid ErrorType for " ++ @typeName(Self) ++ ".get: " ++ @typeName(ErrorType)), }, }; } }; } pub fn print_string(s: []const u8) callconv(.Inline) void { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 0)), [arg1] "{ebx}" (@ptrToInt(&s)), ); } pub fn yield() callconv(.Inline) void { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 2)), ); } pub fn exit(status: u8) callconv(.Inline) noreturn { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 3)), [arg1] "{ebx}" (status), ); unreachable; } pub fn exec(info: *const georgios.ProcessInfo) callconv(.Inline) georgios.ExecError!void { var rv: ValueOrError(void, georgios.ExecError) = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 4)), [arg1] "{ebx}" (info), [arg2] "{ecx}" (@ptrToInt(&rv)), ); return rv.get(); } pub fn get_key(blocking: georgios.Blocking) callconv(.Inline) ?georgios.keyboard.Event { var key: ?georgios.keyboard.Event = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 5)), [arg1] "{ebx}" (@ptrToInt(&blocking)), [arg2] "{ecx}" (@ptrToInt(&key)), ); return key; } pub fn next_dir_entry(iter: *georgios.DirEntry) callconv(.Inline) bool { var rv: bool = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 6)), [arg1] "{ebx}" (iter), [arg2] "{ecx}" (@ptrToInt(&rv)), ); return rv; } pub fn print_hex(value: u32) callconv(.Inline) void { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 7)), [arg1] "{ebx}" (value), ); } pub fn file_open(path: []const u8) callconv(.Inline) georgios.fs.Error!georgios.io.File.Id { var rv: ValueOrError(georgios.io.File.Id, georgios.fs.Error) = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 8)), [arg1] "{ebx}" (@ptrToInt(&path)), [arg2] "{ecx}" (@ptrToInt(&rv)), ); return rv.get(); } pub fn file_read(id: georgios.io.File.Id, to: []u8) callconv(.Inline) georgios.io.FileError!usize { var rv: ValueOrError(usize, georgios.io.FileError) = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 9)), [arg1] "{ebx}" (id), [arg2] "{ecx}" (@ptrToInt(&to)), [arg3] "{edx}" (@ptrToInt(&rv)), ); return rv.get(); } pub fn file_write(id: georgios.io.File.Id, from: []const u8) callconv(.Inline) georgios.io.FileError!usize { var rv: ValueOrError(usize, georgios.io.FileError) = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 10)), [arg1] "{ebx}" (id), [arg2] "{ecx}" (@ptrToInt(&from)), [arg3] "{edx}" (@ptrToInt(&rv)), ); return rv.get(); } pub fn file_seek(id: georgios.io.File.Id, offset: isize, seek_type: georgios.io.File.SeekType) callconv(.Inline) georgios.io.FileError!usize { var rv: ValueOrError(usize, georgios.io.FileError) = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 11)), [arg1] "{ebx}" (id), [arg2] "{ecx}" (offset), [arg3] "{edx}" (seek_type), [arg4] "{edi}" (@ptrToInt(&rv)), ); return rv.get(); } pub fn file_close(id: georgios.io.File.Id) callconv(.Inline) georgios.io.FileError!void { var rv: ValueOrError(void, georgios.io.FileError) = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 12)), [arg1] "{ebx}" (id), [arg2] "{ecx}" (@ptrToInt(&rv)), ); return rv.get(); } pub fn get_cwd(buffer: []u8) callconv(.Inline) georgios.threading.Error![]const u8 { var rv: ValueOrError([]const u8, georgios.threading.Error) = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 13)), [arg1] "{ebx}" (@ptrToInt(&buffer)), [arg2] "{ecx}" (@ptrToInt(&rv)), ); return rv.get(); } pub fn set_cwd(dir: []const u8) callconv(.Inline) georgios.ThreadingOrFsError!void { var rv: ValueOrError(void, georgios.ThreadingOrFsError) = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 14)), [arg1] "{ebx}" (@ptrToInt(&dir)), [arg2] "{ecx}" (@ptrToInt(&rv)), ); return rv.get(); } pub fn sleep_milliseconds(ms: u64) callconv(.Inline) void { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 15)), [arg1] "{ebx}" (@ptrToInt(&ms)), ); } pub fn sleep_seconds(s: u64) callconv(.Inline) void { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 16)), [arg1] "{ebx}" (@ptrToInt(&s)), ); } pub fn time() callconv(.Inline) u64 { var rv: u64 = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 17)), [arg1] "{ebx}" (@ptrToInt(&rv)), ); return rv; } pub fn get_process_id() callconv(.Inline) u32 { var rv: u32 = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 18)), [arg1] "{ebx}" (@ptrToInt(&rv)), ); return rv; } pub fn get_thread_id() callconv(.Inline) u32 { var rv: u32 = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 19)), [arg1] "{ebx}" (@ptrToInt(&rv)), ); return rv; } pub fn overflow_kernel_stack() callconv(.Inline) void { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 20)), ); } pub fn console_width() callconv(.Inline) u32 { var rv: u32 = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 21)), [arg1] "{ebx}" (@ptrToInt(&rv)), ); return rv; } pub fn console_height() callconv(.Inline) u32 { var rv: u32 = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 22)), [arg1] "{ebx}" (@ptrToInt(&rv)), ); return rv; } pub fn vbe_res() callconv(.Inline) ?utils.Point { var rv: ?utils.Point = undefined; asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 23)), [arg1] "{ebx}" (@ptrToInt(&rv)), ); return rv; } pub fn vbe_draw_raw_image_chunk(data: []const u8, w: u32, pos: utils.Point, last: utils.Point) callconv(.Inline) void { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 24)), [arg1] "{ebx}" (@ptrToInt(&data)), [arg2] "{ecx}" (w), [arg3] "{edx}" (@ptrToInt(&pos)), [arg4] "{edi}" (@ptrToInt(&last)), ); } pub fn vbe_flush_buffer() callconv(.Inline) void { asm volatile ("int $100" :: [syscall_number] "{eax}" (@as(u32, 25)), ); }
libs/georgios/system_calls.zig
const std = @import("std.zig"); const assert = std.debug.assert; const testing = std.testing; const Order = std.math.Order; pub fn Treap(comptime Key: type, comptime compareFn: anytype) type { return struct { const Self = @This(); // Allow for compareFn to be fn(anytype, anytype) anytype // which allows the convenient use of std.math.order. fn compare(a: Key, b: Key) Order { return compareFn(a, b); } root: ?*Node = null, prng: Prng = .{}, /// A customized pseudo random number generator for the treap. /// This just helps reducing the memory size of the treap itself /// as std.rand.DefaultPrng requires larger state (while producing better entropy for randomness to be fair). const Prng = struct { xorshift: usize = 0, fn random(self: *Prng, seed: usize) usize { // Lazily seed the prng state if (self.xorshift == 0) { self.xorshift = seed; } // Since we're using usize, decide the shifts by the integer's bit width. const shifts = switch (@bitSizeOf(usize)) { 64 => .{ 13, 7, 17 }, 32 => .{ 13, 17, 5 }, 16 => .{ 7, 9, 8 }, else => @compileError("platform not supported"), }; self.xorshift ^= self.xorshift >> shifts[0]; self.xorshift ^= self.xorshift << shifts[1]; self.xorshift ^= self.xorshift >> shifts[2]; assert(self.xorshift != 0); return self.xorshift; } }; /// A Node represents an item or point in the treap with a uniquely associated key. pub const Node = struct { key: Key, priority: usize, parent: ?*Node, children: [2]?*Node, }; /// Returns the smallest Node by key in the treap if there is one. /// Use `getEntryForExisting()` to replace/remove this Node from the treap. pub fn getMin(self: Self) ?*Node { var node = self.root; while (node) |current| { node = current.children[0] orelse break; } return node; } /// Returns the largest Node by key in the treap if there is one. /// Use `getEntryForExisting()` to replace/remove this Node from the treap. pub fn getMax(self: Self) ?*Node { var node = self.root; while (node) |current| { node = current.children[1] orelse break; } return node; } /// Lookup the Entry for the given key in the treap. /// The Entry act's as a slot in the treap to insert/replace/remove the node associated with the key. pub fn getEntryFor(self: *Self, key: Key) Entry { var parent: ?*Node = undefined; const node = self.find(key, &parent); return Entry{ .key = key, .treap = self, .node = node, .context = .{ .inserted_under = parent }, }; } /// Get an entry for a Node that currently exists in the treap. /// It is undefined behavior if the Node is not currently inserted in the treap. /// The Entry act's as a slot in the treap to insert/replace/remove the node associated with the key. pub fn getEntryForExisting(self: *Self, node: *Node) Entry { assert(node.priority != 0); return Entry{ .key = node.key, .treap = self, .node = node, .context = .{ .inserted_under = node.parent }, }; } /// An Entry represents a slot in the treap associated with a given key. pub const Entry = struct { /// The associated key for this entry. key: Key, /// A reference to the treap this entry is apart of. treap: *Self, /// The current node at this entry. node: ?*Node, /// The current state of the entry. context: union(enum) { /// A find() was called for this entry and the position in the treap is known. inserted_under: ?*Node, /// The entry's node was removed from the treap and a lookup must occur again for modification. removed, }, /// Update's the Node at this Entry in the treap with the new node. pub fn set(self: *Entry, new_node: ?*Node) void { // Update the entry's node reference after updating the treap below. defer self.node = new_node; if (self.node) |old| { if (new_node) |new| { self.treap.replace(old, new); return; } self.treap.remove(old); self.context = .removed; return; } if (new_node) |new| { // A previous treap.remove() could have rebalanced the nodes // so when inserting after a removal, we have to re-lookup the parent again. // This lookup shouldn't find a node because we're yet to insert it.. var parent: ?*Node = undefined; switch (self.context) { .inserted_under => |p| parent = p, .removed => assert(self.treap.find(self.key, &parent) == null), } self.treap.insert(self.key, parent, new); self.context = .{ .inserted_under = parent }; } } }; fn find(self: Self, key: Key, parent_ref: *?*Node) ?*Node { var node = self.root; parent_ref.* = null; // basic binary search while tracking the parent. while (node) |current| { const order = compare(key, current.key); if (order == .eq) break; parent_ref.* = current; node = current.children[@boolToInt(order == .gt)]; } return node; } fn insert(self: *Self, key: Key, parent: ?*Node, node: *Node) void { // generate a random priority & prepare the node to be inserted into the tree node.key = key; node.priority = self.prng.random(@ptrToInt(node)); node.parent = parent; node.children = [_]?*Node{ null, null }; // point the parent at the new node const link = if (parent) |p| &p.children[@boolToInt(compare(key, p.key) == .gt)] else &self.root; assert(link.* == null); link.* = node; // rotate the node up into the tree to balance it according to its priority while (node.parent) |p| { if (p.priority <= node.priority) break; const is_right = p.children[1] == node; assert(p.children[@boolToInt(is_right)] == node); const rotate_right = !is_right; self.rotate(p, rotate_right); } } fn replace(self: *Self, old: *Node, new: *Node) void { // copy over the values from the old node new.key = old.key; new.priority = old.priority; new.parent = old.parent; new.children = old.children; // point the parent at the new node const link = if (old.parent) |p| &p.children[@boolToInt(p.children[1] == old)] else &self.root; assert(link.* == old); link.* = new; // point the children's parent at the new node for (old.children) |child_node| { const child = child_node orelse continue; assert(child.parent == old); child.parent = new; } } fn remove(self: *Self, node: *Node) void { // rotate the node down to be a leaf of the tree for removal, respecting priorities. while (node.children[0] orelse node.children[1]) |_| { self.rotate(node, rotate_right: { const right = node.children[1] orelse break :rotate_right true; const left = node.children[0] orelse break :rotate_right false; break :rotate_right (left.priority < right.priority); }); } // node is a now a leaf; remove by nulling out the parent's reference to it. const link = if (node.parent) |p| &p.children[@boolToInt(p.children[1] == node)] else &self.root; assert(link.* == node); link.* = null; // clean up after ourselves node.key = undefined; node.priority = 0; node.parent = null; node.children = [_]?*Node{ null, null }; } fn rotate(self: *Self, node: *Node, right: bool) void { // if right, converts the following: // parent -> (node (target YY adjacent) XX) // parent -> (target YY (node adjacent XX)) // // if left (!right), converts the following: // parent -> (node (target YY adjacent) XX) // parent -> (target YY (node adjacent XX)) const parent = node.parent; const target = node.children[@boolToInt(!right)] orelse unreachable; const adjacent = target.children[@boolToInt(right)]; // rotate the children target.children[@boolToInt(right)] = node; node.children[@boolToInt(!right)] = adjacent; // rotate the parents node.parent = target; target.parent = parent; if (adjacent) |adj| adj.parent = node; // fix the parent link const link = if (parent) |p| &p.children[@boolToInt(p.children[1] == node)] else &self.root; assert(link.* == node); link.* = target; } }; } // For iterating a slice in a random order // https://lemire.me/blog/2017/09/18/visiting-all-values-in-an-array-exactly-once-in-random-order/ fn SliceIterRandomOrder(comptime T: type) type { return struct { rng: std.rand.Random, slice: []T, index: usize = undefined, offset: usize = undefined, co_prime: usize, const Self = @This(); pub fn init(slice: []T, rng: std.rand.Random) Self { return Self{ .rng = rng, .slice = slice, .co_prime = blk: { if (slice.len == 0) break :blk 0; var prime = slice.len / 2; while (prime < slice.len) : (prime += 1) { var gcd = [_]usize{ prime, slice.len }; while (gcd[1] != 0) { const temp = gcd; gcd = [_]usize{ temp[1], temp[0] % temp[1] }; } if (gcd[0] == 1) break; } break :blk prime; }, }; } pub fn reset(self: *Self) void { self.index = 0; self.offset = self.rng.int(usize); } pub fn next(self: *Self) ?*T { if (self.index >= self.slice.len) return null; defer self.index += 1; return &self.slice[((self.index *% self.co_prime) +% self.offset) % self.slice.len]; } }; } const TestTreap = Treap(u64, std.math.order); const TestNode = TestTreap.Node; test "std.Treap: insert, find, replace, remove" { var treap = TestTreap{}; var nodes: [10]TestNode = undefined; var prng = std.rand.DefaultPrng.init(0xdeadbeef); var iter = SliceIterRandomOrder(TestNode).init(&nodes, prng.random()); // insert check iter.reset(); while (iter.next()) |node| { const key = prng.random().int(u64); // make sure the current entry is empty. var entry = treap.getEntryFor(key); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, null); // insert the entry and make sure the fields are correct. entry.set(node); try testing.expectEqual(node.key, key); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, node); } // find check iter.reset(); while (iter.next()) |node| { const key = node.key; // find the entry by-key and by-node after having been inserted. var entry = treap.getEntryFor(node.key); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, node); try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node); } // replace check iter.reset(); while (iter.next()) |node| { const key = node.key; // find the entry by node since we already know it exists var entry = treap.getEntryForExisting(node); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, node); var stub_node: TestNode = undefined; // replace the node with a stub_node and ensure future finds point to the stub_node. entry.set(&stub_node); try testing.expectEqual(entry.node, &stub_node); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); try testing.expectEqual(entry.node, treap.getEntryForExisting(&stub_node).node); // replace the stub_node back to the node and ensure future finds point to the old node. entry.set(node); try testing.expectEqual(entry.node, node); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node); } // remove check iter.reset(); while (iter.next()) |node| { const key = node.key; // find the entry by node since we already know it exists var entry = treap.getEntryForExisting(node); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, node); // remove the node at the entry and ensure future finds point to it being removed. entry.set(null); try testing.expectEqual(entry.node, null); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); // insert the node back and ensure future finds point to the inserted node entry.set(node); try testing.expectEqual(entry.node, node); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node); // remove the node again and make sure it was cleared after the insert entry.set(null); try testing.expectEqual(entry.node, null); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); } }
lib/std/treap.zig
const std = @import("std"); const Endian = std.builtin.Endian; const assert = std.debug.assert; const link = @import("../../link.zig"); const Module = @import("../../Module.zig"); const ErrorMsg = Module.ErrorMsg; const Liveness = @import("../../Liveness.zig"); const log = std.log.scoped(.sparcv9_emit); const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput; const DW = std.dwarf; const leb128 = std.leb; const Emit = @This(); const Mir = @import("Mir.zig"); const bits = @import("bits.zig"); const Instruction = bits.Instruction; const Register = bits.Register; mir: Mir, bin_file: *link.File, debug_output: DebugInfoOutput, target: *const std.Target, err_msg: ?*ErrorMsg = null, src_loc: Module.SrcLoc, code: *std.ArrayList(u8), prev_di_line: u32, prev_di_column: u32, /// Relative to the beginning of `code`. prev_di_pc: usize, /// The branch type of every branch branch_types: std.AutoHashMapUnmanaged(Mir.Inst.Index, BranchType) = .{}, /// For every forward branch, maps the target instruction to a list of /// branches which branch to this target instruction branch_forward_origins: std.AutoHashMapUnmanaged(Mir.Inst.Index, std.ArrayListUnmanaged(Mir.Inst.Index)) = .{}, /// For backward branches: stores the code offset of the target /// instruction /// /// For forward branches: stores the code offset of the branch /// instruction code_offset_mapping: std.AutoHashMapUnmanaged(Mir.Inst.Index, usize) = .{}, const InnerError = error{ OutOfMemory, EmitFail, }; const BranchType = enum { bpcc, bpr, fn default(tag: Mir.Inst.Tag) BranchType { return switch (tag) { .bpcc => .bpcc, .bpr => .bpr, else => unreachable, }; } }; pub fn emitMir( emit: *Emit, ) InnerError!void { const mir_tags = emit.mir.instructions.items(.tag); // Convert absolute addresses into offsets and // find smallest lowerings for branch instructions try emit.lowerBranches(); // Emit machine code for (mir_tags) |tag, index| { const inst = @intCast(u32, index); switch (tag) { .dbg_line => try emit.mirDbgLine(inst), .dbg_prologue_end => try emit.mirDebugPrologueEnd(), .dbg_epilogue_begin => try emit.mirDebugEpilogueBegin(), .add => try emit.mirArithmetic3Op(inst), .bpr => try emit.mirConditionalBranch(inst), .bpcc => try emit.mirConditionalBranch(inst), .call => @panic("TODO implement sparc64 call"), .jmpl => try emit.mirArithmetic3Op(inst), .ldub => try emit.mirArithmetic3Op(inst), .lduh => try emit.mirArithmetic3Op(inst), .lduw => try emit.mirArithmetic3Op(inst), .ldx => try emit.mirArithmetic3Op(inst), .@"or" => try emit.mirArithmetic3Op(inst), .mulx => try emit.mirArithmetic3Op(inst), .nop => try emit.mirNop(), .@"return" => try emit.mirArithmetic2Op(inst), .save => try emit.mirArithmetic3Op(inst), .restore => try emit.mirArithmetic3Op(inst), .sethi => try emit.mirSethi(inst), .sll => @panic("TODO implement sparc64 sll"), .srl => @panic("TODO implement sparc64 srl"), .sra => @panic("TODO implement sparc64 sra"), .sllx => @panic("TODO implement sparc64 sllx"), .srlx => @panic("TODO implement sparc64 srlx"), .srax => @panic("TODO implement sparc64 srax"), .stb => try emit.mirArithmetic3Op(inst), .sth => try emit.mirArithmetic3Op(inst), .stw => try emit.mirArithmetic3Op(inst), .stx => try emit.mirArithmetic3Op(inst), .sub => try emit.mirArithmetic3Op(inst), .subcc => try emit.mirArithmetic3Op(inst), .tcc => try emit.mirTrap(inst), .cmp => try emit.mirArithmetic2Op(inst), .mov => try emit.mirArithmetic2Op(inst), } } } pub fn deinit(emit: *Emit) void { var iter = emit.branch_forward_origins.valueIterator(); while (iter.next()) |origin_list| { origin_list.deinit(emit.bin_file.allocator); } emit.branch_types.deinit(emit.bin_file.allocator); emit.branch_forward_origins.deinit(emit.bin_file.allocator); emit.code_offset_mapping.deinit(emit.bin_file.allocator); emit.* = undefined; } fn mirDbgLine(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const dbg_line_column = emit.mir.instructions.items(.data)[inst].dbg_line_column; switch (tag) { .dbg_line => try emit.dbgAdvancePCAndLine(dbg_line_column.line, dbg_line_column.column), else => unreachable, } } fn mirDebugPrologueEnd(emit: *Emit) !void { switch (emit.debug_output) { .dwarf => |dbg_out| { try dbg_out.dbg_line.append(DW.LNS.set_prologue_end); try emit.dbgAdvancePCAndLine(emit.prev_di_line, emit.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirDebugEpilogueBegin(emit: *Emit) !void { switch (emit.debug_output) { .dwarf => |dbg_out| { try dbg_out.dbg_line.append(DW.LNS.set_epilogue_begin); try emit.dbgAdvancePCAndLine(emit.prev_di_line, emit.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirArithmetic2Op(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const data = emit.mir.instructions.items(.data)[inst].arithmetic_2op; const rs1 = data.rs1; if (data.is_imm) { const imm = data.rs2_or_imm.imm; switch (tag) { .@"return" => try emit.writeInstruction(Instruction.@"return"(i13, rs1, imm)), .cmp => try emit.writeInstruction(Instruction.subcc(i13, rs1, imm, .g0)), .mov => try emit.writeInstruction(Instruction.@"or"(i13, .g0, imm, rs1)), else => unreachable, } } else { const rs2 = data.rs2_or_imm.rs2; switch (tag) { .@"return" => try emit.writeInstruction(Instruction.@"return"(Register, rs1, rs2)), .cmp => try emit.writeInstruction(Instruction.subcc(Register, rs1, rs2, .g0)), .mov => try emit.writeInstruction(Instruction.@"or"(Register, .g0, rs2, rs1)), else => unreachable, } } } fn mirArithmetic3Op(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const data = emit.mir.instructions.items(.data)[inst].arithmetic_3op; const rd = data.rd; const rs1 = data.rs1; if (data.is_imm) { const imm = data.rs2_or_imm.imm; switch (tag) { .add => try emit.writeInstruction(Instruction.add(i13, rs1, imm, rd)), .jmpl => try emit.writeInstruction(Instruction.jmpl(i13, rs1, imm, rd)), .ldub => try emit.writeInstruction(Instruction.ldub(i13, rs1, imm, rd)), .lduh => try emit.writeInstruction(Instruction.lduh(i13, rs1, imm, rd)), .lduw => try emit.writeInstruction(Instruction.lduw(i13, rs1, imm, rd)), .ldx => try emit.writeInstruction(Instruction.ldx(i13, rs1, imm, rd)), .@"or" => try emit.writeInstruction(Instruction.@"or"(i13, rs1, imm, rd)), .mulx => try emit.writeInstruction(Instruction.mulx(i13, rs1, imm, rd)), .save => try emit.writeInstruction(Instruction.save(i13, rs1, imm, rd)), .restore => try emit.writeInstruction(Instruction.restore(i13, rs1, imm, rd)), .stb => try emit.writeInstruction(Instruction.stb(i13, rs1, imm, rd)), .sth => try emit.writeInstruction(Instruction.sth(i13, rs1, imm, rd)), .stw => try emit.writeInstruction(Instruction.stw(i13, rs1, imm, rd)), .stx => try emit.writeInstruction(Instruction.stx(i13, rs1, imm, rd)), .sub => try emit.writeInstruction(Instruction.sub(i13, rs1, imm, rd)), .subcc => try emit.writeInstruction(Instruction.subcc(i13, rs1, imm, rd)), else => unreachable, } } else { const rs2 = data.rs2_or_imm.rs2; switch (tag) { .add => try emit.writeInstruction(Instruction.add(Register, rs1, rs2, rd)), .jmpl => try emit.writeInstruction(Instruction.jmpl(Register, rs1, rs2, rd)), .ldub => try emit.writeInstruction(Instruction.ldub(Register, rs1, rs2, rd)), .lduh => try emit.writeInstruction(Instruction.lduh(Register, rs1, rs2, rd)), .lduw => try emit.writeInstruction(Instruction.lduw(Register, rs1, rs2, rd)), .ldx => try emit.writeInstruction(Instruction.ldx(Register, rs1, rs2, rd)), .@"or" => try emit.writeInstruction(Instruction.@"or"(Register, rs1, rs2, rd)), .mulx => try emit.writeInstruction(Instruction.mulx(Register, rs1, rs2, rd)), .save => try emit.writeInstruction(Instruction.save(Register, rs1, rs2, rd)), .restore => try emit.writeInstruction(Instruction.restore(Register, rs1, rs2, rd)), .stb => try emit.writeInstruction(Instruction.stb(Register, rs1, rs2, rd)), .sth => try emit.writeInstruction(Instruction.sth(Register, rs1, rs2, rd)), .stw => try emit.writeInstruction(Instruction.stw(Register, rs1, rs2, rd)), .stx => try emit.writeInstruction(Instruction.stx(Register, rs1, rs2, rd)), .sub => try emit.writeInstruction(Instruction.sub(Register, rs1, rs2, rd)), .subcc => try emit.writeInstruction(Instruction.subcc(Register, rs1, rs2, rd)), else => unreachable, } } } fn mirConditionalBranch(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const branch_type = emit.branch_types.get(inst).?; switch (branch_type) { .bpcc => switch (tag) { .bpcc => { const branch_predict_int = emit.mir.instructions.items(.data)[inst].branch_predict_int; const offset = @intCast(i64, emit.code_offset_mapping.get(branch_predict_int.inst).?) - @intCast(i64, emit.code.items.len); log.debug("mirConditionalBranch: {} offset={}", .{ inst, offset }); try emit.writeInstruction( Instruction.bpcc( branch_predict_int.cond, branch_predict_int.annul, branch_predict_int.pt, branch_predict_int.ccr, @intCast(i21, offset), ), ); }, else => unreachable, }, .bpr => switch (tag) { .bpr => { const branch_predict_reg = emit.mir.instructions.items(.data)[inst].branch_predict_reg; const offset = @intCast(i64, emit.code_offset_mapping.get(branch_predict_reg.inst).?) - @intCast(i64, emit.code.items.len); log.debug("mirConditionalBranch: {} offset={}", .{ inst, offset }); try emit.writeInstruction( Instruction.bpr( branch_predict_reg.cond, branch_predict_reg.annul, branch_predict_reg.pt, branch_predict_reg.rs1, @intCast(i18, offset), ), ); }, else => unreachable, }, } } fn mirNop(emit: *Emit) !void { try emit.writeInstruction(Instruction.nop()); } fn mirSethi(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const data = emit.mir.instructions.items(.data)[inst].sethi; const imm = data.imm; const rd = data.rd; assert(tag == .sethi); try emit.writeInstruction(Instruction.sethi(imm, rd)); } fn mirTrap(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const data = emit.mir.instructions.items(.data)[inst].trap; const cond = data.cond; const ccr = data.ccr; const rs1 = data.rs1; if (data.is_imm) { const imm = data.rs2_or_imm.imm; switch (tag) { .tcc => try emit.writeInstruction(Instruction.trap(u7, cond, ccr, rs1, imm)), else => unreachable, } } else { const rs2 = data.rs2_or_imm.rs2; switch (tag) { .tcc => try emit.writeInstruction(Instruction.trap(Register, cond, ccr, rs1, rs2)), else => unreachable, } } } // Common helper functions fn branchTarget(emit: *Emit, inst: Mir.Inst.Index) Mir.Inst.Index { const tag = emit.mir.instructions.items(.tag)[inst]; switch (tag) { .bpcc => return emit.mir.instructions.items(.data)[inst].branch_predict_int.inst, .bpr => return emit.mir.instructions.items(.data)[inst].branch_predict_reg.inst, else => unreachable, } } fn dbgAdvancePCAndLine(emit: *Emit, line: u32, column: u32) !void { const delta_line = @intCast(i32, line) - @intCast(i32, emit.prev_di_line); const delta_pc: usize = emit.code.items.len - emit.prev_di_pc; switch (emit.debug_output) { .dwarf => |dbg_out| { // TODO Look into using the DWARF special opcodes to compress this data. // It lets you emit single-byte opcodes that add different numbers to // both the PC and the line number at the same time. try dbg_out.dbg_line.ensureUnusedCapacity(11); dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_pc); leb128.writeULEB128(dbg_out.dbg_line.writer(), delta_pc) catch unreachable; if (delta_line != 0) { dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_line); leb128.writeILEB128(dbg_out.dbg_line.writer(), delta_line) catch unreachable; } dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.copy); emit.prev_di_pc = emit.code.items.len; emit.prev_di_line = line; emit.prev_di_column = column; emit.prev_di_pc = emit.code.items.len; }, else => {}, } } fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError { @setCold(true); assert(emit.err_msg == null); emit.err_msg = try ErrorMsg.create(emit.bin_file.allocator, emit.src_loc, format, args); return error.EmitFail; } fn instructionSize(emit: *Emit, inst: Mir.Inst.Index) usize { const tag = emit.mir.instructions.items(.tag)[inst]; switch (tag) { .dbg_line, .dbg_epilogue_begin, .dbg_prologue_end, => return 0, // Currently Mir instructions always map to single machine instruction. else => return 4, } } fn isBranch(tag: Mir.Inst.Tag) bool { return switch (tag) { .bpcc => true, .bpr => true, else => false, }; } fn lowerBranches(emit: *Emit) !void { const mir_tags = emit.mir.instructions.items(.tag); const allocator = emit.bin_file.allocator; // First pass: Note down all branches and their target // instructions, i.e. populate branch_types, // branch_forward_origins, and code_offset_mapping // // TODO optimization opportunity: do this in codegen while // generating MIR for (mir_tags) |tag, index| { const inst = @intCast(u32, index); if (isBranch(tag)) { const target_inst = emit.branchTarget(inst); // Remember this branch instruction try emit.branch_types.put(allocator, inst, BranchType.default(tag)); // Forward branches require some extra stuff: We only // know their offset once we arrive at the target // instruction. Therefore, we need to be able to // access the branch instruction when we visit the // target instruction in order to manipulate its type // etc. if (target_inst > inst) { // Remember the branch instruction index try emit.code_offset_mapping.put(allocator, inst, 0); if (emit.branch_forward_origins.getPtr(target_inst)) |origin_list| { try origin_list.append(allocator, inst); } else { var origin_list: std.ArrayListUnmanaged(Mir.Inst.Index) = .{}; try origin_list.append(allocator, inst); try emit.branch_forward_origins.put(allocator, target_inst, origin_list); } } // Remember the target instruction index so that we // update the real code offset in all future passes // // putNoClobber may not be used as the put operation // may clobber the entry when multiple branches branch // to the same target instruction try emit.code_offset_mapping.put(allocator, target_inst, 0); } } // Further passes: Until all branches are lowered, interate // through all instructions and calculate new offsets and // potentially new branch types var all_branches_lowered = false; while (!all_branches_lowered) { all_branches_lowered = true; var current_code_offset: usize = 0; for (mir_tags) |tag, index| { const inst = @intCast(u32, index); // If this instruction contained in the code offset // mapping (when it is a target of a branch or if it is a // forward branch), update the code offset if (emit.code_offset_mapping.getPtr(inst)) |offset| { offset.* = current_code_offset; } // If this instruction is a backward branch, calculate the // offset, which may potentially update the branch type if (isBranch(tag)) { const target_inst = emit.branchTarget(inst); if (target_inst < inst) { const target_offset = emit.code_offset_mapping.get(target_inst).?; const offset = @intCast(i64, target_offset) - @intCast(i64, current_code_offset); const branch_type = emit.branch_types.getPtr(inst).?; const optimal_branch_type = try emit.optimalBranchType(tag, offset); if (branch_type.* != optimal_branch_type) { branch_type.* = optimal_branch_type; all_branches_lowered = false; } log.debug("lowerBranches: branch {} has offset {}", .{ inst, offset }); } } // If this instruction is the target of one or more // forward branches, calculate the offset, which may // potentially update the branch type if (emit.branch_forward_origins.get(inst)) |origin_list| { for (origin_list.items) |forward_branch_inst| { const branch_tag = emit.mir.instructions.items(.tag)[forward_branch_inst]; const forward_branch_inst_offset = emit.code_offset_mapping.get(forward_branch_inst).?; const offset = @intCast(i64, current_code_offset) - @intCast(i64, forward_branch_inst_offset); const branch_type = emit.branch_types.getPtr(forward_branch_inst).?; const optimal_branch_type = try emit.optimalBranchType(branch_tag, offset); if (branch_type.* != optimal_branch_type) { branch_type.* = optimal_branch_type; all_branches_lowered = false; } log.debug("lowerBranches: branch {} has offset {}", .{ forward_branch_inst, offset }); } } // Increment code offset current_code_offset += emit.instructionSize(inst); } } } fn optimalBranchType(emit: *Emit, tag: Mir.Inst.Tag, offset: i64) !BranchType { assert(offset & 0b11 == 0); switch (tag) { // TODO use the following strategy to implement long branches: // - Negate the conditional and target of the original instruction; // - In the space immediately after the branch, load // the address of the original target, preferrably in // a PC-relative way, into %o7; and // - jmpl %o7 + %g0, %g0 .bpcc => { if (std.math.cast(i21, offset)) |_| { return BranchType.bpcc; } else { return emit.fail("TODO support BPcc branches larger than +-1 MiB", .{}); } }, .bpr => { if (std.math.cast(i18, offset)) |_| { return BranchType.bpr; } else { return emit.fail("TODO support BPr branches larger than +-128 KiB", .{}); } }, else => unreachable, } } fn writeInstruction(emit: *Emit, instruction: Instruction) !void { // SPARCv9 instructions are always arranged in BE regardless of the // endianness mode the CPU is running in (Section 3.1 of the ISA specification). // This is to ease porting in case someone wants to do a LE SPARCv9 backend. const endian = Endian.Big; std.mem.writeInt(u32, try emit.code.addManyAsArray(4), instruction.toU32(), endian); }
src/arch/sparc64/Emit.zig
const fmt = @import("std").fmt; const GBA = @import("core.zig").GBA; const OAM = @import("oam.zig").OAM; pub const BIOS = struct { pub const RamResetFlags = packed struct { clearEwRam: bool = false, clearIwram: bool = false, clearPalette: bool = false, clearVRAM: bool = false, clearOAM: bool = false, resetSIORegisters: bool = false, resetSoundRegisters: bool = false, resetOtherRegisters: bool = false, const Self = @This(); pub const All = Self{ .clearEwRam = true, .clearIwram = true, .clearPalette = true, .clearVRAM = true, .clearOAM = true, .resetSIORegisters = true, .resetSoundRegisters = true, .resetOtherRegisters = true, }; }; pub const InterruptWaitReturn = enum(u32) { ReturnImmediately, DiscardOldFlagsAndWaitNewFlags, }; // TODO: see div() function // pub const DivResult = packed struct { // division: i32, // remainder: i32, // absoluteDivision: u32 // }; pub const CpuSetArgs = packed struct { wordCount: u21, dummy: u3 = 0, fixedSourceAddress: enum(u1) { Copy, Fill, }, dataSize: enum(u1) { HalfWord, Word, }, }; pub const CpuFastSetArgs = packed struct { wordCount: u21, dummy: u3 = 0, fixedSourceAddress: enum(u1) { Copy, Fill, }, }; pub const BgAffineSource = packed struct { originalX: i32, // TODO: Use Fixed I19.8 originalY: i32, // TODO: Use Fixed I19.8, displayX: i16, displayY: i16, scaleX: i16, // TODO: Use Fixed I8.8 scaleY: i16, // TODO: Use Fixed I8.8 angle: u16, }; pub const BgAffineDestination = packed struct { pa: i16, pb: i16, pc: i16, pd: i16, startX: i32, // TODO: Use Fixed I19.8 startY: i32, // TODO: Use Fixed I19.8 }; pub const ObjAffineSource = packed struct { scaleX: i16, // TODO: Use Fixed I8.8 scaleY: i16, // TODO: Use Fixed I8.8 angle: u16, }; pub const ObjAffineDestination = packed struct { pa: i16, pb: i16, pc: i16, pd: i16, }; pub const BitUnpackArgs = packed struct { sourceLength: u16, sourceBitWidth: u8, destinationBitWidth: u8, dataOffset: u31, zeroData: bool, }; pub inline fn softReset() void { systemCall0(0x00); } pub inline fn registerRamReset(flags: RamResetFlags) void { systemCall1(0x01, @bitCast(u8, flags)); } pub inline fn half() void { systemCall0(0x02); } pub inline fn stop() void { systemCall0(0x03); } pub inline fn interruptWait(waitReturn: InterruptWaitReturn, flags: GBA.InterruptFlags) void { systemCall2(0x04, @bitCast(u32, waitReturn), @intCast(u32, @bitCast(u14, flags))); } pub inline fn vblankWait() void { systemCall0(5); } // TODO: div when Zig supports multiple return value in inline assembly https://github.com/ziglang/zig/issues/215 // pub inline fn div(numerator: i32, denominator: i32) DivResult { // return @bitCast(DivResult, systemCall2Return3(6, @bitCast(u32, numerator), @bitCast(u32, denominator))); // } // TODO: divArm (swi 7) pub inline fn sqrt(value: u32) u16 { return @truncate(u16, systemCall1Return(0x08, value)); } pub inline fn arcTan(value: i16) i16 { const paramValue = @intCast(u32, @bitCast(u16, value)); return @truncate(i16, @bitCast(i32, systemCall1Return(0x09, paramValue))); } pub inline fn arcTan2(x: i16, y: i16) i16 { const paramX = @intCast(u32, @bitCast(u16, x)); const paramY = @intCast(u32, @bitCast(u16, y)); return @truncate(i16, @bitCast(i32, systemCall2Return(0x0A, paramX, paramY))); } pub inline fn cpuSet(source: *const u32, destination: *u32, args: CpuSetArgs) void { systemCall3(0x0B, @ptrToInt(source), @ptrToInt(destination), @intCast(u32, @bitCast(u26, args))); } pub inline fn cpuFastSet(source: *const u32, destination: *u32, args: CpuFastSetArgs) void { systemCall3(0x0C, @ptrToInt(source), @ptrToInt(destination), @intCast(u32, @bitCast(u25, args))); } pub inline fn bgAffineSet(source: *const BgAffineSource, destination: *BgAffineDestination, calculationCount: u32) void { systemCall3(0x0E, @ptrToInt(source), @ptrToInt(destination), calculationCount); } pub inline fn objAffineSetContinuous(source: *const ObjAffineSource, destination: *ObjAffineDestination, calculationCount: u32) void { systemCall4(0x0F, @ptrToInt(source), @ptrToInt(destination), calculationCount, 2); } pub inline fn objAffineSetOam(source: *const ObjAffineSource, destination: *OAM.Affine, calculationCount: u32) void { systemCall4(0x0F, @ptrToInt(source), @ptrToInt(destination), calculationCount, 2); } pub inline fn bitUnpack(source: *const u32, destination: *u32, unpackArgs: *const BitUnpackArgs) void { systemCall3(0x10, @ptrToInt(source), @ptrToInt(destination), @ptrToInt(unpackArgs)); } pub inline fn LZ77UnCompReadNormalWrite8bit(source: *const u32, destination: *u32) void { systemCall2(0x11, @ptrToInt(source), @ptrToInt(destination)); } pub inline fn LZ77UnCompReadNormalWrite16bit(source: *const u32, destination: *u32) void { systemCall2(0x12, @ptrToInt(source), @ptrToInt(destination)); } pub inline fn huffUnCompReadNormal(source: *const u32, destination: *u32) void { systemCall2(0x13, @ptrToInt(source), @ptrToInt(destination)); } pub inline fn RLUnCompReadNormalWrite8bit(source: *const u32, destination: *u32) void { systemCall2(0x14, @ptrToInt(source), @ptrToInt(destination)); } pub inline fn RLUnCompReadNormalWrite16bit(source: *const u32, destination: *u32) void { systemCall2(0x15, @ptrToInt(source), @ptrToInt(destination)); } pub inline fn diff8bitUnFilterWrite8bit(source: *const u32, destination: *u32) void { systemCall2(0x16, @ptrToInt(source), @ptrToInt(destination)); } pub inline fn diff8bitUnFilterWrite16bit(source: *const u32, destination: *u32) void { systemCall2(0x17, @ptrToInt(source), @ptrToInt(destination)); } pub inline fn diff16bitUnFilter(source: *const u32, destination: *u32) void { systemCall2(0x18, @ptrToInt(source), @ptrToInt(destination)); } pub inline fn hardReset() void { systemCall0(0x26); } pub inline fn debugFlush() void { systemCall0(0xFA); } pub inline fn systemCall0(comptime call: u8) void { const assembly = comptime getSystemCallAssemblyCode(call); asm volatile (assembly); } pub inline fn systemCall1(comptime call: u8, param0: u32) void { const assembly = comptime getSystemCallAssemblyCode(call); asm volatile (assembly : : [param0] "{r0}" (param0) : "r0" ); } pub inline fn systemCall2(comptime call: u8, param0: u32, param1: u32) void { const assembly = comptime getSystemCallAssemblyCode(call); asm volatile (assembly : : [param0] "{r0}" (param0), [param1] "{r1}" (param1) : "r0", "r1" ); } pub inline fn systemCall3(comptime call: u8, param0: u32, param1: u32, param2: u32) void { const assembly = comptime getSystemCallAssemblyCode(call); asm volatile (assembly : : [param0] "{r0}" (param0), [param1] "{r1}" (param1), [param2] "{r2}" (param2) : "r0", "r1", "r2" ); } pub inline fn systemCall4(comptime call: u8, param0: u32, param1: u32, param2: u32, param3: u32) void { const assembly = comptime getSystemCallAssemblyCode(call); asm volatile (assembly : : [param0] "{r0}" (param0), [param1] "{r1}" (param1), [param2] "{r2}" (param2), [param3] "{r3}" (param3) : "r0", "r1", "r2", "r3" ); } pub inline fn systemCall1Return(comptime call: u8, param0: u32) u32 { const assembly = comptime getSystemCallAssemblyCode(call); return asm volatile (assembly : [ret] "={r0}" (-> u32) : [param0] "{r0}" (param0) : "r0" ); } pub inline fn systemCall2Return(comptime call: u8, param0: u32, param1: u32) u32 { const assembly = comptime getSystemCallAssemblyCode(call); return asm volatile (assembly : [ret] "={r0}" (-> u32) : [param0] "{r0}" (param0), [param1] "{r1}" (param1) : "r0", "r1" ); } pub inline fn systemCall3Return(comptime call: u8, param0: u32, param1: u32, param2: u32) u32 { const assembly = comptime getSystemCallAssemblyCode(call); return asm volatile (assembly : [ret] "={r0}" (-> u32) : [param0] "{r0}" (param0), [param1] "{r1}" (param1), [param2] "{r2}" (param2) : "r0", "r1", "r2" ); } inline fn getSystemCallAssemblyCode(comptime call: u8) []const u8 { var buffer: [64]u8 = undefined; return fmt.bufPrint(buffer[0..], "swi {}", .{call}) catch unreachable; } };
GBA/bios.zig
const std = @import("std"); const builtin = @import("builtin"); const Builder = std.build.Builder; pub fn createPackage(comptime root: []const u8) std.build.Pkg { return std.build.Pkg{ .name = "lola", .path = .{ .path = root ++ "/src/library/main.zig" }, .dependencies = &[_]std.build.Pkg{ std.build.Pkg{ .name = "interface", .path = .{ .path = root ++ "/libs/interface.zig/interface.zig" }, }, std.build.Pkg{ .name = "any-pointer", .path = .{ .path = root ++ "/libs/any-pointer/any-pointer.zig" }, }, }, }; } const linkPcre = @import("libs/koino/vendor/libpcre.zig/build.zig").linkPcre; const pkgs = struct { const args = std.build.Pkg{ .name = "args", .path = .{ .path = "libs/args/args.zig" }, .dependencies = &[_]std.build.Pkg{}, }; const interface = std.build.Pkg{ .name = "interface", .path = .{ .path = "libs/interface.zig/interface.zig" }, .dependencies = &[_]std.build.Pkg{}, }; const lola = std.build.Pkg{ .name = "lola", .path = .{ .path = "src/library/main.zig" }, .dependencies = &[_]std.build.Pkg{ interface, any_pointer }, }; const koino = std.build.Pkg{ .name = "koino", .path = .{ .path = "libs/koino/src/koino.zig" }, .dependencies = &[_]std.build.Pkg{ std.build.Pkg{ .name = "libpcre", .path = .{ .path = "libs/koino/vendor/libpcre.zig/src/main.zig" } }, std.build.Pkg{ .name = "htmlentities", .path = .{ .path = "libs/koino/vendor/htmlentities.zig/src/main.zig" } }, std.build.Pkg{ .name = "clap", .path = .{ .path = "libs/koino/vendor/zig-clap/clap.zig" } }, std.build.Pkg{ .name = "zunicode", .path = .{ .path = "libs/koino/vendor/zunicode/src/zunicode.zig" } }, }, }; const any_pointer = std.build.Pkg{ .name = "any-pointer", .path = .{ .path = "libs/any-pointer/any-pointer.zig" }, }; }; const Example = struct { name: []const u8, path: []const u8, }; const examples = [_]Example{ Example{ .name = "minimal-host", .path = "examples/host/minimal-host/main.zig", }, Example{ .name = "multi-environment", .path = "examples/host/multi-environment/main.zig", }, Example{ .name = "serialization", .path = "examples/host/serialization/main.zig", }, }; pub fn build(b: *Builder) !void { const version_tag = b.option([]const u8, "version", "Sets the version displayed in the docs and for `lola version`"); const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const build_options = b.addOptions(); build_options.addOption([]const u8, "version", version_tag orelse "development"); const exe = b.addExecutable("lola", "src/frontend/main.zig"); exe.setBuildMode(mode); exe.setTarget(target); exe.addPackage(pkgs.lola); exe.addPackage(pkgs.args); exe.addPackage(build_options.getPackage("build_options")); exe.install(); const benchmark_renderer = b.addExecutable("benchmark-render", "src/benchmark/render.zig"); benchmark_renderer.setBuildMode(mode); benchmark_renderer.install(); { const render_benchmark_step = b.step("render-benchmarks", "Runs the benchmark suite."); const only_render_benchmark = benchmark_renderer.run(); only_render_benchmark.addArg(b.pathFromRoot("benchmarks/data")); only_render_benchmark.addArg(b.pathFromRoot("benchmarks/visualization")); render_benchmark_step.dependOn(&only_render_benchmark.step); } const benchmark_modes = [_]std.builtin.Mode{ .ReleaseSafe, .ReleaseFast, .ReleaseSmall, }; const benchmark_step = b.step("benchmark", "Runs the benchmark suite."); const render_benchmark = benchmark_renderer.run(); render_benchmark.addArg(b.pathFromRoot("benchmarks/data")); render_benchmark.addArg(b.pathFromRoot("benchmarks/visualization")); benchmark_step.dependOn(&render_benchmark.step); for (benchmark_modes) |benchmark_mode| { const benchmark = b.addExecutable(b.fmt("benchmark-{s}", .{@tagName(benchmark_mode)}), "src/benchmark/perf.zig"); benchmark.setBuildMode(benchmark_mode); benchmark.addPackage(pkgs.lola); const run_benchmark = benchmark.run(); run_benchmark.addArg(b.pathFromRoot("benchmarks/code")); run_benchmark.addArg(b.pathFromRoot("benchmarks/data")); render_benchmark.step.dependOn(&run_benchmark.step); } const wasm_runtime = b.addSharedLibrary("lola", "src/wasm-compiler/main.zig", .unversioned); wasm_runtime.addPackage(pkgs.lola); wasm_runtime.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }); wasm_runtime.setBuildMode(.ReleaseSafe); wasm_runtime.install(); const examples_step = b.step("examples", "Compiles all examples"); inline for (examples) |example| { const example_exe = b.addExecutable("example-" ++ example.name, example.path); example_exe.setBuildMode(mode); example_exe.setTarget(target); example_exe.addPackage(pkgs.lola); examples_step.dependOn(&b.addInstallArtifact(example_exe).step); } var main_tests = b.addTest("src/library/test.zig"); if (pkgs.lola.dependencies) |deps| { for (deps) |pkg| { main_tests.addPackage(pkg); } } main_tests.setBuildMode(mode); const test_step = b.step("test", "Run test suite"); test_step.dependOn(&main_tests.step); // Run compiler test suites { const prefix = "src/test/"; const behaviour_tests = exe.run(); behaviour_tests.addArg("run"); behaviour_tests.addArg("--no-stdlib"); // we don't want the behaviour tests to be run with any stdlib functions behaviour_tests.addArg(prefix ++ "behaviour.lola"); behaviour_tests.expectStdOutEqual("Behaviour test suite passed.\n"); test_step.dependOn(&behaviour_tests.step); const stdib_test = exe.run(); stdib_test.addArg("run"); stdib_test.addArg(prefix ++ "stdlib.lola"); stdib_test.expectStdOutEqual("Standard library test suite passed.\n"); test_step.dependOn(&stdib_test.step); // when the host is windows, this won't work :( if (builtin.os.tag != .windows) { std.fs.cwd().makeDir("zig-cache/tmp") catch |err| switch (err) { error.PathAlreadyExists => {}, // nice else => |e| return e, }; const runlib_test = exe.run(); // execute in the zig-cache directory so we have a "safe" playfield // for file I/O runlib_test.cwd = "zig-cache/tmp"; // `Exit(123)` is the last call in the runtime suite runlib_test.expected_exit_code = 123; runlib_test.expectStdOutEqual( \\ \\1 \\1.2 \\[ ] \\[ 1, 2 ] \\truefalse \\hello \\Runtime library test suite passed. \\ ); runlib_test.addArg("run"); runlib_test.addArg("../../" ++ prefix ++ "runtime.lola"); test_step.dependOn(&runlib_test.step); } const emptyfile_test = exe.run(); emptyfile_test.addArg("run"); emptyfile_test.addArg(prefix ++ "empty.lola"); emptyfile_test.expectStdOutEqual(""); test_step.dependOn(&emptyfile_test.step); const globreturn_test = exe.run(); globreturn_test.addArg("run"); globreturn_test.addArg(prefix ++ "global-return.lola"); globreturn_test.expectStdOutEqual(""); test_step.dependOn(&globreturn_test.step); const extended_behaviour_test = exe.run(); extended_behaviour_test.addArg("run"); extended_behaviour_test.addArg(prefix ++ "behaviour-with-stdlib.lola"); extended_behaviour_test.expectStdOutEqual("Extended behaviour test suite passed.\n"); test_step.dependOn(&extended_behaviour_test.step); const compiler_test = exe.run(); compiler_test.addArg("compile"); compiler_test.addArg("--verify"); // verify should not emit a compiled module compiler_test.addArg(prefix ++ "compiler.lola"); compiler_test.expectStdOutEqual(""); test_step.dependOn(&compiler_test.step); } 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); ///////////////////////////////////////////////////////////////////////// // Documentation and Website generation: // this is disabed by-default so we don't depend on any vcpkgs if (b.option(bool, "enable-website", "Enables website generation.") orelse false) { // Generates documentation and future files. const gen_website_step = b.step("website", "Generates the website and all required resources."); const md_renderer = b.addExecutable("markdown-md-page", "src/tools/render-md-page.zig"); md_renderer.addPackage(pkgs.koino); try linkPcre(md_renderer); const render = md_renderer.run(); render.addArg(version_tag orelse "development"); gen_website_step.dependOn(&render.step); const copy_wasm_runtime = b.addSystemCommand(&[_][]const u8{ "cp", }); copy_wasm_runtime.addArtifactArg(wasm_runtime); copy_wasm_runtime.addArg("website/lola.wasm"); gen_website_step.dependOn(&copy_wasm_runtime.step); var gen_docs_runner = b.addTest(pkgs.lola.path.path); gen_docs_runner.emit_bin = .no_emit; gen_docs_runner.emit_asm = .no_emit; gen_docs_runner.emit_bin = .no_emit; gen_docs_runner.emit_docs = .{ .emit_to = "website/docs" }; gen_docs_runner.emit_h = false; gen_docs_runner.emit_llvm_ir = .no_emit; gen_docs_runner.addPackage(pkgs.interface); gen_docs_runner.addPackage(pkgs.any_pointer); gen_docs_runner.setBuildMode(mode); gen_website_step.dependOn(&gen_docs_runner.step); // Only generates documentation const gen_docs_step = b.step("docs", "Generate the code documentation"); gen_docs_step.dependOn(&gen_docs_runner.step); } }
build.zig
const __muloti4 = @import("muloti4.zig").__muloti4; const testing = @import("std").testing; fn test__muloti4(a: i128, b: i128, expected: i128, expected_overflow: c_int) void { var overflow: c_int = undefined; const x = __muloti4(a, b, &overflow); testing.expect(overflow == expected_overflow and (expected_overflow != 0 or x == expected)); } test "muloti4" { test__muloti4(0, 0, 0, 0); test__muloti4(0, 1, 0, 0); test__muloti4(1, 0, 0, 0); test__muloti4(0, 10, 0, 0); test__muloti4(10, 0, 0, 0); test__muloti4(0, 81985529216486895, 0, 0); test__muloti4(81985529216486895, 0, 0, 0); test__muloti4(0, -1, 0, 0); test__muloti4(-1, 0, 0, 0); test__muloti4(0, -10, 0, 0); test__muloti4(-10, 0, 0, 0); test__muloti4(0, -81985529216486895, 0, 0); test__muloti4(-81985529216486895, 0, 0, 0); test__muloti4(3037000499, 3037000499, 9223372030926249001, 0); test__muloti4(-3037000499, 3037000499, -9223372030926249001, 0); test__muloti4(3037000499, -3037000499, -9223372030926249001, 0); test__muloti4(-3037000499, -3037000499, 9223372030926249001, 0); test__muloti4(4398046511103, 2097152, 9223372036852678656, 0); test__muloti4(-4398046511103, 2097152, -9223372036852678656, 0); test__muloti4(4398046511103, -2097152, -9223372036852678656, 0); test__muloti4(-4398046511103, -2097152, 9223372036852678656, 0); test__muloti4(2097152, 4398046511103, 9223372036852678656, 0); test__muloti4(-2097152, 4398046511103, -9223372036852678656, 0); test__muloti4(2097152, -4398046511103, -9223372036852678656, 0); test__muloti4(-2097152, -4398046511103, 9223372036852678656, 0); test__muloti4(@bitCast(i128, @as(u128, 0x00000000000000B504F333F9DE5BE000)), @bitCast(i128, @as(u128, 0x000000000000000000B504F333F9DE5B)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFF328DF915DA296E8A000)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(-2, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), -1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0); test__muloti4(-1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0, 0, 0); test__muloti4(0, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0, 0); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0); test__muloti4(1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(2, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(-2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), -1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(-1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0, 0, 0); test__muloti4(0, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0, 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0); test__muloti4(1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(-2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), -1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0); test__muloti4(-1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0, 0, 0); test__muloti4(0, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0, 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0); test__muloti4(1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); }
lib/std/special/compiler_rt/muloti4_test.zig
const page_table = @import("page_table.zig"); pub const PAGE_TABLE_ENTRY_COUNT = page_table.PAGE_TABLE_ENTRY_COUNT; pub const FrameError = page_table.FrameError; pub const PageTableEntry = page_table.PageTableEntry; pub const PageTableFlags = page_table.PageTableFlags; pub const PageTable = page_table.PageTable; pub const PageTableIndex = page_table.PageTableIndex; pub const PageOffset = page_table.PageOffset; const frame = @import("frame.zig"); pub const PhysFrame = frame.PhysFrame; pub const PhysFrame2MiB = frame.PhysFrame2MiB; pub const PhysFrame1GiB = frame.PhysFrame1GiB; pub const PhysFrameError = frame.PhysFrameError; pub const PhysFrameIterator = frame.PhysFrameIterator; pub const PhysFrameIterator2MiB = frame.PhysFrameIterator2MiB; pub const PhysFrameIterator1GiB = frame.PhysFrameIterator1GiB; pub const PhysFrameRange = frame.PhysFrameRange; pub const PhysFrameRange2MiB = frame.PhysFrameRange2MiB; pub const PhysFrameRange1GiB = frame.PhysFrameRange1GiB; pub const PhysFrameRangeInclusive = frame.PhysFrameRangeInclusive; pub const PhysFrameRange2MiBInclusive = frame.PhysFrameRange2MiBInclusive; pub const PhysFrameRange1GiBInclusive = frame.PhysFrameRange1GiBInclusive; const page = @import("page.zig"); pub const PageSize = page.PageSize; pub const Page = page.Page; pub const Page2MiB = page.Page2MiB; pub const Page1GiB = page.Page1GiB; pub const PageError = page.PageError; pub const pageFromTableIndices = page.pageFromTableIndices; pub const pageFromTableIndices2MiB = page.pageFromTableIndices2MiB; pub const pageFromTableIndices1GiB = page.pageFromTableIndices1GiB; pub const PageRange = page.PageRange; pub const PageRange2MiB = page.PageRange2MiB; pub const PageRange1GiB = page.PageRange1GiB; pub const PageRangeInclusive = page.PageRangeInclusive; pub const PageRange2MiBInclusive = page.PageRange2MiBInclusive; pub const PageRange1GiBInclusive = page.PageRange1GiBInclusive; pub const PageIterator = page.PageIterator; pub const PageIterator2MiB = page.PageIterator2MiB; pub const PageIterator1GiB = page.PageIterator1GiB; const frame_alloc = @import("frame_alloc.zig"); pub const FrameAllocator = frame_alloc.FrameAllocator; pub const mapping = @import("mapping/mapping.zig"); comptime { @import("std").testing.refAllDecls(@This()); }
src/structures/paging/paging.zig
const crc = @import("crc"); const it = @import("ziter"); const std = @import("std"); const util = @import("util"); const int = @import("../int.zig"); const nds = @import("../nds.zig"); const ascii = std.ascii; const debug = std.debug; const io = std.io; const mem = std.mem; const lu16 = int.lu16; const lu32 = int.lu32; const lu64 = int.lu64; pub const crc_modbus = blk: { @setEvalBranchQuota(crc.crcspec_init_backward_cycles); break :blk crc.CrcSpec(u16).init(0x8005, 0xFFFF, 0x0000, true, true); }; test "nds.crc_modbus" { debug.assert(crc_modbus.checksum("123456789") == 0x4B37); } // http://problemkaputt.de/gbatek.htm#dscartridgeheader pub const Header = extern struct { game_title: util.TerminatedArray(12, u8, 0), gamecode: [4]u8, makercode: [2]u8, unitcode: u8, encryption_seed_select: u8, device_capacity: u8, reserved1: [7]u8, reserved2: u8, // (except, used on DSi) nds_region: u8, rom_version: u8, autostart: u8, arm9: Arm, arm7: Arm, fnt: nds.Slice, fat: nds.Slice, arm9_overlay: nds.Slice, arm7_overlay: nds.Slice, // TODO: Rename when I know exactly what his means. port_40001a4h_setting_for_normal_commands: [4]u8, port_40001a4h_setting_for_key1_commands: [4]u8, banner_offset: lu32, secure_area_checksum: lu16, secure_area_delay: lu16, arm9_auto_load_list_ram_address: lu32, arm7_auto_load_list_ram_address: lu32, secure_area_disable: lu64, total_used_rom_size: lu32, rom_header_size: lu32, reserved3: [0x38]u8, nintendo_logo: [0x9C]u8, nintendo_logo_checksum: lu16, header_checksum: lu16, debug_rom_offset: lu32, debug_size: lu32, debug_ram_address: lu32, reserved4: [4]u8, reserved5: [0x10]u8, // New DSi Header Entries wram_slots: [20]u8, arm9_wram_areas: [12]u8, arm7_wram_areas: [12]u8, wram_slot_master: [3]u8, // 1AFh 1 ... whatever, rather not 4000247h WRAMCNT ? // (above byte is usually 03h) // (but, it's FCh in System Menu?) // (but, it's 00h in System Settings?) unknown: u8, region_flags: [4]u8, access_control: [4]u8, arm7_scfg_ext_setting: [4]u8, reserved6: [3]u8, // 1BFh 1 Flags? (usually 01h) (DSiware Browser: 0Bh) // bit2: Custom Icon (0=No/Normal, 1=Use banner.sav) unknown_flags: u8, arm9i_rom_offset: lu32, reserved7: [4]u8, arm9i_ram_load_address: lu32, arm9i_size: lu32, arm7i_rom_offset: lu32, device_list_arm7_ram_addr: lu32, arm7i_ram_load_address: lu32, arm7i_size: lu32, digest_ntr_region_offset: lu32, digest_ntr_region_length: lu32, digest_twl_region_offset: lu32, digest_twl_region_length: lu32, digest_sector_hashtable_offset: lu32, digest_sector_hashtable_length: lu32, digest_block_hashtable_offset: lu32, digest_block_hashtable_length: lu32, digest_sector_size: lu32, digest_block_sectorcount: lu32, banner_size: lu32, reserved8: [4]u8, total_used_rom_size_including_dsi_area: lu32, reserved9: [4]u8, reserved10: [4]u8, reserved11: [4]u8, modcrypt_area_1_offset: lu32, modcrypt_area_1_size: lu32, modcrypt_area_2_offset: lu32, modcrypt_area_2_size: lu32, title_id_emagcode: [4]u8, title_id_filetype: u8, // 235h 1 Title ID, Zero (00h=Normal) // 236h 1 Title ID, Three (03h=Normal, why?) // 237h 1 Title ID, Zero (00h=Normal) title_id_rest: [3]u8, public_sav_filesize: lu32, private_sav_filesize: lu32, reserved12: [176]u8, // Parental Control Age Ratings cero_japan: u8, esrb_us_canada: u8, reserved13: u8, usk_germany: u8, pegi_pan_europe: u8, resereved14: u8, pegi_portugal: u8, pegi_and_bbfc_uk: u8, agcb_australia: u8, grb_south_korea: u8, reserved15: [6]u8, // SHA1-HMACS and RSA-SHA1 arm9_hash_with_secure_area: [20]u8, arm7_hash: [20]u8, digest_master_hash: [20]u8, icon_title_hash: [20]u8, arm9i_hash: [20]u8, arm7i_hash: [20]u8, reserved16: [40]u8, arm9_hash_without_secure_area: [20]u8, reserved17: [2636]u8, reserved18: [0x180]u8, signature_across_header_entries: [0x80]u8, comptime { debug.assert(@sizeOf(Header) == 4096); } pub const Arm = extern struct { offset: lu32, entry_address: lu32, ram_address: lu32, size: lu32, }; pub fn isDsi(header: Header) bool { return (header.unitcode & 0x02) != 0; } pub fn calcChecksum(header: Header) u16 { return crc_modbus.checksum(mem.toBytes(header)[0..0x15E]); } pub fn validate(header: Header) !void { if (header.header_checksum.value() != header.calcChecksum()) return error.InvalidHeaderChecksum; if (!it.all(header.game_title.span(), notLower)) return error.InvalidGameTitle; if (!it.all(&header.gamecode, ascii.isUpper)) return error.InvalidGamecode; // TODO: Docs says that makercode is uber ascii, but for Pokemon games, it is // ascii numbers. //const makercode = ascii.asAsciiConst(header.makercode) catch return error.InvalidMakercode; //if (!it.all(makercode, ascii.isUpper)) // return error.InvalidMakercode; if (header.unitcode > 0x03) return error.InvalidUnitcode; if (header.encryption_seed_select > 0x07) return error.InvalidEncryptionSeedSelect; //if (!it.all(header.reserved1[0..], isZero)) // return error.InvalidReserved1; // It seems that arm9 (secure area) is always at 0x4000 // http://problemkaputt.de/gbatek.htm#dscartridgesecurearea if (header.arm9.offset.value() != 0x4000) return error.InvalidArm9RomOffset; if (header.arm9.entry_address.value() < 0x2000000 or 0x23BFE00 < header.arm9.entry_address.value()) return error.InvalidArm9EntryAddress; if (header.arm9.ram_address.value() < 0x2000000 or 0x23BFE00 < header.arm9.ram_address.value()) return error.InvalidArm9RamAddress; if (header.arm9.size.value() > 0x3BFE00) return error.InvalidArm9Size; if (header.arm7.offset.value() < 0x8000) return error.InvalidArm7RomOffset; if ((header.arm7.entry_address.value() < 0x2000000 or 0x23BFE00 < header.arm7.entry_address.value()) and (header.arm7.entry_address.value() < 0x37F8000 or 0x3807E00 < header.arm7.entry_address.value())) return error.InvalidArm7EntryAddress; if ((header.arm7.ram_address.value() < 0x2000000 or 0x23BFE00 < header.arm7.ram_address.value()) and (header.arm7.ram_address.value() < 0x37F8000 or 0x3807E00 < header.arm7.ram_address.value())) return error.InvalidArm7RamAddress; if (header.arm7.size.value() > 0x3BFE00) return error.InvalidArm7Size; if (header.banner_offset.value() != 0 and header.banner_offset.value() < 0x8000) return error.InvalidIconTitleOffset; if (header.secure_area_delay.value() != 0x051E and header.secure_area_delay.value() != 0x0D7E) return error.InvalidSecureAreaDelay; if (header.rom_header_size.value() != 0x4000) return error.InvalidRomHeaderSize; //if (!it.all(header.reserved3, isZero)) // return error.InvalidReserved3; //if (!it.all(header.reserved4, isZero)) // return error.InvalidReserved4; //if (!it.all(header.reserved5, isZero)) // return error.InvalidReserved5; if (header.isDsi()) { //if (!it.all(header.reserved6[0..], isZero)) // return error.InvalidReserved6; //if (!it.all(header.reserved7[0..], isZero)) // return error.InvalidReserved7; // TODO: (usually same as ARM9 rom offs, 0004000h) // Does that mean that it also always 0x4000? if (header.digest_ntr_region_offset.value() != 0x4000) return error.InvalidDigestNtrRegionOffset; //if (!mem.eql(u8, header.reserved8, [_]u8{ 0x00, 0x00, 0x01, 0x00 })) // return error.InvalidReserved8; //if (!it.all(header.reserved9, isZero)) // return error.InvalidReserved9; if (!mem.eql(u8, &header.title_id_rest, "\x00\x03\x00")) return error.InvalidTitleIdRest; //if (!it.all(header.reserved12, isZero)) // return error.InvalidReserved12; //if (!it.all(header.reserved16, isZero)) // return error.InvalidReserved16; //if (!it.all(header.reserved17, isZero)) // return error.InvalidReserved17; //if (!it.all(header.reserved18, isZero)) // return error.InvalidReserved18; } } fn isZero(b: u8) bool { return b == 0; } fn notLower(char: u8) bool { return !ascii.isLower(char); } };
src/core/rom/nds/header.zig
const std = @import("std"); usingnamespace @import("wren.zig"); /// Sets the basic Wren default configuration with the basic handlers /// defined in this library pub fn initDefaultConfig (configuration:[*c]Configuration) void { initConfiguration(configuration); configuration.*.writeFn = bindings.writeFn; configuration.*.errorFn = bindings.errorFn; configuration.*.bindForeignMethodFn = bindings.foreignMethodFn; configuration.*.bindForeignClassFn = bindings.bindForeignClassFn; configuration.*.loadModuleFn = bindings.loadModuleFn; } /// Returns a basic configuration with the default handlers. /// See initDefaultConfig for setting an existing configuration. pub fn defaultConfig () Configuration { var config:Configuration = undefined; initDefaultConfig(&config); return config; } /// Tests if a C string matches a Zig string pub fn matches (cstr:CString,str:[]const u8) bool { return std.mem.eql(u8,std.mem.span(cstr),str); } /// Loads a Wren source file based on the current working path /// Appends '.wren' onto the end of the given path /// Caller must deallocate file contents? pub fn loadWrenSourceFile (allocator:*std.mem.Allocator,path:[]const u8) !CString { const file_size_limit:usize = 1024 * 1024 * 2; // 2Mb, should be pretty reasonable const c_dir = std.fs.cwd(); const fpath = std.mem.concat(allocator,u8, &[_][]const u8{std.mem.span(path),".wren"[0..]} ) catch unreachable; defer allocator.free(fpath); const cpath = c_dir.realpathAlloc(allocator,".") catch unreachable; defer allocator.free(cpath); std.debug.print("Loading module: {s} from location {s}\n",.{fpath,cpath}); const file_contents = try c_dir.readFileAlloc(allocator,fpath,file_size_limit); const rval = @ptrCast([*c]const u8,file_contents); return rval; } /// A simple code runner pub fn run (vm:?*VM,module:CString,code:CString) !void { var call_res = @intToEnum(ResType,interpret(vm,module,code)); switch (call_res) { .compile_error => return error.CompileError, .runtime_error => return error.RuntimeError, .success => return, //else => return error.UnexpectedResult, } } /// Retuns the DataType enum of the slot type at the given index pub fn slotType(vm:?*VM,slot:i32) DataType { return @intToEnum(DataType,getSlotType(vm,slot)); } /// Returns true for types of [*c]const u8 and [*c]u8 pub fn isCString(comptime T:type) bool { comptime { const info = @typeInfo(T); if (info != .Pointer) return false; const ptr = &info.Pointer; return (ptr.size == .C and ptr.is_volatile == false and ptr.alignment == 1 and ptr.child == u8 and ptr.is_allowzero == true and ptr.sentinel == null); } } /// Prints the current slot state to stdout via std.debug.print pub fn dumpSlotState(vm:?*VM) void { const print = std.debug.print; //Lazy var active_slots = getSlotCount(vm); print("\nSlots Acitve: {}\n",.{active_slots}); var i:c_int = 0; while(i < active_slots) : (i += 1) { var slot_type = slotType(vm,i); print(" [{d}]: {s}\n '---> ",.{i,slot_type}); switch(slot_type) { .wren_bool => print("{}\n",.{getSlotBool(vm,i)}), .wren_foreign => print("{any}\n",.{getSlotForeign(vm,i)}), .wren_list => print("List [{d}]\n",.{getListCount(vm,i)}), .wren_map => print("{s}\n",.{"MAP"}), .wren_null => print("{s}\n",.{"NULL"}), .wren_num => print("{d}\n",.{getSlotDouble(vm,i)}), .wren_string => print("{s}\n",.{getSlotString(vm,i)}), .wren_unknown => { var handle = getSlotHandle(vm,i); print("{any}\n",.{handle}); }, } } } pub fn isHashMap(comptime hash_map:anytype) bool { return @hasDecl(hash_map,"KV") and @hasDecl(hash_map,"Hash"); } const KVType = struct {key:type, value:type}; pub fn getHashMapTypes(comptime hash_map:anytype) KVType { return .{ .key = TypeOfField(hash_map.KV, "key"), .value = TypeOfField(hash_map.KV, "value"), }; } pub fn TypeOfField(comptime structure: anytype, comptime field_name: []const u8) type { inline for (std.meta.fields(structure)) |f| { if (std.mem.eql(u8, f.name, field_name)) { return f.field_type; } } @compileError(field_name ++ " not found in " ++ @typeName(@TypeOf(structure))); }
src/util.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const meta = std.meta; const trait = meta.trait; const assert = std.debug.assert; const testing = std.testing; const mustache = @import("../mustache.zig"); const RenderOptions = mustache.options.RenderOptions; const Delimiters = mustache.Delimiters; const context = @import("context.zig"); const Escape = context.Escape; const rendering = @import("rendering.zig"); /// Context for a lambda call, /// this type must be accept as parameter by any function intended to be used as a lambda /// /// When a lambda is called, any children {{tags}} will not have been expanded - the lambda should do that on its own. /// In this way you can implement transformations, filters or caching. pub const LambdaContext = struct { ptr: *const anyopaque, vtable: *const VTable, inner_text: []const u8, const VTable = struct { renderAlloc: fn (*const anyopaque, Allocator, []const u8) anyerror![]u8, render: fn (*const anyopaque, Allocator, []const u8) anyerror!void, write: fn (*const anyopaque, []const u8) anyerror!usize, }; /// Renders a template against the current context /// Returns an owned mutable slice with the rendered text pub inline fn renderAlloc(self: LambdaContext, allocator: Allocator, template_text: []const u8) anyerror![]u8 { return try self.vtable.renderAlloc(self.ptr, allocator, template_text); } /// Formats a template to be rendered against the current context /// Returns an owned mutable slice with the rendered text pub fn renderFormatAlloc(self: LambdaContext, allocator: Allocator, comptime fmt: []const u8, args: anytype) anyerror![]u8 { const template_text = try std.fmt.allocPrint(allocator, fmt, args); defer allocator.free(template_text); return try self.vtable.renderAlloc(self.ptr, allocator, template_text); } /// Renders a template against the current context /// Can return anyerror depending on the underlying writer pub inline fn render(self: LambdaContext, allocator: Allocator, template_text: []const u8) anyerror!void { try self.vtable.render(self.ptr, allocator, template_text); } /// Formats a template to be rendered against the current context /// Can return anyerror depending on the underlying writer pub fn renderFormat(self: LambdaContext, allocator: Allocator, comptime fmt: []const u8, args: anytype) anyerror!void { const template_text = try std.fmt.allocPrint(allocator, fmt, args); defer allocator.free(template_text); try self.vtable.render(self.ptr, allocator, template_text); } /// Writes the raw text on the output stream. /// Can return anyerror depending on the underlying writer pub fn writeFormat(self: LambdaContext, comptime fmt: []const u8, args: anytype) anyerror!void { var writer = std.io.Writer(LambdaContext, anyerror, writeFn){ .context = self, }; try std.fmt.format(writer, fmt, args); } /// Writes the raw text on the output stream. /// Can return anyerror depending on the underlying writer pub fn write(self: LambdaContext, raw_text: []const u8) anyerror!void { _ = try self.vtable.write(self.ptr, raw_text); } fn writeFn(self: LambdaContext, bytes: []const u8) anyerror!usize { return try return self.vtable.write(self.ptr, bytes); } }; pub fn LambdaContextImpl(comptime Writer: type, comptime PartialsMap: type, comptime options: RenderOptions) type { const RenderEngine = rendering.RenderEngine(Writer, PartialsMap, options); const DataRender = RenderEngine.DataRender; return struct { const Self = @This(); data_render: *DataRender, escape: Escape, delimiters: Delimiters, const vtable = LambdaContext.VTable{ .renderAlloc = renderAlloc, .render = render, .write = write, }; pub fn context(self: *Self, inner_text: []const u8) LambdaContext { return .{ .ptr = self, .vtable = &vtable, .inner_text = inner_text, }; } fn renderAlloc(ctx: *const anyopaque, allocator: Allocator, template_text: []const u8) anyerror![]u8 { var self = getSelf(ctx); var template = switch (try mustache.parseText(allocator, template_text, self.delimiters, .{ .copy_strings = false })) { .success => |value| value, .parse_error => |detail| return detail.parse_error, }; defer template.deinit(allocator); var out_writer = self.data_render.out_writer; var list = std.ArrayList(u8).init(allocator); self.data_render.out_writer = .{ .Buffer = list.writer() }; defer { self.data_render.out_writer = out_writer; list.deinit(); } try self.data_render.render(template.elements); return list.toOwnedSlice(); } fn render(ctx: *const anyopaque, allocator: Allocator, template_text: []const u8) anyerror!void { var self = getSelf(ctx); var template = switch (try mustache.parseText(allocator, template_text, self.delimiters, .{ .copy_strings = false })) { .success => |value| value, .parse_error => return, }; defer template.deinit(allocator); try self.data_render.render(template.elements); } fn write(ctx: *const anyopaque, rendered_text: []const u8) anyerror!usize { var self = getSelf(ctx); return try self.data_render.countWrite(rendered_text, self.escape); } inline fn getSelf(ctx: *const anyopaque) *const Self { return @ptrCast(*const Self, @alignCast(@alignOf(Self), ctx)); } }; } /// Returns true if TValue is a type generated by LambdaInvoker(...) pub fn isLambdaInvoker(comptime TValue: type) bool { if (comptime trait.isSingleItemPtr(TValue)) { return isLambdaInvoker(meta.Child(TValue)); } else { return @typeInfo(TValue) == .Struct and @hasField(TValue, "data") and @hasField(TValue, "bound_fn") and blk: { const TFn = meta.fieldInfo(TValue, .bound_fn).field_type; const TData = meta.fieldInfo(TValue, .data).field_type; break :blk comptime isValidLambdaFunction(TData, TFn) and TValue == LambdaInvoker(TData, TFn); }; } } test "isLambdaInvoker" { const foo = struct { pub fn _foo(ctx: LambdaContext) void { _ = ctx; } }._foo; const TFn = @TypeOf(foo); const Impl = LambdaInvoker(void, TFn); const IsntImpl = struct { field: usize }; try testing.expect(isLambdaInvoker(Impl)); try testing.expect(isLambdaInvoker(IsntImpl) == false); try testing.expect(isLambdaInvoker(TFn) == false); try testing.expect(isLambdaInvoker(u32) == false); } /// Returns true if TFn is a function of one of the signatures: /// fn (LambdaContext) anyerror!void /// fn (TData, LambdaContext) anyerror!void /// fn (*const TData, LambdaContext) anyerror!void /// fn (*TData, LambdaContext) anyerror!void pub fn isValidLambdaFunction(comptime TData: type, comptime TFn: type) bool { const fn_info = switch (@typeInfo(TFn)) { .Fn => |info| info, else => return false, }; //TODO: deprecated const Type = std.builtin.TypeInfo; const argIs = struct { fn _argIs(comptime arg: Type.FnArg, comptime types: []const type) bool { inline for (types) |compare_to| { if (arg.arg_type) |arg_type| { if (arg_type == compare_to) return true; } } else { return false; } } }._argIs; const TValue = if (comptime meta.trait.isSingleItemPtr(TData)) meta.Child(TData) else TData; const valid_args = comptime switch (fn_info.args.len) { 1 => argIs(fn_info.args[0], &.{LambdaContext}), 2 => argIs(fn_info.args[0], &.{ TValue, *const TValue, *TValue }) and argIs(fn_info.args[1], &.{LambdaContext}), else => false, }; const valid_return = comptime if (fn_info.return_type) |return_type| switch (@typeInfo(return_type)) { .ErrorUnion => |err_info| err_info.payload == void, .Void => true, else => false, } else false; return valid_args and valid_return; } test "isValidLambdaFunction" { const signatures = struct { const Self = struct {}; const WrongSelf = struct {}; const static_valid_1 = fn (LambdaContext) anyerror!void; const static_valid_2 = fn (LambdaContext) void; const self_valid_1 = fn (Self, LambdaContext) anyerror!void; const self_valid_2 = fn (*const Self, LambdaContext) anyerror!void; const self_valid_3 = fn (*Self, LambdaContext) anyerror!void; const self_valid_4 = fn (Self, LambdaContext) void; const self_valid_5 = fn (*const Self, LambdaContext) void; const self_valid_6 = fn (*Self, LambdaContext) void; const invalid_return_1 = fn (LambdaContext) anyerror!u32; const invalid_return_2 = fn (Self, LambdaContext) anyerror![]const u8; const invalid_return_3 = fn (*const Self, LambdaContext) anyerror!?usize; const invalid_return_4 = fn (*Self, LambdaContext) []u8; const invalid_args_1 = fn () anyerror!void; const invalid_args_2 = fn (Self) anyerror!void; const invalid_args_3 = fn (*const Self) anyerror!void; const invalid_args_4 = fn (*Self) anyerror!void; const invalid_args_5 = fn (u32) anyerror!void; const invalid_args_6 = fn (LambdaContext, Self) anyerror!void; const invalid_args_7 = fn (LambdaContext, u32) anyerror!void; const invalid_args_8 = fn (Self, LambdaContext, u32) anyerror!void; }; try testing.expect(isValidLambdaFunction(signatures.Self, signatures.static_valid_1)); try testing.expect(isValidLambdaFunction(void, signatures.static_valid_1)); try testing.expect(isValidLambdaFunction(signatures.WrongSelf, signatures.static_valid_1)); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.static_valid_2)); try testing.expect(isValidLambdaFunction(void, signatures.static_valid_2)); try testing.expect(isValidLambdaFunction(signatures.WrongSelf, signatures.static_valid_2)); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.self_valid_1)); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.self_valid_2)); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.self_valid_3)); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.self_valid_4)); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.self_valid_5)); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.self_valid_6)); try testing.expect(isValidLambdaFunction(signatures.WrongSelf, signatures.self_valid_1) == false); try testing.expect(isValidLambdaFunction(signatures.WrongSelf, signatures.self_valid_2) == false); try testing.expect(isValidLambdaFunction(signatures.WrongSelf, signatures.self_valid_3) == false); try testing.expect(isValidLambdaFunction(signatures.WrongSelf, signatures.self_valid_4) == false); try testing.expect(isValidLambdaFunction(signatures.WrongSelf, signatures.self_valid_5) == false); try testing.expect(isValidLambdaFunction(signatures.WrongSelf, signatures.self_valid_6) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_return_1) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_return_2) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_return_3) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_return_4) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_args_1) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_args_2) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_args_3) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_args_4) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_args_5) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_args_6) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_args_7) == false); try testing.expect(isValidLambdaFunction(signatures.Self, signatures.invalid_args_8) == false); } pub fn LambdaInvoker(comptime TData: type, comptime TFn: type) type { return struct { const Self = @This(); bound_fn: TFn, data: TData, pub fn invoke(self: *const Self, lambda_context: LambdaContext) anyerror!void { comptime { if (!isValidLambdaFunction(TData, TFn)) { @compileLog("isValidLambdaFunction", TData, TFn); } } const fn_type = @typeInfo(TFn).Fn; const return_type = fn_type.return_type orelse @compileError("Generic function could not be evaluated"); const has_error = @typeInfo(return_type) == .ErrorUnion; const args = if (TData == void) .{lambda_context} else blk: { // Determining the correct type to call the first argument // depending on how is was declared on the lambda signature // // fn(self TValue ...) // fn(self *const TValue ...) // fn(self *TValue ...) const fnArg = fn_type.args[0].arg_type orelse @compileError("Generic argument could not be evaluated"); switch (@typeInfo(TData)) { .Pointer => |info| { switch (info.size) { .One => { if (info.child == fnArg) { // Context is a pointer, but the parameter is a value // fn (self TValue ...) called from a *TValue or *const TValue break :blk .{ self.data.*, lambda_context }; } else { switch (@typeInfo(fnArg)) { .Pointer => |arg_info| { if (info.child == arg_info.child) { if (arg_info.is_const == true or info.is_const == false) { // Both context and parameter are pointers // fn (self *TValue ...) called from a *TValue // or // fn (self const* TValue ...) called from a *const TValue or *TValue break :blk .{ self.data, lambda_context }; } } }, else => {}, } } }, else => {}, } }, else => { switch (@typeInfo(fnArg)) { .Pointer => |arg_info| { if (TData == arg_info.child and arg_info.is_const == true) { // fn (self const* TValue ...) break :blk .{ &self.data, lambda_context }; } }, else => { if (TData == fnArg) { // Both context and parameter are the same type:'' // fn (self TValue ...) called from a TValue // or // fn (self *TValue ...) called from a *TValue // or // fn (self const* TValue ...) called from a *const TValue break :blk .{ self.data, lambda_context }; } }, } }, } // Cannot call the function if the lambda expects a mutable reference // and the context is a value or a const pointer return; }; if (has_error) try @call(.{}, self.bound_fn, args) else @call(.{}, self.bound_fn, args); } }; } test "LambdaInvoker" { // LambdaInvoker is comptime validated // Only valid sinatures can be used // Invalid signatures are tested on "isValidLambdaFunction" const Foo = struct { var static_counter: u32 = 0; counter: u32 = 0, pub fn staticFn(ctx: LambdaContext) void { _ = ctx; static_counter += 1; } pub fn selfFnValue(self: @This(), ctx: LambdaContext) void { _ = self; _ = ctx; static_counter += 1; } pub fn selfFnConstPtr(self: *const @This(), ctx: LambdaContext) void { _ = self; _ = ctx; static_counter += 1; } pub fn selfFnPtr(self: *@This(), ctx: LambdaContext) void { _ = ctx; static_counter += 1; self.counter += 1; } }; { const Impl = LambdaInvoker(void, @TypeOf(Foo.staticFn)); var impl = Impl{ .bound_fn = Foo.staticFn, .data = {} }; const last_counter = Foo.static_counter; try impl.invoke(undefined); try testing.expect(Foo.static_counter == last_counter + 1); try impl.invoke(undefined); try testing.expect(Foo.static_counter == last_counter + 2); } { const Impl = LambdaInvoker(Foo, @TypeOf(Foo.selfFnValue)); var foo = Foo{}; var impl = Impl{ .bound_fn = Foo.selfFnValue, .data = foo, }; const last_counter = Foo.static_counter; try impl.invoke(undefined); try testing.expect(Foo.static_counter == last_counter + 1); try testing.expect(foo.counter == 0); try impl.invoke(undefined); try testing.expect(Foo.static_counter == last_counter + 2); try testing.expect(foo.counter == 0); } { const Impl = LambdaInvoker(*Foo, @TypeOf(Foo.selfFnConstPtr)); var foo = Foo{}; var impl = Impl{ .bound_fn = Foo.selfFnConstPtr, .data = &foo, }; const last_counter = Foo.static_counter; try impl.invoke(undefined); try testing.expect(Foo.static_counter == last_counter + 1); try testing.expect(foo.counter == 0); try impl.invoke(undefined); try testing.expect(Foo.static_counter == last_counter + 2); try testing.expect(foo.counter == 0); } { const Impl = LambdaInvoker(*Foo, @TypeOf(Foo.selfFnPtr)); var foo = Foo{}; var impl = Impl{ .bound_fn = Foo.selfFnPtr, .data = &foo, }; const last_counter = Foo.static_counter; try impl.invoke(undefined); try testing.expect(Foo.static_counter == last_counter + 1); try testing.expect(foo.counter == 1); try impl.invoke(undefined); try testing.expect(Foo.static_counter == last_counter + 2); try testing.expect(foo.counter == 2); } }
src/rendering/lambda.zig
const std = @import("std"); const Endian = std.builtin.Endian; const assert = std.debug.assert; const link = @import("../../link.zig"); const Module = @import("../../Module.zig"); const ErrorMsg = Module.ErrorMsg; const Liveness = @import("../../Liveness.zig"); const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput; const DW = std.dwarf; const leb128 = std.leb; const Emit = @This(); const Mir = @import("Mir.zig"); const bits = @import("bits.zig"); const Instruction = bits.Instruction; const Register = bits.Register; mir: Mir, bin_file: *link.File, debug_output: DebugInfoOutput, target: *const std.Target, err_msg: ?*ErrorMsg = null, src_loc: Module.SrcLoc, code: *std.ArrayList(u8), prev_di_line: u32, prev_di_column: u32, /// Relative to the beginning of `code`. prev_di_pc: usize, const InnerError = error{ OutOfMemory, EmitFail, }; pub fn emitMir( emit: *Emit, ) InnerError!void { const mir_tags = emit.mir.instructions.items(.tag); // Emit machine code for (mir_tags) |tag, index| { const inst = @intCast(u32, index); switch (tag) { .dbg_arg => try emit.mirDbgArg(inst), .dbg_line => try emit.mirDbgLine(inst), .dbg_prologue_end => try emit.mirDebugPrologueEnd(), .dbg_epilogue_begin => try emit.mirDebugEpilogueBegin(), .add => try emit.mirArithmetic3Op(inst), .bpcc => @panic("TODO implement sparcv9 bpcc"), .call => @panic("TODO implement sparcv9 call"), .jmpl => @panic("TODO implement sparcv9 jmpl"), .jmpl_i => @panic("TODO implement sparcv9 jmpl to reg"), .ldub => try emit.mirArithmetic3Op(inst), .lduh => try emit.mirArithmetic3Op(inst), .lduw => try emit.mirArithmetic3Op(inst), .ldx => try emit.mirArithmetic3Op(inst), .@"or" => try emit.mirArithmetic3Op(inst), .nop => try emit.mirNop(), .@"return" => try emit.mirArithmetic2Op(inst), .save => try emit.mirArithmetic3Op(inst), .restore => try emit.mirArithmetic3Op(inst), .sethi => try emit.mirSethi(inst), .sllx => @panic("TODO implement sparcv9 sllx"), .sub => try emit.mirArithmetic3Op(inst), .tcc => try emit.mirTrap(inst), } } } pub fn deinit(emit: *Emit) void { emit.* = undefined; } fn mirDbgArg(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const dbg_arg_info = emit.mir.instructions.items(.data)[inst].dbg_arg_info; _ = dbg_arg_info; switch (tag) { .dbg_arg => {}, // TODO try emit.genArgDbgInfo(dbg_arg_info.air_inst, dbg_arg_info.arg_index), else => unreachable, } } fn mirDbgLine(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const dbg_line_column = emit.mir.instructions.items(.data)[inst].dbg_line_column; switch (tag) { .dbg_line => try emit.dbgAdvancePCAndLine(dbg_line_column.line, dbg_line_column.column), else => unreachable, } } fn mirDebugPrologueEnd(self: *Emit) !void { switch (self.debug_output) { .dwarf => |dbg_out| { try dbg_out.dbg_line.append(DW.LNS.set_prologue_end); try self.dbgAdvancePCAndLine(self.prev_di_line, self.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirDebugEpilogueBegin(self: *Emit) !void { switch (self.debug_output) { .dwarf => |dbg_out| { try dbg_out.dbg_line.append(DW.LNS.set_epilogue_begin); try self.dbgAdvancePCAndLine(self.prev_di_line, self.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirArithmetic2Op(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const data = emit.mir.instructions.items(.data)[inst].arithmetic_2op; const rs1 = data.rs1; if (data.is_imm) { const imm = data.rs2_or_imm.imm; switch (tag) { .@"return" => try emit.writeInstruction(Instruction.@"return"(i13, rs1, imm)), else => unreachable, } } else { const rs2 = data.rs2_or_imm.rs2; switch (tag) { .@"return" => try emit.writeInstruction(Instruction.@"return"(Register, rs1, rs2)), else => unreachable, } } } fn mirArithmetic3Op(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const data = emit.mir.instructions.items(.data)[inst].arithmetic_3op; const rd = data.rd; const rs1 = data.rs1; if (data.is_imm) { const imm = data.rs2_or_imm.imm; switch (tag) { .add => try emit.writeInstruction(Instruction.add(i13, rs1, imm, rd)), .ldub => try emit.writeInstruction(Instruction.ldub(i13, rs1, imm, rd)), .lduh => try emit.writeInstruction(Instruction.lduh(i13, rs1, imm, rd)), .lduw => try emit.writeInstruction(Instruction.lduw(i13, rs1, imm, rd)), .ldx => try emit.writeInstruction(Instruction.ldx(i13, rs1, imm, rd)), .@"or" => try emit.writeInstruction(Instruction.@"or"(i13, rs1, imm, rd)), .save => try emit.writeInstruction(Instruction.save(i13, rs1, imm, rd)), .restore => try emit.writeInstruction(Instruction.restore(i13, rs1, imm, rd)), .sub => try emit.writeInstruction(Instruction.sub(i13, rs1, imm, rd)), else => unreachable, } } else { const rs2 = data.rs2_or_imm.rs2; switch (tag) { .add => try emit.writeInstruction(Instruction.add(Register, rs1, rs2, rd)), .ldub => try emit.writeInstruction(Instruction.ldub(Register, rs1, rs2, rd)), .lduh => try emit.writeInstruction(Instruction.lduh(Register, rs1, rs2, rd)), .lduw => try emit.writeInstruction(Instruction.lduw(Register, rs1, rs2, rd)), .ldx => try emit.writeInstruction(Instruction.ldx(Register, rs1, rs2, rd)), .@"or" => try emit.writeInstruction(Instruction.@"or"(Register, rs1, rs2, rd)), .save => try emit.writeInstruction(Instruction.save(Register, rs1, rs2, rd)), .restore => try emit.writeInstruction(Instruction.restore(Register, rs1, rs2, rd)), .sub => try emit.writeInstruction(Instruction.sub(Register, rs1, rs2, rd)), else => unreachable, } } } fn mirNop(emit: *Emit) !void { try emit.writeInstruction(Instruction.nop()); } fn mirSethi(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const data = emit.mir.instructions.items(.data)[inst].sethi; const imm = data.imm; const rd = data.rd; assert(tag == .sethi); try emit.writeInstruction(Instruction.sethi(imm, rd)); } fn mirTrap(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const data = emit.mir.instructions.items(.data)[inst].trap; const cond = data.cond; const ccr = data.ccr; const rs1 = data.rs1; if (data.is_imm) { const imm = data.rs2_or_imm.imm; switch (tag) { .tcc => try emit.writeInstruction(Instruction.trap(u7, cond, ccr, rs1, imm)), else => unreachable, } } else { const rs2 = data.rs2_or_imm.rs2; switch (tag) { .tcc => try emit.writeInstruction(Instruction.trap(Register, cond, ccr, rs1, rs2)), else => unreachable, } } } // Common helper functions fn dbgAdvancePCAndLine(self: *Emit, line: u32, column: u32) !void { const delta_line = @intCast(i32, line) - @intCast(i32, self.prev_di_line); const delta_pc: usize = self.code.items.len - self.prev_di_pc; switch (self.debug_output) { .dwarf => |dbg_out| { // TODO Look into using the DWARF special opcodes to compress this data. // It lets you emit single-byte opcodes that add different numbers to // both the PC and the line number at the same time. try dbg_out.dbg_line.ensureUnusedCapacity(11); dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_pc); leb128.writeULEB128(dbg_out.dbg_line.writer(), delta_pc) catch unreachable; if (delta_line != 0) { dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_line); leb128.writeILEB128(dbg_out.dbg_line.writer(), delta_line) catch unreachable; } dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.copy); self.prev_di_pc = self.code.items.len; self.prev_di_line = line; self.prev_di_column = column; self.prev_di_pc = self.code.items.len; }, .plan9 => |dbg_out| { if (delta_pc <= 0) return; // only do this when the pc changes // we have already checked the target in the linker to make sure it is compatable const quant = @import("../../link/Plan9/aout.zig").getPCQuant(self.target.cpu.arch) catch unreachable; // increasing the line number try @import("../../link/Plan9.zig").changeLine(dbg_out.dbg_line, delta_line); // increasing the pc const d_pc_p9 = @intCast(i64, delta_pc) - quant; if (d_pc_p9 > 0) { // minus one because if its the last one, we want to leave space to change the line which is one quanta try dbg_out.dbg_line.append(@intCast(u8, @divExact(d_pc_p9, quant) + 128) - quant); if (dbg_out.pcop_change_index.*) |pci| dbg_out.dbg_line.items[pci] += 1; dbg_out.pcop_change_index.* = @intCast(u32, dbg_out.dbg_line.items.len - 1); } else if (d_pc_p9 == 0) { // we don't need to do anything, because adding the quant does it for us } else unreachable; if (dbg_out.start_line.* == null) dbg_out.start_line.* = self.prev_di_line; dbg_out.end_line.* = line; // only do this if the pc changed self.prev_di_line = line; self.prev_di_column = column; self.prev_di_pc = self.code.items.len; }, .none => {}, } } fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError { @setCold(true); assert(emit.err_msg == null); emit.err_msg = try ErrorMsg.create(emit.bin_file.allocator, emit.src_loc, format, args); return error.EmitFail; } fn writeInstruction(emit: *Emit, instruction: Instruction) !void { // SPARCv9 instructions are always arranged in BE regardless of the // endianness mode the CPU is running in (Section 3.1 of the ISA specification). // This is to ease porting in case someone wants to do a LE SPARCv9 backend. const endian = Endian.Big; std.mem.writeInt(u32, try emit.code.addManyAsArray(4), instruction.toU32(), endian); }
src/arch/sparcv9/Emit.zig
const std = @import("std"); const gc = @import("gc.zig"); const Rational = std.math.big.Rational; const Allocator = std.mem.Allocator; // TODO: maybe something that allows plugging your own irrational numbers as Multiple: // it could be defined with a representation (e.g. Ο€) and a function to approximate the result /// Enumeration of exact value that are irrational const Multiple = enum { /// If multiple is one, this just means 'multiplier' field /// is the actual number. One, /// This one is special as it means the Real represents root_extra(multiplier) Root, /// Represents sqrt(multiplier), it's like with Root multiplier but we save on a Real Sqrt, /// This one means the Real represents log_extra(multiplier), that is /// performs a logarithm of base 'extra' with 'multiplier'. Log, /// This takes 'multiplier' to the power of 'extra' Exponential, /// It means the Real represents the result of multipler + extra Addition, // Actual irrational numbers Pi, EulerNumber, GoldenRatio, }; const Multiplier = union(enum) { Real: *Real, // TODO: maybe make it a pointer too to save space Rational: Rational, pub fn isOne(self: Multiplier) bool { var one = Rational.init(std.heap.page_allocator) catch unreachable; defer one.deinit(); one.setInt(1) catch unreachable; return switch (self) { .Real => |real| real.multiple == .One and real.multiplier.isOne(), .Rational => |rational| (rational.order(one) catch unreachable) == .eq }; } }; pub const bigOne = std.math.big.int.Const { .limbs = &.{1}, .positive = true }; /// This class can represent exactly any real number /// Note that it uses reference counting for memory management /// and so reals are passed as pointers only. /// Also note that the API of this interface is unmanged, that is /// you must always provide the allocator which MUST be the same /// during all of the real's lifetime. pub const Real = struct { multiplier: Multiplier, /// Used for things like logarithms and exponentials extra: ?*Real = null, multiple: Multiple, rc: gc.ReferenceCounter(Real) = .{}, // We only need multiplication (and exponentiation) and addition as for example: // 2 / sqrt(Ο€) can be translated to 2 * sqrt(Ο€)⁻¹ // and Ο€ - 1 can be translated to Ο€ + (-1) pub fn initRational(allocator: Allocator, number: Rational, multiple: Multiple) !*Real { const real = try allocator.create(Real); real.* = Real { .multiplier = .{ .Rational = number }, .multiple = multiple, }; return real; } fn initOne(allocator: Allocator, other: *Real) !*Real { const real = try allocator.create(Real); real.* = Real { .multiplier = .{ .Real = other }, .multiple = .One, }; return real; } pub fn pi(allocator: Allocator) !*Real { var one = try Rational.init(allocator); try one.setInt(1); return try Real.initRational(allocator, one, .Pi); } pub fn initFloat(allocator: Allocator, number: anytype) !*Real { var rational = try Rational.init(allocator); try rational.setFloat(@TypeOf(number), number); return try Real.initRational(allocator, rational, .One); } fn getRational(multiplier: *Multiplier) *Rational { switch (multiplier.*) { .Real => |real| return Real.getRational(&real.multiplier), .Rational => |*rational| return rational } } pub fn mul(a: *Real, allocator: Allocator, b: *const Real) std.mem.Allocator.Error!void { var new = allocator.create(Real); new.* = .{ .multiplier = a.multiplier, .multiple = b.multiple, }; switch (b.multiplier) { .Rational => |rational| { const second = getRational(&new.multiplier); try second.mul(rational, second.*); }, .Real => |real| { try new.mul(real.*); } } a.multiplier = .{ .Real = new }; a.simplify(); } pub fn pow(self: *Real, allocator: Allocator, exponent: *Real) std.mem.Allocator.Error!void { if (self.multiple != .One) { const new = try Real.initOne(allocator, self.*); self.* = new; } self.extra = exponent; self.multiple = .Exponential; self.simplify(); } pub fn add(a: *Real, allocator: Allocator, b: *const Real) std.mem.Allocator.Error!void { var newA = try a.clone(allocator); newA.simplify(allocator); var newB = try b.clone(allocator); newB.simplify(allocator); const rc = a.rc; a.* = .{ .multiplier = .{ .Real = newA }, .extra = newB, .multiple = .Addition, .rc = rc, }; a.simplify(allocator); } pub fn simplify(self: *Real, allocator: Allocator) void { // we're multiplying a real by one, which is redundant if (self.multiple == .One and self.multiplier == .Real) { const real = self.multiplier.Real; self.* = real.*; allocator.destroy(real); // extra and multiplier don't need deinit } // We check our multiplier // If it is a rational that is a multiple of one // That means we can simplify the multiplier by using // .{ .Rational = ... } if (self.multiplier == .Real and self.multiplier.Real.multiple == .One and self.multiplier.Real.multiplier == .Rational) { const rational = self.multiplier.Real.multiplier.Rational; var newRational = Rational.init(allocator) catch unreachable; newRational.copyRatio(rational.p, rational.q) catch unreachable; self.multiplier.Real.rc.dereference(); self.multiplier = .{ .Rational = newRational }; } if (self.extra) |extra| { std.log.info("extra: {*}", .{ extra }); extra.simplify(allocator); } if (self.multiple == .Addition) { const extra = self.extra.?; if (self.multiplier == .Rational and extra.multiple == .One) { switch (extra.multiplier) { .Rational => |*rational| { rational.add(rational.*, self.multiplier.Rational) catch unreachable; self.extra = null; self.selfDeinit(); self.* = extra.*; allocator.destroy(extra); }, .Real => |real| { _ = real; // TODO: try real.add(self.multiplier); } } } } } pub fn clone(self: *const Real, allocator: Allocator) std.mem.Allocator.Error!*Real { if (std.debug.runtime_safety and self.rc.count == 0) { @panic("Cannot clone an object with no references"); } var new = try allocator.create(Real); new.* = self.*; new.rc.count = 1; switch (new.multiplier) { .Real => |real| { new.multiplier = .{ .Real = try real.clone(allocator) }; }, .Rational => |rational| { var newRational = try Rational.init(allocator); try newRational.copyRatio(rational.p, rational.q); new.multiplier = .{ .Rational = newRational }; } } if (new.extra) |extra| { new.extra = try extra.clone(allocator); } return new; } fn formatImpl(value: Real, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, depth: usize) @TypeOf(writer).Error!void { const prefix: []const u8 = switch (value.multiple) { .Root => "root(", .Sqrt => "√(", .Log => "log(", .Exponential => "(", .Addition => "((", else => "" }; try writer.print("{s}", .{ prefix }); if (value.extra) |extra| { if (value.multiple != .Exponential) { // handled separately try formatImpl(extra.*, fmt, options, writer, depth + 1); if (value.multiple == .Addition) { try writer.print(") + (", .{}); } else { try writer.print(", ", .{}); } } } switch (value.multiplier) { .Real => |real| { try formatImpl(real.*, fmt, options, writer, depth + 1); if (depth > 0) { if (value.multiple == .Addition) { try writer.writeAll(" + "); } else { try writer.writeAll(" * "); } } }, .Rational => |rational| { // avoid useless things like 1 * number if (!(rational.p.toConst().eq(bigOne) and rational.q.toConst().eq(bigOne)) or true) { if (comptime std.mem.eql(u8, fmt, "d")) { const float = rational.toFloat(f64) catch unreachable; try writer.print("{d}", .{ float }); } else { try writer.print("{}/{}", .{ rational.p, rational.q }); } if (depth > 0) { if (value.multiple == .Addition) { try writer.writeAll(" + "); } else { try writer.writeAll(" * "); } } } } } const multiple: []const u8 = switch (value.multiple) { //.One => " * 1", .One => "", // * 1 is used purely for debug reasons .Pi => "Ο€", .EulerNumber => "e", .GoldenRatio => "Ξ¦", .Addition => "))", .Root, .Sqrt, .Log, .Exponential => ")", }; try writer.print("{s}", .{ multiple }); if (value.multiple == .Exponential) { try writer.print(" ^ (", .{}); try formatImpl(value.extra.?.*, fmt, options, writer, 0); try writer.print(")", .{}); } } pub fn format(value: Real, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try formatImpl(value, fmt, options, writer, 0); } pub fn deinit(self: *Real, allocator: Allocator) void { std.log.info("deinit rational {*}: rc={d} value={0}", .{ self, self.rc.count }); //std.debug.dumpCurrentStackTrace(null); self.rc.deinit(); self.selfDeinit(); allocator.destroy(self); } fn selfDeinit(self: *Real) void { switch (self.multiplier) { .Real => |real| { real.rc.dereference(); }, .Rational => |*rational| { rational.deinit(); } } if (self.extra) |extra| { std.log.info("deref extra", .{}); extra.rc.dereference(); } } // TODO: approximate() function, which computes the irrational up to around the given number of digits }; test "simple rationals" { const allocator = std.testing.allocator; var real = try Real.initFloat(allocator, @as(f64, 123.4)); defer real.deinit(); var pi = try Real.pi(allocator); defer pi.deinit(); std.log.err("{d}, multiplied by {d}", .{ real, pi }); try real.mul(pi); std.log.err("result = {d}", .{ real }); try real.mul(pi); std.log.err("result * pi = {d}", .{ real }); try real.pow(&pi); std.log.err("(result) ^ pi = {}", .{ real }); } test "addition" { const allocator = std.testing.allocator; var real = try Real.initFloat(allocator, @as(f64, 1.23456789)); defer real.deinit(); var pi = try Real.pi(allocator); defer pi.deinit(); std.log.err("{d} + {d}", .{ real, pi }); try real.add(pi); std.log.err("result = {d}", .{ real }); }
src/Real.zig
const std = @import("std"); const builtin = @import("builtin"); const T = std.testing; const date = @import("gregorianDate.zig"); const warn = std.debug.warn; test "Date coarse range check" { const R = enum { inRange, outOfRange, }; const RangeCheckElem = struct { y: i32, m: i32, d: i32, dflt: @typeOf(date.min), exp: R, val: i32, }; const rangeCheckTable = []RangeCheckElem{ RangeCheckElem{ .y = 2019, .m = 3, .d = 130, .dflt = date.min, .exp = R.outOfRange, .val = undefined }, RangeCheckElem{ .y = 2019, .m = 3, .d = 1, .dflt = date.min, .exp = R.inRange, .val = 1033792 }, RangeCheckElem{ .y = 2019, .m = 0, .d = 12, .dflt = date.min, .exp = R.outOfRange, .val = undefined }, RangeCheckElem{ .y = 2019, .m = -1, .d = 4, .dflt = date.min, .exp = R.outOfRange, .val = undefined }, RangeCheckElem{ .y = 2019, .m = 1, .d = 7, .dflt = date.min, .exp = R.inRange, .val = 1033734 }, RangeCheckElem{ .y = 2019, .m = 12, .d = 29, .dflt = date.min, .exp = R.inRange, .val = 1034108 }, RangeCheckElem{ .y = 2019, .m = 12, .d = 31, .dflt = date.min, .exp = R.inRange, .val = 1034110 }, RangeCheckElem{ .y = 2019, .m = 12, .d = 32, .dflt = date.min, .exp = R.outOfRange, .val = undefined }, RangeCheckElem{ .y = 2019, .m = 13, .d = 1, .dflt = date.min, .exp = R.outOfRange, .val = undefined }, RangeCheckElem{ .y = 2020, .m = 2, .d = 29, .dflt = date.min, .exp = R.inRange, .val = 1034300 }, RangeCheckElem{ .y = 2020, .m = 2, .d = 30, .dflt = date.min, .exp = R.inRange, .val = 1034301 }, RangeCheckElem{ .y = 2020, .m = 2, .d = 31, .dflt = date.min, .exp = R.inRange, .val = 1034302 }, RangeCheckElem{ .y = 2020, .m = 2, .d = 32, .dflt = date.min, .exp = R.outOfRange, .val = undefined }, RangeCheckElem{ .y = date.maxYear, .m = 1, .d = 1, .dflt = date.min, .exp = R.inRange, .val = 2147483136 }, RangeCheckElem{ .y = date.maxYear, .m = 12, .d = 31, .dflt = date.min, .exp = R.inRange, .val = 2147483518 }, RangeCheckElem{ .y = date.maxYear, .m = 12, .d = 32, .dflt = date.min, .exp = R.outOfRange, .val = undefined }, RangeCheckElem{ .y = date.maxYear + 1, .m = 1, .d = 1, .dflt = date.min, .exp = R.outOfRange, .val = undefined }, RangeCheckElem{ .y = date.minYear, .m = 1, .d = 1, .dflt = date.max, .exp = R.inRange, .val = -2147483648 }, RangeCheckElem{ .y = date.minYear - 1, .m = 12, .d = 31, .dflt = date.max, .exp = R.outOfRange, .val = undefined }, }; var my_date = date.min; var count: usize = 0; for (rangeCheckTable) |elem| { my_date = date.FromYmd(elem.y, elem.m, elem.d) catch elem.dflt; T.expectEqual(elem.exp, switch (my_date.compare(elem.dflt) == 0) { false => R.inRange, true => R.outOfRange, }); if (elem.exp == R.inRange) { T.expectEqual(elem.val, @bitCast(i32, my_date)); } count += 1; } } test "Calendrical Calculations test points" { const rata_die_offset: i32 = 719163; const unix_to_julian_bias: f64 = 2440587.5; const CalCalElem = struct { rd: i32, dw: date.Weekday, jd: f64, gy: i32, gm: i32, gd: i32, }; // The set of reference points from Calendrical Calculations, Appendix C, Table 1 (part 1) const appendix_c = []CalCalElem{ CalCalElem{ .rd = -214193, .dw = date.Weekday.Sunday, .jd = 1507231.5, .gy = -586, .gm = 7, .gd = 24 }, CalCalElem{ .rd = -61387, .dw = date.Weekday.Wednesday, .jd = 1660037.5, .gy = -168, .gm = 12, .gd = 5 }, CalCalElem{ .rd = 25469, .dw = date.Weekday.Wednesday, .jd = 1746893.5, .gy = 70, .gm = 9, .gd = 24 }, CalCalElem{ .rd = 49217, .dw = date.Weekday.Sunday, .jd = 1770641.5, .gy = 135, .gm = 10, .gd = 2 }, CalCalElem{ .rd = 171307, .dw = date.Weekday.Wednesday, .jd = 1892731.5, .gy = 470, .gm = 1, .gd = 8 }, CalCalElem{ .rd = 210155, .dw = date.Weekday.Monday, .jd = 1931579.5, .gy = 576, .gm = 5, .gd = 20 }, CalCalElem{ .rd = 253427, .dw = date.Weekday.Saturday, .jd = 1974851.5, .gy = 694, .gm = 11, .gd = 10 }, CalCalElem{ .rd = 369740, .dw = date.Weekday.Sunday, .jd = 2091164.5, .gy = 1013, .gm = 4, .gd = 25 }, CalCalElem{ .rd = 400085, .dw = date.Weekday.Sunday, .jd = 2121509.5, .gy = 1096, .gm = 5, .gd = 24 }, CalCalElem{ .rd = 434355, .dw = date.Weekday.Friday, .jd = 2155779.5, .gy = 1190, .gm = 3, .gd = 23 }, CalCalElem{ .rd = 452605, .dw = date.Weekday.Saturday, .jd = 2174029.5, .gy = 1240, .gm = 3, .gd = 10 }, CalCalElem{ .rd = 470160, .dw = date.Weekday.Friday, .jd = 2191584.5, .gy = 1288, .gm = 4, .gd = 2 }, CalCalElem{ .rd = 473837, .dw = date.Weekday.Sunday, .jd = 2195261.5, .gy = 1298, .gm = 4, .gd = 27 }, CalCalElem{ .rd = 507850, .dw = date.Weekday.Sunday, .jd = 2229274.5, .gy = 1391, .gm = 6, .gd = 12 }, CalCalElem{ .rd = 524156, .dw = date.Weekday.Wednesday, .jd = 2245580.5, .gy = 1436, .gm = 2, .gd = 3 }, CalCalElem{ .rd = 544676, .dw = date.Weekday.Saturday, .jd = 2266100.5, .gy = 1492, .gm = 4, .gd = 9 }, CalCalElem{ .rd = 567118, .dw = date.Weekday.Saturday, .jd = 2288542.5, .gy = 1553, .gm = 9, .gd = 19 }, CalCalElem{ .rd = 569477, .dw = date.Weekday.Saturday, .jd = 2290901.5, .gy = 1560, .gm = 3, .gd = 5 }, CalCalElem{ .rd = 601716, .dw = date.Weekday.Wednesday, .jd = 2323140.5, .gy = 1648, .gm = 6, .gd = 10 }, CalCalElem{ .rd = 613424, .dw = date.Weekday.Sunday, .jd = 2334848.5, .gy = 1680, .gm = 6, .gd = 30 }, CalCalElem{ .rd = 626596, .dw = date.Weekday.Friday, .jd = 2348020.5, .gy = 1716, .gm = 7, .gd = 24 }, CalCalElem{ .rd = 645554, .dw = date.Weekday.Sunday, .jd = 2366978.5, .gy = 1768, .gm = 6, .gd = 19 }, CalCalElem{ .rd = 664224, .dw = date.Weekday.Monday, .jd = 2385648.5, .gy = 1819, .gm = 8, .gd = 2 }, CalCalElem{ .rd = 671401, .dw = date.Weekday.Wednesday, .jd = 2392825.5, .gy = 1839, .gm = 3, .gd = 27 }, CalCalElem{ .rd = 694799, .dw = date.Weekday.Sunday, .jd = 2416223.5, .gy = 1903, .gm = 4, .gd = 19 }, CalCalElem{ .rd = 704424, .dw = date.Weekday.Sunday, .jd = 2425848.5, .gy = 1929, .gm = 8, .gd = 25 }, CalCalElem{ .rd = 708842, .dw = date.Weekday.Monday, .jd = 2430266.5, .gy = 1941, .gm = 9, .gd = 29 }, CalCalElem{ .rd = 709409, .dw = date.Weekday.Monday, .jd = 2430833.5, .gy = 1943, .gm = 4, .gd = 19 }, CalCalElem{ .rd = 709580, .dw = date.Weekday.Thursday, .jd = 2431004.5, .gy = 1943, .gm = 10, .gd = 7 }, CalCalElem{ .rd = 727274, .dw = date.Weekday.Tuesday, .jd = 2448698.5, .gy = 1992, .gm = 3, .gd = 17 }, CalCalElem{ .rd = 728714, .dw = date.Weekday.Sunday, .jd = 2450138.5, .gy = 1996, .gm = 2, .gd = 25 }, CalCalElem{ .rd = 744313, .dw = date.Weekday.Wednesday, .jd = 2465737.5, .gy = 2038, .gm = 11, .gd = 10 }, CalCalElem{ .rd = 764652, .dw = date.Weekday.Sunday, .jd = 2486076.5, .gy = 2094, .gm = 7, .gd = 18 }, }; for (appendix_c) |elem| { const d = try date.FromYmd(elem.gy, elem.gm, elem.gd); const dc: i32 = d.code(); T.expectEqual(elem.rd, dc + rata_die_offset); T.expectEqual(elem.dw, date.weekday(dc)); const f = date.FromCode(dc); T.expectEqual(elem.gy, f.year()); T.expectEqual(elem.gm, f.month()); T.expectEqual(elem.gd, f.day()); const jd: f64 = unix_to_julian_bias + @intToFloat(f64, dc); T.expectEqual(elem.jd, jd); } } test "cardinal dates" { const CdElem = struct { nth: date.Nth, wkdy: date.Weekday, y: i32, m: i32, exp: i32, }; const cd_data = []CdElem{ CdElem{ .nth = date.Nth.First, .wkdy = date.Weekday.Monday, .y = 2019, .m = 4, .exp = 1 }, CdElem{ .nth = date.Nth.Second, .wkdy = date.Weekday.Friday, .y = 2019, .m = 9, .exp = 13 }, CdElem{ .nth = date.Nth.Last, .wkdy = date.Weekday.Tuesday, .y = 1992, .m = 7, .exp = 28 }, }; for (cd_data) |elem| { const d = try date.FromCardinal(elem.nth, elem.wkdy, elem.y, elem.m); T.expectEqual(elem.exp, d.day()); } }
src/gregorianDate_test.zig
const std = @import("std"); const ztBuild = @import("ZT/build.zig"); const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; const Pkg = std.build.Pkg; pub const EngineConfig = struct { /// Path to where didot is relative to the game's build.zig file. Must end with a slash or be empty. prefix: []const u8 = "", windowModule: []const u8 = "didot-glfw", physicsModule: []const u8 = "didot-ode", graphicsModule: []const u8 = "didot-opengl", /// Whether or not to automatically set the recommended window module depending on the target platform. /// Currently, didot-x11 will be used for Linux and didot-glfw for other platforms. /// Temporarily disabled! autoWindow: bool = true, /// Whether or not to include the physics module usePhysics: bool = false, embedAssets: bool = false, }; pub fn addEngineToExe(b: *std.build.Builder, step: *LibExeObjStep, target: std.zig.CrossTarget, comptime config: EngineConfig) !void { const prefix = config.prefix; const zalgebra = Pkg { .name = "zalgebra", .path = std.build.FileSource.relative(prefix ++ "zalgebra/src/main.zig") }; const image = Pkg { .name = "didot-image", .path = std.build.FileSource.relative(prefix ++ "didot-image/image.zig") }; const windowModule = comptime blk: { // if (config.autoWindow) { // const target = step.target.toTarget().os.tag; // break :blk switch (target) { // .linux => "didot-x11", // else => "didot-glfw" // }; // } else { break :blk config.windowModule; // } }; if (!comptime std.mem.eql(u8, windowModule, "didot-glfw")) { @compileError("windowing module must be didot-glfw"); } else if (!comptime std.mem.eql(u8, config.graphicsModule, "didot-opengl")) { @compileError("graphics module must be OpenGL"); } else if (!comptime std.mem.eql(u8, config.physicsModule, "didot-ode")) { @compileError("graphics module must be ODE"); } //const windowPath = windowModule ++ "/build.zig"; const window = (try @import("didot-glfw/build.zig").build(step, config)) orelse Pkg { .name = "didot-window", .path = std.build.FileSource.relative(prefix ++ windowModule ++ "/window.zig"), .dependencies = &[_]Pkg{zalgebra,ztBuild.glfwPkg,ztBuild.glPkg} }; const graphics = Pkg { .name = "didot-graphics", .path = std.build.FileSource.relative(prefix ++ config.graphicsModule ++ "/main.zig"), .dependencies = &[_]Pkg{window,image,zalgebra,ztBuild.glPkg} }; try @import("didot-opengl/build.zig").build(step); const models = Pkg { .name = "didot-models", .path = std.build.FileSource.relative(prefix ++ "didot-models/models.zig"), .dependencies = &[_]Pkg{zalgebra,graphics} }; if (config.embedAssets) { try createBundle(step); } const objects = Pkg { .name = "didot-objects", .path = std.build.FileSource.relative(prefix ++ "didot-objects/main.zig"), .dependencies = &[_]Pkg{zalgebra,graphics,models,image} }; //@@@ const physics = Pkg { //@@@ .name = "didot-physics", //@@@ .path = std.build.FileSource.relative(prefix ++ config.physicsModule ++ "/physics.zig"), //@@@ .dependencies = &[_]Pkg{objects, zalgebra} //@@@ }; //@@@ if (config.usePhysics) { //@@@ try @import("didot-ode/build.zig").build(step); //@@@ step.addPackage(physics); //@@@ } const app = Pkg { .name = "didot-app", .path = std.build.FileSource.relative(prefix ++ "didot-app/app.zig"), .dependencies = &[_]Pkg{objects,graphics,ztBuild.glPkg} }; ztBuild.link(b, step, target); step.addPackage(zalgebra); step.addPackage(image); step.addPackage(window); step.addPackage(graphics); step.addPackage(objects); step.addPackage(models); step.addPackage(app); } fn createBundle(step: *LibExeObjStep) !void { const b = step.builder; const allocator = b.allocator; var dir = try std.fs.openDirAbsolute(b.build_root, .{}); defer dir.close(); var cacheDir = try dir.openDir(b.cache_root, .{}); defer cacheDir.close(); (try cacheDir.makeOpenPath("assets", .{})).close(); // mkdir "assets" const fullName = try std.mem.concat(allocator, u8, &[_][]const u8 {"assets/", step.name, ".bundle"}); const cacheFile = try cacheDir.createFile(fullName, .{ .truncate = true }); defer cacheFile.close(); allocator.free(fullName); // const writer = cacheFile.writer(); const dirPath = try dir.realpathAlloc(allocator, "assets"); defer allocator.free(dirPath); var walkedDir = try std.fs.openDirAbsolute(dirPath, .{ .iterate = true }); defer walkedDir.close(); var count: u64 = 0; // Count the number of items { var walker = try walkedDir.walk(allocator); defer walker.deinit(); while ((try walker.next()) != null) { count += 1; } } // var walker = try walkedDir.walk(allocator); // defer walker.deinit(); // try writer.writeByte(0); // no compression // try writer.writeIntLittle(u64, count); // while (try walker.next()) |entry| { // if (entry.kind == .File) { // const path = entry.path[dirPath.len+1..]; // const file = try std.fs.openFileAbsolute(entry.path, .{}); // defer file.close(); // const data = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); // defer allocator.free(data); // try writer.writeIntLittle(u32, @intCast(u32, path.len)); // try writer.writeIntLittle(u32, @intCast(u32, data.len)); // try writer.writeAll(path); // try writer.writeAll(data); // } // } } pub fn build(b: *Builder) !void { var target = b.standardTargetOptions(.{}); var mode = b.standardReleaseOptions(); const stripExample = b.option(bool, "strip-example", "Attempt to minify examples by stripping them and changing release mode.") orelse false; const wasm = b.option(bool, "wasm-target", "Compile the code to run on WASM backend.") orelse false; if (@hasField(LibExeObjStep, "emit_docs")) { const otest = b.addTest("didot.zig"); // otest.emit_docs = true; //otest.emit_bin = false; try addEngineToExe(b, otest, target, .{ .autoWindow = false, .usePhysics = false //@@@ true }); const test_step = b.step("doc", "Test and generate documentation for Didot"); test_step.dependOn(&otest.step); } else { const no_doc = b.addSystemCommand(&[_][]const u8{"echo", "Please build with the latest version of Zig to be able to emit documentation."}); const no_doc_step = b.step("doc", "Test and generate documentation for Didot"); no_doc_step.dependOn(&no_doc.step); } const examples = [_][2][]const u8 { //@@@ .{"test-portal", "examples/test-portal/example-scene.zig"}, .{"kart-and-cubes", "examples/kart-and-cubes/example-scene.zig"}, //@@@ .{"planet-test", "examples/planet-test/example-scene.zig"} }; const engineConfig = EngineConfig { .windowModule = "didot-glfw", .graphicsModule = "didot-opengl", .autoWindow = false, .usePhysics = true, .embedAssets = true }; if (wasm) { target = try std.zig.CrossTarget.parse(.{ .arch_os_abi = "wasm64-freestanding-gnu" }); } inline for (examples) |example| { const name = example[0]; const path = example[1]; const exe = b.addExecutable(name, path); exe.setTarget(target); exe.setBuildMode(if (stripExample) std.builtin.Mode.ReleaseSmall else mode); try addEngineToExe(b, exe, target, engineConfig); exe.single_threaded = stripExample; exe.strip = stripExample; exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(&exe.install_step.?.step); const run_step = b.step(name, "Test Didot with the " ++ name ++ " example"); run_step.dependOn(&run_cmd.step); } }
build.zig
const util = @import("../sdf_util.zig"); pub const info: util.SdfInfo = .{ .name = "Transform", .data_size = @sizeOf(Data), .function_definition = "", .enter_command_fn = enterCommand, .exit_command_fn = exitCommand, .sphere_bound_fn = sphereBound, }; pub const Data = struct { rotation: util.math.vec3, translation: util.math.vec3, transform_matrix: util.math.mat4x4, }; pub fn initZero(buffer: *[]u8) void { const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); data.rotation = util.math.Vec3.zeros(); data.translation = util.math.Vec3.zeros(); data.transform_matrix = util.math.Mat4x4.identity(); } pub fn translate(buffer: *[]u8, v: util.math.vec3) void { const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); data.translation += v; } pub fn updateMatrix(buffer: *[]u8) void { const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); data.transform_matrix = util.math.Mat4x4.identity(); util.math.Transform.rotateX(&data.transform_matrix, -data.rotation[0]); util.math.Transform.rotateY(&data.transform_matrix, -data.rotation[1]); util.math.Transform.rotateZ(&data.transform_matrix, -data.rotation[2]); util.math.Transform.translate(&data.transform_matrix, -data.translation); } fn enterCommand(ctxt: *util.IterationContext, iter: usize, mat_offset: usize, buffer: *[]u8) []const u8 { _ = mat_offset; const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); const next_point: []const u8 = util.std.fmt.allocPrint(ctxt.allocator, "p{d}", .{iter}) catch unreachable; const temp: []const u8 = util.std.fmt.allocPrint(ctxt.allocator, "mat4({d:.5},{d:.5},{d:.5},{d:.5}, {d:.5},{d:.5},{d:.5},{d:.5}, {d:.5},{d:.5},{d:.5},{d:.5}, {d:.5},{d:.5},{d:.5},{d:.5})", .{ data.transform_matrix[0][0], data.transform_matrix[0][1], data.transform_matrix[0][2], data.transform_matrix[0][3], data.transform_matrix[1][0], data.transform_matrix[1][1], data.transform_matrix[1][2], data.transform_matrix[1][3], data.transform_matrix[2][0], data.transform_matrix[2][1], data.transform_matrix[2][2], data.transform_matrix[2][3], data.transform_matrix[3][0], data.transform_matrix[3][1], data.transform_matrix[3][2], data.transform_matrix[3][3], }) catch unreachable; const format: []const u8 = "vec3 {s} = ({s} * vec4({s}, 1.)).xyz;"; const res: []const u8 = util.std.fmt.allocPrint(ctxt.allocator, format, .{ next_point, temp, ctxt.cur_point_name, }) catch unreachable; ctxt.pushPointName(next_point); ctxt.allocator.free(temp); return res; } fn exitCommand(ctxt: *util.IterationContext, iter: usize, buffer: *[]u8) []const u8 { _ = iter; _ = buffer; ctxt.popPointName(); return util.std.fmt.allocPrint(ctxt.allocator, "", .{}) catch unreachable; } fn sphereBound(buffer: *[]u8, bound: *util.math.sphereBound, children: []util.math.sphereBound) void { const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); bound.* = children[0]; bound.*.pos += data.translation; }
src/sdf/modifiers/transform.zig
const std = @import("std"); const generate = @import("generator.zig").generate; const path = std.fs.path; const Builder = std.build.Builder; const Step = std.build.Step; /// build.zig integration for Vulkan binding generation. This step can be used to generate /// Vulkan bindings at compiletime from vk.xml, by providing the path to vk.xml and the output /// path relative to zig-cache. The final package can then be obtained by `package()`, the result /// of which can be added to the project using `std.build.Builder.addPackage`. pub const GenerateStep = struct { step: Step, builder: *Builder, /// The path to vk.xml spec_path: []const u8, /// The package representing the generated bindings. The generated bindings will be placed /// in `package.path`. When using this step, this member should be passed to /// `std.build.Builder.addPackage`, which causes the bindings to become available under the /// name `vulkan`. package: std.build.Pkg, output_file: std.build.GeneratedFile, /// Initialize a Vulkan generation step, for `builder`. `spec_path` is the path to /// vk.xml, relative to the project root. The generated bindings will be placed at /// `out_path`, which is relative to the zig-cache directory. pub fn init(builder: *Builder, spec_path: []const u8, out_path: []const u8) *GenerateStep { const self = builder.allocator.create(GenerateStep) catch unreachable; const full_out_path = path.join(builder.allocator, &[_][]const u8{ builder.build_root, builder.cache_root, out_path, }) catch unreachable; self.* = .{ .step = Step.init(.custom, "vulkan-generate", builder.allocator, make), .builder = builder, .spec_path = spec_path, .package = .{ .name = "vulkan", .source = .{ .generated = &self.output_file }, .dependencies = null, }, .output_file = .{ .step = &self.step, .path = full_out_path, }, }; return self; } /// Initialize a Vulkan generation step for `builder`, by extracting vk.xml from the LunarG installation /// root. Typically, the location of the LunarG SDK root can be retrieved by querying for the VULKAN_SDK /// environment variable, set by activating the environment setup script located in the SDK root. /// `builder` and `out_path` are used in the same manner as `init`. pub fn initFromSdk(builder: *Builder, sdk_path: []const u8, out_path: []const u8) *GenerateStep { const spec_path = std.fs.path.join( builder.allocator, &[_][]const u8{ sdk_path, "share/vulkan/registry/vk.xml" }, ) catch unreachable; return init(builder, spec_path, out_path); } /// Internal build function. This reads `vk.xml`, and passes it to `generate`, which then generates /// the final bindings. The resulting generated bindings are not formatted, which is why an ArrayList /// writer is passed instead of a file writer. This is then formatted into standard formatting /// by parsing it and rendering with `std.zig.parse` and `std.zig.render` respectively. fn make(step: *Step) !void { const self = @fieldParentPtr(GenerateStep, "step", step); const cwd = std.fs.cwd(); const spec = try cwd.readFileAlloc(self.builder.allocator, self.spec_path, std.math.maxInt(usize)); var out_buffer = std.ArrayList(u8).init(self.builder.allocator); try generate(self.builder.allocator, spec, out_buffer.writer()); try out_buffer.append(0); const src = out_buffer.items[0 .. out_buffer.items.len - 1 :0]; const tree = try std.zig.parse(self.builder.allocator, src); std.debug.assert(tree.errors.len == 0); // If this triggers, vulkan-zig produced invalid code. var formatted = try tree.render(self.builder.allocator); const dir = path.dirname(self.output_file.path.?).?; try cwd.makePath(dir); try cwd.writeFile(self.output_file.path.?, formatted); } };
generator/vulkan/build_integration.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Vec2 = tools.Vec2; pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const param: struct { stride: usize, width: usize, height: usize, map: []const u8, } = blk: { const width = std.mem.indexOfScalar(u8, input_text, '\n').?; const stride = width + 1; const height = (input_text.len + 1) / (width + 1); // std.debug.print("{}\n", .{input}); break :blk .{ .stride = stride, .width = width, .height = height, .map = input_text, }; }; const ans1 = ans: { const dim1 = 24; const dim2 = dim1 * dim1; const center_offset = (dim1 / 2) * dim2 + (dim1 / 2) * dim1 + (dim1 / 2); const cube = try allocator.alloc(u8, dim2 * dim1); defer allocator.free(cube); std.mem.set(u8, cube, '.'); for (param.map) |v, i| { const y = i / param.stride; const x = i % param.stride; if (x > param.width or y > param.height) continue; const x0 = @intCast(i32, x) - @intCast(i32, param.width / 2); const y0 = @intCast(i32, y) - @intCast(i32, param.height / 2); cube[@intCast(usize, center_offset + y0 * dim1 + x0)] = v; } const neighbours = comptime blk: { var o: [26]isize = undefined; var nb: usize = 0; var z: isize = -1; while (z <= 1) : (z += 1) { var y: isize = -1; while (y <= 1) : (y += 1) { var x: isize = -1; while (x <= 1) : (x += 1) { if (x == 0 and y == 0 and z == 0) continue; o[nb] = dim2 * z + dim1 * y + x; nb += 1; } } } break :blk o; }; // avec deux plans d'espace supplΓ©mentaire pour que Γ§a wrappe et eviter les frontieres const cube2 = try allocator.alloc(u8, dim2 * dim1 + dim2 * 2 + dim1 * 2 + 2); defer allocator.free(cube2); std.mem.set(u8, cube2, '.'); const padding = dim2 + dim1 + 1; var gen: usize = 0; while (gen < 6) : (gen += 1) { std.mem.copy(u8, cube2[padding .. padding + cube.len], cube); for (cube) |*v, i| { var n: usize = 0; inline for (neighbours) |o| { if (cube2[@intCast(usize, @intCast(isize, padding + i) + o)] == '#') n += 1; } if (v.* == '#') { v.* = if (n == 2 or n == 3) '#' else '.'; } else { v.* = if (n == 3) '#' else '.'; } } } var count: usize = 0; for (cube) |v| { if (v == '#') count += 1; } break :ans count; }; const ans2 = ans: { const dim1 = 22; const dim2 = dim1 * dim1; const dim3 = dim2 * dim1; const center_offset = (dim1 / 2) * dim3 + (dim1 / 2) * dim2 + (dim1 / 2) * dim1 + (dim1 / 2) * 1; const cube = try allocator.alloc(u8, dim3 * dim1); defer allocator.free(cube); std.mem.set(u8, cube, '.'); for (param.map) |v, i| { const y = i / param.stride; const x = i % param.stride; if (x > param.width or y > param.height) continue; const x0 = @intCast(i32, x) - @intCast(i32, param.width / 2); const y0 = @intCast(i32, y) - @intCast(i32, param.height / 2); cube[@intCast(usize, center_offset + y0 * dim1 + x0)] = v; } const neighbours = comptime blk: { var o: [80]isize = undefined; var nb: usize = 0; var w: isize = -1; while (w <= 1) : (w += 1) { var z: isize = -1; while (z <= 1) : (z += 1) { var y: isize = -1; while (y <= 1) : (y += 1) { var x: isize = -1; while (x <= 1) : (x += 1) { if (x == 0 and y == 0 and z == 0 and w == 0) continue; o[nb] = dim3 * w + dim2 * z + dim1 * y + x; nb += 1; } } } } break :blk o; }; // avec deux hyper-plans d'espace supplΓ©mentaire pour que Γ§a wrappe et eviter les frontieres const cube2 = try allocator.alloc(u8, dim2 * dim2 + dim3 * 2 + dim2 * 2 + dim1 * 2 + 2); defer allocator.free(cube2); std.mem.set(u8, cube2, '.'); const padding = dim3 + dim2 + dim1 + 1; var gen: usize = 0; while (gen < 6) : (gen += 1) { std.mem.copy(u8, cube2[padding .. padding + cube.len], cube); for (cube) |*v, i| { var n: usize = 0; inline for (neighbours) |o| { if (cube2[@intCast(usize, @intCast(isize, padding + i) + o)] == '#') n += 1; } if (v.* == '#') { v.* = if (n == 2 or n == 3) '#' else '.'; } else { v.* = if (n == 3) '#' else '.'; } } } var count: usize = 0; for (cube) |v| { if (v == '#') count += 1; } break :ans count; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2020/input_day17.txt", run);
2020/day17.zig
const std = @import("std"); const assert = std.debug.assert; const spec = @import("spec.zig"); pub const Type = extern union { tag_if_small_enough: Tag, ptr_otherwise: *Payload, /// A reference to another SPIR-V type. pub const Ref = usize; pub fn initTag(comptime small_tag: Tag) Type { comptime assert(@enumToInt(small_tag) < Tag.no_payload_count); return .{ .tag_if_small_enough = small_tag }; } pub fn initPayload(pl: *Payload) Type { assert(@enumToInt(pl.tag) >= Tag.no_payload_count); return .{ .ptr_otherwise = pl }; } pub fn tag(self: Type) Tag { if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) { return self.tag_if_small_enough; } else { return self.ptr_otherwise.tag; } } pub fn castTag(self: Type, comptime t: Tag) ?*t.Type() { if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) return null; if (self.ptr_otherwise.tag == t) return self.payload(t); return null; } /// Access the payload of a type directly. pub fn payload(self: Type, comptime t: Tag) *t.Type() { assert(self.tag() == t); return @fieldParentPtr(t.Type(), "base", self.ptr_otherwise); } /// Perform a shallow equality test, comparing two types while assuming that any child types /// are equal only if their references are equal. pub fn eqlShallow(a: Type, b: Type) bool { if (a.tag_if_small_enough == b.tag_if_small_enough) return true; const tag_a = a.tag(); const tag_b = b.tag(); if (tag_a != tag_b) return false; inline for (@typeInfo(Tag).Enum.fields) |field| { const t = @field(Tag, field.name); if (t == tag_a) { return eqlPayloads(t, a, b); } } unreachable; } /// Compare the payload of two compatible tags, given that we already know the tag of both types. fn eqlPayloads(comptime t: Tag, a: Type, b: Type) bool { switch (t) { .void, .bool, .sampler, .event, .device_event, .reserve_id, .queue, .pipe_storage, .named_barrier, => return true, .int, .float, .vector, .matrix, .sampled_image, .array, .runtime_array, .@"opaque", .pointer, .pipe, .image, => return std.meta.eql(a.payload(t).*, b.payload(t).*), .@"struct" => { const struct_a = a.payload(.@"struct"); const struct_b = b.payload(.@"struct"); if (struct_a.members.len != struct_b.members.len) return false; for (struct_a.members) |mem_a, i| { if (!std.meta.eql(mem_a, struct_b.members[i])) return false; } return true; }, .@"function" => { const fn_a = a.payload(.function); const fn_b = b.payload(.function); if (fn_a.return_type != fn_b.return_type) return false; return std.mem.eql(Ref, fn_a.parameters, fn_b.parameters); }, } } /// Perform a shallow hash, which hashes the reference value of child types instead of recursing. pub fn hashShallow(self: Type) u64 { var hasher = std.hash.Wyhash.init(0); const t = self.tag(); std.hash.autoHash(&hasher, t); inline for (@typeInfo(Tag).Enum.fields) |field| { if (@field(Tag, field.name) == t) { switch (@field(Tag, field.name)) { .void, .bool, .sampler, .event, .device_event, .reserve_id, .queue, .pipe_storage, .named_barrier, => {}, else => self.hashPayload(@field(Tag, field.name), &hasher), } } } return hasher.final(); } /// Perform a shallow hash, given that we know the tag of the field ahead of time. fn hashPayload(self: Type, comptime t: Tag, hasher: *std.hash.Wyhash) void { const fields = @typeInfo(t.Type()).Struct.fields; const pl = self.payload(t); comptime assert(std.mem.eql(u8, fields[0].name, "base")); inline for (fields[1..]) |field| { // Skip the 'base' field. std.hash.autoHashStrat(hasher, @field(pl, field.name), .DeepRecursive); } } /// Hash context that hashes and compares types in a shallow fashion, useful for type caches. pub const ShallowHashContext32 = struct { pub fn hash(self: @This(), t: Type) u32 { _ = self; return @truncate(u32, t.hashShallow()); } pub fn eql(self: @This(), a: Type, b: Type, b_index: usize) bool { _ = self; _ = b_index; return a.eqlShallow(b); } }; /// Return the reference to any child type. Asserts the type is one of: /// - Vectors /// - Matrices /// - Images /// - SampledImages, /// - Arrays /// - RuntimeArrays /// - Pointers pub fn childType(self: Type) Ref { return switch (self.tag()) { .vector => self.payload(.vector).component_type, .matrix => self.payload(.matrix).column_type, .image => self.payload(.image).sampled_type, .sampled_image => self.payload(.sampled_image).image_type, .array => self.payload(.array).element_type, .runtime_array => self.payload(.runtime_array).element_type, .pointer => self.payload(.pointer).child_type, else => unreachable, }; } pub const Tag = enum(usize) { void, bool, sampler, event, device_event, reserve_id, queue, pipe_storage, named_barrier, // After this, the tag requires a payload. int, float, vector, matrix, image, sampled_image, array, runtime_array, @"struct", @"opaque", pointer, function, pipe, pub const last_no_payload_tag = Tag.named_barrier; pub const no_payload_count = @enumToInt(last_no_payload_tag) + 1; pub fn Type(comptime t: Tag) type { return switch (t) { .void, .bool, .sampler, .event, .device_event, .reserve_id, .queue, .pipe_storage, .named_barrier => @compileError("Type Tag " ++ @tagName(t) ++ " has no payload"), .int => Payload.Int, .float => Payload.Float, .vector => Payload.Vector, .matrix => Payload.Matrix, .image => Payload.Image, .sampled_image => Payload.SampledImage, .array => Payload.Array, .runtime_array => Payload.RuntimeArray, .@"struct" => Payload.Struct, .@"opaque" => Payload.Opaque, .pointer => Payload.Pointer, .function => Payload.Function, .pipe => Payload.Pipe, }; } }; pub const Payload = struct { tag: Tag, pub const Int = struct { base: Payload = .{ .tag = .int }, width: u32, signedness: std.builtin.Signedness, }; pub const Float = struct { base: Payload = .{ .tag = .float }, width: u32, }; pub const Vector = struct { base: Payload = .{ .tag = .vector }, component_type: Ref, component_count: u32, }; pub const Matrix = struct { base: Payload = .{ .tag = .matrix }, column_type: Ref, column_count: u32, }; pub const Image = struct { base: Payload = .{ .tag = .image }, sampled_type: Ref, dim: spec.Dim, depth: enum(u2) { no = 0, yes = 1, maybe = 2, }, arrayed: bool, multisampled: bool, sampled: enum(u2) { known_at_runtime = 0, with_sampler = 1, without_sampler = 2, }, format: spec.ImageFormat, access_qualifier: ?spec.AccessQualifier, }; pub const SampledImage = struct { base: Payload = .{ .tag = .sampled_image }, image_type: Ref, }; pub const Array = struct { base: Payload = .{ .tag = .array }, element_type: Ref, /// Note: Must be emitted as constant, not as literal! length: u32, /// Type has the 'ArrayStride' decoration. /// If zero, no stride is present. array_stride: u32, }; pub const RuntimeArray = struct { base: Payload = .{ .tag = .runtime_array }, element_type: Ref, /// Type has the 'ArrayStride' decoration. /// If zero, no stride is present. array_stride: u32, }; pub const Struct = struct { base: Payload = .{ .tag = .@"struct" }, members: []Member, decorations: StructDecorations, /// Extra information for decorations, packed for efficiency. Fields are stored sequentially by /// order of the `members` slice and `MemberDecorations` struct. member_decoration_extra: []u32, pub const Member = struct { ty: Ref, offset: u32, decorations: MemberDecorations, }; pub const StructDecorations = packed struct { /// Type has the 'Block' decoration. block: bool, /// Type has the 'BufferBlock' decoration. buffer_block: bool, /// Type has the 'GLSLShared' decoration. glsl_shared: bool, /// Type has the 'GLSLPacked' decoration. glsl_packed: bool, /// Type has the 'CPacked' decoration. c_packed: bool, }; pub const MemberDecorations = packed struct { /// Matrix layout for (arrays of) matrices. If this field is not .none, /// then there is also an extra field containing the matrix stride corresponding /// to the 'MatrixStride' decoration. matrix_layout: enum(u2) { /// Member has the 'RowMajor' decoration. The member type /// must be a matrix or an array of matrices. row_major, /// Member has the 'ColMajor' decoration. The member type /// must be a matrix or an array of matrices. col_major, /// Member is not a matrix or array of matrices. none, }, // Regular decorations, these do not imply extra fields. /// Member has the 'NoPerspective' decoration. no_perspective: bool, /// Member has the 'Flat' decoration. flat: bool, /// Member has the 'Patch' decoration. patch: bool, /// Member has the 'Centroid' decoration. centroid: bool, /// Member has the 'Sample' decoration. sample: bool, /// Member has the 'Invariant' decoration. /// Note: requires parent struct to have 'Block'. invariant: bool, /// Member has the 'Volatile' decoration. @"volatile": bool, /// Member has the 'Coherent' decoration. coherent: bool, /// Member has the 'NonWritable' decoration. non_writable: bool, /// Member has the 'NonReadable' decoration. non_readable: bool, // The following decorations all imply extra field(s). /// Member has the 'BuiltIn' decoration. /// This decoration has an extra field of type `spec.BuiltIn`. /// Note: If any member of a struct has the BuiltIn decoration, all members must have one. /// Note: Each builtin may only be reachable once for a particular entry point. /// Note: The member type may be constrained by a particular built-in, defined in the client API specification. builtin: bool, /// Member has the 'Stream' decoration. /// This member has an extra field of type `u32`. stream: bool, /// Member has the 'Location' decoration. /// This member has an extra field of type `u32`. location: bool, /// Member has the 'Component' decoration. /// This member has an extra field of type `u32`. component: bool, /// Member has the 'XfbBuffer' decoration. /// This member has an extra field of type `u32`. xfb_buffer: bool, /// Member has the 'XfbStride' decoration. /// This member has an extra field of type `u32`. xfb_stride: bool, /// Member has the 'UserSemantic' decoration. /// This member has an extra field of type `[]u8`, which is encoded /// by an `u32` containing the number of chars exactly, and then the string padded to /// a multiple of 4 bytes with zeroes. user_semantic: bool, }; }; pub const Opaque = struct { base: Payload = .{ .tag = .@"opaque" }, name: []u8, }; pub const Pointer = struct { base: Payload = .{ .tag = .pointer }, storage_class: spec.StorageClass, child_type: Ref, /// Type has the 'ArrayStride' decoration. /// This is valid for pointers to elements of an array. /// If zero, no stride is present. array_stride: u32, /// Type has the 'Alignment' decoration. alignment: ?u32, /// Type has the 'MaxByteOffset' decoration. max_byte_offset: ?u32, }; pub const Function = struct { base: Payload = .{ .tag = .function }, return_type: Ref, parameters: []Ref, }; pub const Pipe = struct { base: Payload = .{ .tag = .pipe }, qualifier: spec.AccessQualifier, }; }; };
src/codegen/spirv/type.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const String = std.ArrayList(u8); const StringMap = std.StringHashMap(u8); const Bags = std.ArrayList([]const u8); const Backward = std.StringHashMap(Bags); const NBag = struct { n: usize, bag: []const u8 }; const NBags = std.ArrayList(NBag); const Forward = std.StringHashMap(NBags); fn parse(allocator: *Allocator, line: []const u8, backward: *Backward, forward: *Forward) !void { var iter = std.mem.tokenize(line, " "); var parent = String.init(allocator); try parent.appendSlice(iter.next().?); try parent.appendSlice(iter.next().?); _ = iter.next(); // bags _ = iter.next(); // contain var children = NBags.init(allocator); while (iter.next()) |num| { if (std.mem.eql(u8, num, "no")) { _ = iter.next(); // other _ = iter.next(); // bags } else { const n = try std.fmt.parseUnsigned(usize, num, 10); var child = String.init(allocator); try child.appendSlice(iter.next().?); try child.appendSlice(iter.next().?); _ = iter.next(); // bags try children.append(NBag{ .n = n, .bag = child.items }); var parents = backward.get(child.items) orelse Bags.init(allocator); try parents.append(parent.items); try backward.put(child.items, parents); } } try forward.put(parent.items, children); } fn countBackward(backward: *Backward, checked: *StringMap, bag: []const u8) Allocator.Error!usize { var n: usize = 0; if (backward.get(bag)) |parents| { for (parents.items) |parent| { if (checked.get(parent) == null) { n += 1; try checked.put(parent, 1); n += try countBackward(backward, checked, parent); } } } return n; } fn countForward(forward: *Forward, bag: []const u8) usize { var n: usize = 0; if (forward.get(bag)) |children| { for (children.items) |child| { n += child.n; n += child.n * countForward(forward, child.bag); } } return n; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; // Store each bag as a key in a HashMap with a list of parent bags var backward = std.StringHashMap(Bags).init(allocator); // Store each bag as a key in a HashMap with a list of children bags var forward = std.StringHashMap(NBags).init(allocator); var stdin = std.io.getStdIn().reader(); var in = std.io.bufferedReader(stdin).reader(); var buf: [256]u8 = undefined; while (try in.readUntilDelimiterOrEof(&buf, '\n')) |line| { try parse(allocator, line, &backward, &forward); } var checked = StringMap.init(allocator); const na = try countBackward(&backward, &checked, "shinygold"); std.debug.print("A) {d} bags can contain a shiny gold bag\n", .{na}); const nb = countForward(&forward, "shinygold"); std.debug.print("B) a shiny gold bag must contain {d} bags\n", .{nb}); }
2020/zig/src/7.zig
const script = @import("main.zig").script; const types = @import("types.zig"); const Atom = types.Atom; const AtomList = types.AtomList; const SyntaxErrors = types.SyntaxErrors; const parseFloat = @import("std").fmt.parseFloat; // I'd prefer this all to be in a function, but I couldn't figure out how to give the tokenize // function the size of the needed token-array without having an external/global variable for it // I guess I should do a double-pass? - read to count then make? pub const token_count = comptime countTokens(script); pub const tokens = comptime tokenize(script, token_count); pub const abstract_syntax_tree = try comptime parse(); pub fn countTokens(comptime buf: []const u8) usize { var num = 0; var last = ' '; for (buf) |char| { num += switch (char) { '(', ')' => 1, ' ', '\n' => 0, else => if (isSplitByte(last)) 1 else 0, }; last = char; } return num; } pub fn tokenize(comptime buf: []const u8, size: usize) [size][]const u8 { var token_array: [size][]const u8 = undefined; var index: usize = 0; var token_iter = TokenIterator{ .index = 0, .buf = buf }; while (token_iter.next()) |token| : (index += 1) { token_array[index] = token; } return token_array; } const TokenIterator = struct { buf: []const u8, index: usize, pub fn next(self: *TokenIterator) ?[]const u8 { // move to beginning of token while (self.index < self.buf.len and isSkipByte(self.buf[self.index])) : (self.index += 1) {} const start = self.index; if (start == self.buf.len) return null; if (self.buf[start] == '(' or self.buf[start] == ')') { self.index += 1; return self.buf[start .. start + 1]; } // move to end of token while (self.index < self.buf.len and !isSplitByte(self.buf[self.index])) : (self.index += 1) {} const end = self.index; return self.buf[start..end]; } }; fn isSkipByte(byte: u8) bool { return byte == ' ' or byte == '\n'; } fn isSplitByte(byte: u8) bool { @setEvalBranchQuota(1_000_000); // use this as needed to stop compiler quitting on the job! return byte == ' ' or byte == ')' or byte == '(' or byte == '\n'; } /// takes in the current index and accesses the globals 'token_count' and 'tokens'; ideally these /// would be in a struct or something.. but I wasn't sure how to do that with the recursion /// neither of these globals are (or probably can be) modified/altered fn parse() SyntaxErrors!AtomList { comptime var list = AtomList{}; comptime var index: comptime_int = 0; while (index < token_count) { comptime var atom_index = try comptime nextBlock(index); comptime var node = AtomList.Node{ .data = atom_index.atom }; if (index == 0) { list.prepend(&node); } else { list.first.?.findLast().insertAfter(&node); } index = atom_index.index; } return list; } fn nextBlock(comptime current_index: comptime_int) SyntaxErrors!AtomIndex { @setEvalBranchQuota(1_000_000); var index = current_index; if (index == token_count) return error.IndexEqualTokenCount; if (popToken(index)) |token_index| { // poptoken just increments a counter and returns a char const token = token_index.token; index = token_index.index; if (token[0] == '(') { // we're starting a new expression var list = AtomList{}; while (popToken(index)) |next_token_index| { const next_token = next_token_index.token; // extract the token index = next_token_index.index; // update the index if (next_token[0] == ')') break; // we've reached the end of a 'list' // index - 1 fixes an off-by-one error (I can't figure out why exactly) var next_atom_index = try nextBlock(index - 1); // recurse in case of other expressions index = next_atom_index.index; // update the index yet again after recursion var list_node = AtomList.Node{ .data = next_atom_index.atom }; if (list.len() >= 1) { list.first.?.findLast().insertAfter(&list_node); // front to back growth } else { list.prepend(&list_node); // if it's the first in the list we'll just add it } } return AtomIndex{ .atom = Atom{ .list = list }, .index = index }; // we got the expression } else if (token[0] == ')') { return error.FoundRParensInParse; // mismatched parens } else { return AtomIndex{ .atom = atomize(token), .index = index }; } } else { return error.EndOfTokenList; // we shouldn't reach end of tokens here } return error.ParsingUnreachable; // makes the comptime happy } /// somewhat eagerly increments counters fn popToken(index: usize) ?TokenIndex { return if (token_count == index) null else TokenIndex{ .index = index + 1, .token = tokens[index] }; } pub fn atomize(token: []const u8) Atom { return if (parseNumber(token)) |t| t else Atom{ .keyword = token }; } fn parseNumber(token: []const u8) ?Atom { return if (parseFloat(f64, token)) |t| Atom{ .number = t } else |err| null; } /// these seem like silly things - but I can't figure out how to return the index without them... pub const AtomIndex = struct { atom: Atom, index: comptime_int, }; pub const TokenIndex = struct { token: []const u8, index: comptime_int, };
parse.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const windows = std.os.windows; const WAVE_FORMAT_PCM = 0x01; const WHDR_INQUEUE = 0x10; const WAVE_MAPPER = 0xffffffff; const CALLBACK_NULL = 0x0; const HWAVEOUT = windows.HANDLE; const UINT_PTR = usize; const MMError = error{ Error, BadDeviceID, Allocated, InvalidHandle, NoDriver, NoMem, BadFormat, StillPlaying, Unprepared, Sync, }; const MMRESULT = extern enum(u32) { MMSYSERR_NOERROR = 0, MMSYSERR_ERROR = 1, MMSYSERR_BADDEVICEID = 2, MMSYSERR_ALLOCATED = 4, MMSYSERR_INVALIDHANDLE = 5, MMSYSERR_NODRIVER = 6, MMSYSERR_NOMEM = 7, WAVERR_BADFORMAT = 32, WAVERR_STILLPLAYING = 33, WAVERR_UNPREPARED = 34, WAVERR_SYNC = 35, pub fn toError(self: MMRESULT) MMError!void { return switch (self) { MMRESULT.MMSYSERR_NOERROR => {}, MMRESULT.MMSYSERR_ERROR => MMError.Error, MMRESULT.MMSYSERR_BADDEVICEID => MMError.BadDeviceID, MMRESULT.MMSYSERR_ALLOCATED => MMError.Allocated, MMRESULT.MMSYSERR_INVALIDHANDLE => MMError.InvalidHandle, MMRESULT.MMSYSERR_NODRIVER => MMError.NoDriver, MMRESULT.MMSYSERR_NOMEM => MMError.NoMem, MMRESULT.WAVERR_BADFORMAT => MMError.BadFormat, MMRESULT.WAVERR_STILLPLAYING => MMError.StillPlaying, MMRESULT.WAVERR_UNPREPARED => MMError.Unprepared, MMRESULT.WAVERR_SYNC => MMError.Sync, }; } }; const WAVEHDR = extern struct { lpData: windows.LPSTR, dwBufferLength: windows.DWORD, dwBytesRecorded: windows.DWORD, dwUser: windows.DWORD_PTR, dwFlags: windows.DWORD, dwLoops: windows.DWORD, lpNext: ?*WAVEHDR, reserved: windows.DWORD_PTR, }; const WAVEFORMATEX = extern struct { wFormatTag: windows.WORD, nChannels: windows.WORD, nSamplesPerSec: windows.DWORD, nAvgBytesPerSec: windows.DWORD, nBlockAlign: windows.WORD, wBitsPerSample: windows.WORD, cbSize: windows.WORD, }; extern "winmm" stdcallcc fn waveOutOpen(phwo: *HWAVEOUT, uDeviceID: UINT_PTR, pwfx: *const WAVEFORMATEX, dwCallback: windows.DWORD_PTR, dwCallbackInstance: windows.DWORD_PTR, fdwOpen: windows.DWORD) MMRESULT; extern "winmm" stdcallcc fn waveOutClose(hwo: HWAVEOUT) MMRESULT; extern "winmm" stdcallcc fn waveOutPrepareHeader(hwo: HWAVEOUT, pwh: *WAVEHDR, cbwh: windows.UINT) MMRESULT; extern "winmm" stdcallcc fn waveOutUnprepareHeader(hwo: HWAVEOUT, pwh: *WAVEHDR, cbwh: windows.UINT) MMRESULT; extern "winmm" stdcallcc fn waveOutWrite(hwo: HWAVEOUT, pwh: *WAVEHDR, cbwh: windows.UINT) MMRESULT; const Buffer = @import("../buffer.zig").Buffer; const AudioMode = @import("../../audio.zig").AudioMode; const Header = struct { const Self = @This(); pub const Error = error{InvalidLength}; buffer: Buffer(i16), wave_out: HWAVEOUT, wave_hdr: winnm.WAVEHDR, pub fn new(player: *Player, buf_size: usize) !Self { var result: Self = undefined; result.buffer = try Buffer(i16).initSize(player.allocator, buf_size); result.wave_out = player.wave_out; result.wave_hdr.dwBufferLength = @intCast(windows.DWORD, buf_size); result.wave_hdr.lpData = result.buffer.ptr(); result.wave_hdr.dwFlags = 0; try winnm.waveOutPrepareHeader(result.wave_out, &result.wave_hdr, @sizeOf(winnm.WAVEHDR)).toError(); return result; } pub fn write(self: *Self, data: []const i16) !void { if (data.len != self.buffer.len()) { return error.InvalidLength; } try self.buffer.replaceContents(data); try winnm.waveOutWrite(self.wave_out, &self.wave_hdr, @intCast(windows.UINT, self.buffer.len())).toError(); } pub fn destroy(self: *Self) !void { try winnm.waveOutUnprepareHeader(sefl.wave_out, &self.wave_hdr, @sizeOf(winnm.WAVEHDR)).toError(); self.buffer.deinit(); } }; pub const Backend = struct { const BUF_COUNT = 2; allocator: *Allocator, wave_out: winnm.HWAVEOUT, headers: [BUF_COUNT]Header, buffer: Buffer(f32), pub fn init(allocator: *Allocator, sample_rate: usize, mode: AudioMode, buf_size: usize) Error!Self { var result: Self = undefined; var handle: windows.HANDLE = undefined; const bps = switch (mode) { AudioMode.Mono => |bps| bps, AudioMode.Stereo => |bps| bps, }; const block_align = bps * mode.channelCount(); const format = winnm.WAVEFORMATEX{ .wFormatTag = winnm.WAVE_FORMAT_PCM, .nChannels = @intCast(windows.WORD, mode.channelCount()), .nSamplesPerSec = @intCast(windows.DWORD, sample_rate), .nAvgBytesPerSec = @intCast(windows.DWORD, sample_rate * block_align), .nBlockAlign = @intCast(windows.WORD, block_align), .wBitsPerSample = @intCast(windows.WORD, bps * 8), .cbSize = 0, }; try winnm.waveOutOpen(&handle, winnm.WAVE_MAPPER, &format, 0, 0, winnm.CALLBACK_NULL).toError(); result = Self{ .handle = handle, .headers = []Header{undefined} ** BUF_COUNT, .buf_size = buf_size, .allocator = allocator, .tmp = try Buffer(u8).initSize(allocator, buf_size), }; for (result.headers) |*header| { header.* = try Header.new(result, buf_size); } return result; } pub fn write(self: *Self, data: []const u8) Error!usize { const n = std.math.min(data.len, std.math.max(0, self.buf_size - self.tmp.len())); try self.tmp.append(data[0..n]); if (self.tmp.len() < self.buf_size) { return n; } var header = for (self.headers) |header| { if (header.wavehdr.dwFlags & winnm.WHDR_INQUEUE == 0) { break header; } } else return n; try header.write(self, self.tmp.toSlice()); try self.tmp.resize(0); return n; } pub fn close(self: *Self) Error!void { try winmm.waveOutReset(self.wave_out).toError(); for (self.headers) |*header| { try header.destroy(); } try winnm.waveOutClose(self.handle).toError(); self.buffer.deinit(); } };
src/audio/backend/winnm.zig
const std = @import("std"); const FileSystemDescription = @This(); allocator: std.mem.Allocator, /// Do not modify directly entries: std.ArrayListUnmanaged(*EntryDescription) = .{}, /// Do not modify directly root: *EntryDescription, /// Do not modify directly cwd: *EntryDescription, pub fn init(allocator: std.mem.Allocator) !*FileSystemDescription { var fs_desc = try allocator.create(FileSystemDescription); errdefer allocator.destroy(fs_desc); const root_name = try allocator.dupe(u8, "root"); errdefer allocator.free(root_name); var root_dir = try allocator.create(EntryDescription); errdefer allocator.destroy(root_dir); root_dir.* = .{ .file_system_description = fs_desc, .name = root_name, .subdata = .{ .dir = .{} }, }; fs_desc.* = .{ .allocator = allocator, .root = root_dir, .cwd = root_dir, }; try fs_desc.entries.append(allocator, root_dir); return fs_desc; } pub fn deinit(self: *FileSystemDescription) void { for (self.entries.items) |entry| entry.deinit(); self.entries.deinit(self.allocator); self.allocator.destroy(self); } pub fn getCwd(self: *const FileSystemDescription) *EntryDescription { return self.cwd; } pub fn setCwd(self: *FileSystemDescription, entry: *EntryDescription) void { std.debug.assert(entry.subdata == .dir); self.cwd = entry; } pub const EntryDescription = struct { file_system_description: *FileSystemDescription, name: []const u8, subdata: SubData, pub const SubData = union(enum) { file: FileData, dir: DirData, pub const FileData = struct { contents: []const u8, }; pub const DirData = struct { entries: std.ArrayListUnmanaged(*EntryDescription) = .{}, }; comptime { std.testing.refAllDecls(@This()); } }; pub fn addFile(self: *EntryDescription, name: []const u8, content: []const u8) !void { std.debug.assert(self.subdata == .dir); const allocator = self.file_system_description.allocator; const duped_name = try allocator.dupe(u8, name); errdefer allocator.free(duped_name); const duped_content = try allocator.dupe(u8, content); errdefer allocator.free(duped_content); var file = try allocator.create(EntryDescription); errdefer allocator.destroy(file); file.* = .{ .file_system_description = self.file_system_description, .name = duped_name, .subdata = .{ .file = .{ .contents = duped_content } }, }; try self.subdata.dir.entries.append(allocator, file); errdefer _ = self.subdata.dir.entries.pop(); try self.file_system_description.entries.append(allocator, file); } pub fn addDirectory(self: *EntryDescription, name: []const u8) !*EntryDescription { std.debug.assert(self.subdata == .dir); const allocator = self.file_system_description.allocator; const duped_name = try allocator.dupe(u8, name); errdefer allocator.free(duped_name); var dir = try allocator.create(EntryDescription); errdefer allocator.destroy(dir); dir.* = .{ .file_system_description = self.file_system_description, .name = duped_name, .subdata = .{ .dir = .{} }, }; try self.subdata.dir.entries.append(allocator, dir); errdefer _ = self.subdata.dir.entries.pop(); try self.file_system_description.entries.append(allocator, dir); return dir; } fn deinit(self: *EntryDescription) void { const allocator = self.file_system_description.allocator; allocator.free(self.name); switch (self.subdata) { .file => |file| allocator.free(file.contents), .dir => |*dir| dir.entries.deinit(allocator), } allocator.destroy(self); } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/config/FileSystemDescription.zig
const std = @import("std"); const platform = @import("platform.zig"); const util = @import("util.zig"); const c = @cImport({ @cInclude("ucontext.h"); }); const Cookie = util.Cookie; pub const Error = error{NoSuchTask}; fn nop(task: *Task) void {} pub const Task = struct { pub const Id = i24; pub const EntryPoint = fn (task: *Task) void; pub const stack_data_align = @alignOf(usize); pub const KernelParentId: Task.Id = -1; scheduler: *Scheduler, tid: Task.Id, parent_tid: ?Task.Id, cookie_meta: usize = undefined, cookie: Cookie, stack_data: []align(Task.stack_data_align) u8, context: c.ucontext_t = undefined, started: bool = false, killed: bool = false, entry_point: Task.EntryPoint, on_deinit: ?fn (task: *Task) void = null, pub fn init(scheduler: *Scheduler, tid: Task.Id, parent_tid: ?Task.Id, entry_point: Task.EntryPoint, stack_size: usize, cookie: Cookie) !*Task { var allocator = scheduler.allocator; var ret = try allocator.create(Task); errdefer allocator.destroy(ret); var stack_data = try allocator.allocAdvanced(u8, Task.stack_data_align, stack_size, .at_least); errdefer allocator.free(stack_data); ret.* = Task{ .scheduler = scheduler, .tid = tid, .parent_tid = parent_tid, .entry_point = entry_point, .stack_data = stack_data, .cookie = cookie }; ret.context.uc_stack.ss_sp = @ptrCast(*c_void, stack_data); ret.context.uc_stack.ss_size = stack_size; c.t_makecontext(&ret.context, Task.entryPoint, @ptrToInt(ret)); return ret; } fn entryPoint(self_ptr: usize) callconv(.C) void { var self = @intToPtr(*Task, self_ptr); self.entry_point(self); self.yield(); } pub fn yield(self: *Task) void { self.started = false; _ = c.t_getcontext(&self.context); if (!self.started) _ = c.t_setcontext(&self.scheduler.context); } pub fn kill(self: *Task) void { self.killed = true; } pub fn wait(self: *Task, peek: bool) bool { if (!peek and self.killed) self.parent_tid = null; return self.killed; } pub fn deinit(self: *Task) void { if (self.on_deinit) |on_deinit| on_deinit(self); self.scheduler.allocator.destroy(self); } }; pub const Scheduler = struct { const TaskList = std.AutoHashMap(Task.Id, *Task); allocator: *std.mem.Allocator, tasks: Scheduler.TaskList, next_spawn_tid: Task.Id, context: c.ucontext_t = undefined, current_tid: ?Task.Id = undefined, pub fn init(allocator: *std.mem.Allocator) !Scheduler { return Scheduler{ .allocator = allocator, .tasks = Scheduler.TaskList.init(allocator), .next_spawn_tid = 0 }; } pub fn yieldCurrent(self: *Scheduler) void { if (self.current_tid) |tid| { self.tasks.get(tid).?.yield(); } } pub fn spawn(self: *Scheduler, parent_tid: ?Task.Id, entry_point: Task.EntryPoint, cookie: Cookie, stack_size: usize) !*Task { var new_index: Task.Id = undefined; while (true) { new_index = @atomicRmw(Task.Id, &self.next_spawn_tid, .Add, 1, .SeqCst); if (self.tasks.get(new_index) == null) break; } var task = try Task.init(self, new_index, parent_tid, entry_point, stack_size, cookie); errdefer task.deinit(); _ = try self.tasks.put(new_index, task); return task; } pub fn loopOnce(self: *Scheduler) void { for (self.tasks.items()) |entry| { var task = entry.value; self.current_tid = entry.key; task.started = true; _ = c.t_getcontext(&self.context); if (!task.killed and task.started) _ = c.t_setcontext(&task.context); if (task.parent_tid != null and task.parent_tid.? != Task.KernelParentId and self.tasks.get(task.parent_tid.?) == null) task.parent_tid = null; if (task.killed and task.parent_tid == null) { _ = self.tasks.remove(entry.key); task.deinit(); } self.current_tid = null; } } };
kernel/task.zig
const std = @import("std"); const image = @import("image.zig"); const scene = @import("scene.zig"); const camera = @import("camera.zig"); const config = @import("config.zig"); const sphere = @import("sphere.zig"); const tracer = @import("tracer.zig"); const vector = @import("vector.zig"); const worker = @import("worker.zig"); const material = @import("material.zig"); const Vec3 = config.Vec3; pub fn main() !void { // Allocator var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); // Camera const field_of_view = std.math.tan(@as(f64, 55.0 * std.math.pi / 180.0 * 0.5)); var cur_camera = camera.Camera{ .direction = vector.create_unit_vector(0.0, -0.042612, -1.0), .field_of_view = field_of_view }; // Materials const diffuse_black = material.Material{}; const diffuse_grey = material.Material{ .diffuse = .{ 0.75, 0.75, 0.75 } }; const diffuse_red = material.Material{ .diffuse = .{ 0.95, 0.15, 0.15 } }; const diffuse_blue = material.Material{ .diffuse = .{ 0.25, 0.25, 0.7 } }; const white_light = material.Material{ .emissive = @splat(config.SCENE_DIMS, @as(f64, 10)) }; const mirror = material.Material{ .material_type = material.MaterialType.MIRROR, .diffuse = @splat(config.SCENE_DIMS, @as(f64, 0.99)) }; const glossy_white = material.Material{ .material_type = material.MaterialType.GLOSSY, .diffuse = .{ 0.3, 0.05, 0.05 }, .specular = @splat(config.SCENE_DIMS, @as(f64, 0.69)), .specular_exponent = 45.0 }; // Scene var cornell_box = scene.Scene{ .objects = try std.ArrayList(sphere.Sphere).initCapacity(allocator, 16), .lights = try std.ArrayList(usize).initCapacity(allocator, 16), .camera = &cur_camera }; try cornell_box.objects.append(sphere.make_sphere(16.5, .{ 76.0, 16.5, 78.0 }, &mirror)); try cornell_box.objects.append(sphere.make_sphere(1e5, .{ 50.0, 1e5, 81.6 }, &diffuse_grey)); try cornell_box.objects.append(sphere.make_sphere(1e5, .{ 50.0, 40.8, 1e5 }, &diffuse_grey)); try cornell_box.objects.append(sphere.make_sphere(10.5, .{ 50.0, 65.1, 81.6 }, &white_light)); try cornell_box.objects.append(sphere.make_sphere(16.5, .{ 27.0, 16.5, 57.0 }, &glossy_white)); try cornell_box.objects.append(sphere.make_sphere(1e5, .{ 1e5 + 1.0, 40.8, 81.6 }, &diffuse_red)); try cornell_box.objects.append(sphere.make_sphere(1e5, .{ 50.0, -1e5 + 81.6, 81.6 }, &diffuse_grey)); try cornell_box.objects.append(sphere.make_sphere(1e5, .{ -1e5 + 99.0, 40.8, 81.6 }, &diffuse_blue)); try cornell_box.objects.append(sphere.make_sphere(1e5, .{ 50.0, 40.8, -1e5 + 170.0 }, &diffuse_black)); try cornell_box.collectLights(); // Path tracer var cur_tracer = tracer.Tracer{ .scene = &cornell_box, .samples = undefined }; var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; try std.os.getrandom(std.mem.asBytes(&seed)); break :blk seed; }); const rng = &prng.random(); camera.samplePixels(&cur_tracer.samples, rng); // Framebuffer var framebuffer = std.ArrayList(u8).init(allocator); try framebuffer.appendNTimes(0, config.SCREEN_SIDE * config.SCREEN_SIDE * config.NUM_CHANNELS); // Cores const num_cores = try std.Thread.getCpuCount(); std.debug.print("Found {} CPU cores\n", .{num_cores}); // Workers var num_workers = num_cores; var worker_data = try std.ArrayList(worker.WorkerThread).initCapacity(allocator, num_workers); var threads = try std.ArrayList(std.Thread).initCapacity(allocator, num_workers); var done_count = std.atomic.Atomic(u32).init(0); var work_queue = std.atomic.Queue(worker.WorkItem).init(); // Multi-threaded preparation if (config.IS_MULTI_THREADED) { var worker_idx: usize = 0; while (worker_idx < num_workers) : (worker_idx += 1) { worker_data.appendAssumeCapacity(.{ .done_count = &done_count, .queue = &work_queue }); threads.appendAssumeCapacity(try std.Thread.spawn(.{}, worker.launchWorkerThread, .{&worker_data.items[worker_idx]})); } } // Execution const chunk_size: usize = 256; const num_chunks = config.SCREEN_SIDE * config.SCREEN_SIDE / chunk_size; const start_time = std.time.milliTimestamp(); if (config.IS_MULTI_THREADED) { var chunk_idx: usize = 0; var thread_idx: usize = 0; while (chunk_idx < num_chunks) : (chunk_idx += 1) { const node = allocator.create(std.atomic.Queue(worker.WorkItem).Node) catch unreachable; node.* = .{ .prev = undefined, .next = undefined, .data = .{ .tracer = &cur_tracer, .buffer = &framebuffer.items, .offset = chunk_idx * chunk_size, .chunk_size = chunk_size } }; worker_data.items[thread_idx].pushJobAndWake(node); thread_idx = (thread_idx + 1) % num_workers; } } else { try tracer.tracePaths(cur_tracer, framebuffer.items, 0, config.SCREEN_SIDE * config.SCREEN_SIDE); } try worker.waitUntilDone(&done_count, num_chunks); // Time const time_taken = std.time.milliTimestamp() - start_time; std.debug.print("Took {d} seconds\n", .{@intToFloat(f64, time_taken) / 1000.0}); // Image try image.createImage(framebuffer.items); for (threads.items) |thread, idx| { worker.joinThread(thread, &worker_data.items[idx]); } }
src/main.zig
const std = @import("std"); const kernel = @import("root"); const arch = kernel.arch; const mm = kernel.mm; pub var logger = kernel.logging.logger("task"){}; pub const Task = struct { regs: arch.TaskRegs, stack: []u8, next: NextNode, const Self = @This(); pub const NextNode = std.TailQueue(void).Node; pub fn create(func: fn () noreturn) !*Task { var task = try mm.memoryAllocator().alloc(Task); var stack = try mm.memoryAllocator().alloc([arch.KERNEL_STACK_SIZE]u8); task.regs = arch.TaskRegs.setup(func, stack); task.stack = stack; task.next = NextNode{ .next = null, .data = {} }; return task; } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void { _ = fmt; try stream.writeAll(@typeName(Self)); try stream.writeAll("{"); try std.fmt.formatType(self.regs, fmt, options, stream, 1); try stream.writeAll("}"); } }; pub fn switch_task(to: *Task) void { const core_block = kernel.getCoreBlock(); const prev_task = core_block.current_task; const next_task = to; std.debug.assert(prev_task != next_task); // Ensure we'll get scheduled sometime scheduler().addTask(prev_task); // Swap tasks core_block.current_task = next_task; defer core_block.current_task = prev_task; arch.switch_task(prev_task, next_task); } pub var init_task: Task = std.mem.zeroes(Task); pub const Scheduler = struct { task_list: std.TailQueue(void), const Self = @This(); pub fn addTask(self: *Self, task: *Task) void { self.task_list.append(&task.next); } pub fn reschedule(self: *Self) *Task { if (self.task_list.popFirst()) |node| { var task: *Task = @fieldParentPtr(Task, "next", node); return task; } @panic("Nothing to schedule!"); } pub fn yield(self: *Self) void { const next_task: *Task = self.reschedule(); switch_task(next_task); } }; var sched = Scheduler{ .task_list = std.TailQueue(void){} }; pub fn scheduler() *Scheduler { return &sched; }
kernel/task.zig
const std = @import("std"); const util = @import("util.zig"); const uv_util = @import("uv_util.zig"); const c = uv_util.c; pub const log = util.log; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = &gpa.allocator; const DEFAULT_PORT = 3000; const data = "HELLO FROM CLIENT!"; pub fn main() !void { uv_util.init(alloc); defer _ = gpa.deinit(); const loop = c.uv_default_loop(); var addr: c.sockaddr_in = undefined; var client: c.uv_tcp_t = undefined; _ = c.uv_tcp_init(loop, &client); client.data = @ptrCast(?*c_void, loop); _ = c.uv_ip4_addr("127.0.0.1", DEFAULT_PORT, &addr); const connect = try alloc.create(c.uv_connect_t); _ = c.uv_tcp_connect(connect, &client, @ptrCast(?*const c.sockaddr, &addr), on_connect); //_ = c.uv_tcp_bind(&server, @ptrCast(?*const c.sockaddr, &addr), 0); //const r = c.uv_listen(@ptrCast(?*c.uv_stream_t, &server), DEFAULT_BACKLOG, on_new_connection); //if (r != 0) { // std.log.err("Listen error {}", .{c.uv_strerror(r)}); // return error.listen_error; //} _ = c.uv_run(loop, util.castCEnum(c.uv_run, 1, c.UV_RUN_DEFAULT)); std.log.info("Closing...", .{}); } export fn on_connect(con: ?*c.uv_connect_t, status: i32) void { var req = alloc.create(uv_util.WriteReq) catch unreachable; std.log.info("> {s}", .{data}); const to_send = alloc.dupe(u8, data) catch unreachable; req.buf = c.uv_buf_init(to_send.ptr, @intCast(u32, to_send.len)); _ = c.uv_write(&req.req, con.?.handle, &req.buf, 1, uv_util.on_write); _ = c.uv_read_start(con.?.handle, uv_util.alloc_buffer, on_read); alloc.destroy(con.?); } export fn on_read(client: ?*c.uv_stream_t, nread: isize, buf: ?*const c.uv_buf_t) void { std.debug.assert(client != null); std.debug.assert(buf != null); if (nread < 0) { if (nread == c.UV_EOF) { _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), null); } } else if (nread > 0) { std.log.info("< {s}", .{buf.?.base[0..buf.?.len]}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), null); } if (buf.?.base != null) { alloc.free(buf.?.base[0..buf.?.len]); } }
src/uv_examples/uvclient.zig
const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.network; }; const TcpListener = @This(); // Constructor/destructor /// Creates a new tcp listener socket pub fn create() !TcpListener { var sock = sf.c.sfTcpListener_create(); if (sock) |s| { return TcpListener{ ._ptr = s }; } else return sf.Error.nullptrUnknownReason; } /// Destroys this socket pub fn destroy(self: *TcpListener) void { sf.c.sfTcpListener_destroy(self._ptr); } // Methods /// Enables or disables blocking mode (true for blocking) /// In blocking mode, receive waits for data pub fn setBlocking(self: *TcpListener, blocking: bool) void { sf.c.sfTcpListener_setBlocking(self._ptr, @boolToInt(blocking)); } /// Tells whether or not the socket is in blocking mode pub fn isBlocking(self: TcpListener) bool { return sf.c.sfTcpListener_isBlocking(self._ptr) != 0; } /// Gets the port this socket is listening on /// Error if the socket is not listening pub fn getLocalPort(self: TcpListener) error{notListening}!u16 { const port = sf.c.sfTcpListener_getLocalPort(self._ptr); if (port == 0) return error.notListening; return port; } /// Starts listening for incoming connections on a given port (and address) /// If address is null, it listens on any address of this machine pub fn listen(self: *TcpListener, port: u16, address: ?sf.IpAddress) sf.Socket.Error!void { const ip = if (address) |i| i._ip else sf.c.sfIpAddress_Any; const code = sf.c.sfTcpListener_listen(self._ptr, port, ip); try sf.Socket._codeToErr(code); } /// Accepts a new connection, returns a tcp socket if it works /// If the tcp is in blocking mode, it will wait pub fn accept(self: *TcpListener) sf.Socket.Error!?sf.TcpSocket { var ret: sf.TcpSocket = undefined; const retptr = @ptrCast([*c]?*sf.c.sfTcpSocket, &(ret._ptr)); const code = sf.c.sfTcpListener_accept(self._ptr, retptr); if (!self.isBlocking() and code == sf.c.sfSocketNotReady) return null; try sf.Socket._codeToErr(code); return ret; } /// Pointer to the csfml structure _ptr: *sf.c.sfTcpListener, // TODO: write tests
src/sfml/network/TcpListener.zig
const std = @import("std"); const ft = @import("freetype"); const zigimg = @import("zigimg"); const Atlas = @import("atlas.zig").Atlas; const AtlasErr = @import("atlas.zig").Error; const UVData = @import("atlas.zig").UVData; const App = @import("main.zig").App; const draw = @import("draw.zig"); const Vertex = draw.Vertex; const Tessellator = @import("tessellator.zig").Tessellator; // If true, show the filled triangles green, the concave beziers blue and the convex ones red const debug_colors = false; pub const ResizableLabel = @This(); const Vec2 = @Vector(2, f32); const Vec4 = @Vector(4, f32); const VertexList = std.ArrayList(Vertex); // All the data that a single character needs to be rendered // TODO: hori/vert advance, write file format const CharVertices = struct { filled_vertices: VertexList, filled_vertices_indices: std.ArrayList(u16), // Concave vertices belong to the filled_vertices list, so just index them concave_vertices: std.ArrayList(u16), // The point outside of the convex bezier, doesn't belong to the filled vertices, // But the other two points do, so put those in the indices convex_vertices: VertexList, convex_vertices_indices: std.ArrayList(u16), }; face: ft.Face, char_map: std.AutoHashMap(u21, CharVertices), allocator: std.mem.Allocator, tessellator: Tessellator, white_texture: UVData, // The data that the write function needs // TODO: move twxture here, don't limit to just white_texture const WriterContext = struct { label: *ResizableLabel, app: *App, position: Vec4, text_color: Vec4, text_size: u32, }; const WriterError = ft.Error || std.mem.Allocator.Error || AtlasErr; const Writer = std.io.Writer(WriterContext, WriterError, write); pub fn writer(label: *ResizableLabel, app: *App, position: Vec4, text_color: Vec4, text_size: u32) Writer { return Writer{ .context = .{ .label = label, .app = app, .position = position, .text_color = text_color, .text_size = text_size, }, }; } pub fn init(self: *ResizableLabel, lib: ft.Library, font_path: []const u8, face_index: i32, allocator: std.mem.Allocator, white_texture: UVData) !void { self.* = ResizableLabel{ .face = try lib.newFace(font_path, face_index), .char_map = std.AutoHashMap(u21, CharVertices).init(allocator), .allocator = allocator, .tessellator = undefined, .white_texture = white_texture, }; self.tessellator.init(self.allocator); } pub fn deinit(label: *ResizableLabel) void { label.face.deinit(); label.tessellator.deinit(); // FIXME: // std.debug.todo("valueIterator() doesn't stop? How do we deallocate the values?"); // while (label.char_map.valueIterator().next()) |value| { // _ = value; // value.filled_vertices.deinit(); // value.filled_vertices_indices.deinit(); // value.convex_vertices.deinit(); // value.convex_vertices_indices.deinit(); // value.concave_vertices.deinit(); // } label.char_map.deinit(); } // TODO: handle offsets // FIXME: many useless allocations for the arraylists fn write(ctx: WriterContext, bytes: []const u8) WriterError!usize { var offset = Vec4{ 0, 0, 0, 0 }; var c: usize = 0; while (c < bytes.len) { const len = std.unicode.utf8ByteSequenceLength(bytes[c]) catch unreachable; const char = std.unicode.utf8Decode(bytes[c..(c + len)]) catch unreachable; c += len; switch (char) { '\n' => { offset[0] = 0; offset[1] -= @intToFloat(f32, ctx.label.face.size().metrics().height >> 6); std.debug.todo("New line not implemented yet"); }, ' ' => { std.debug.todo("Space character not implemented yet"); // const v = try ctx.label.char_map.getOrPut(char); // if (!v.found_existing) { // try ctx.label.face.setCharSize(ctx.label.size * 64, 0, 50, 0); // try ctx.label.face.loadChar(char, .{ .render = true }); // const glyph = ctx.label.face.glyph; // v.value_ptr.* = GlyphInfo{ // .uv_data = undefined, // .metrics = glyph.metrics(), // }; // } // offset[0] += @intToFloat(f32, v.value_ptr.metrics.horiAdvance >> 6); }, else => { const v = try ctx.label.char_map.getOrPut(char); if (!v.found_existing) { try ctx.label.face.loadChar(char, .{ .no_scale = true, .no_bitmap = true }); const glyph = ctx.label.face.glyph(); // Use a big scale and then scale to the actual text size const multiplier = 1024 << 6; const matrix = ft.Matrix{ .xx = 1 * multiplier, .xy = 0 * multiplier, .yx = 0 * multiplier, .yy = 1 * multiplier, }; glyph.outline().?.transform(matrix); v.value_ptr.* = CharVertices{ .filled_vertices = VertexList.init(ctx.label.allocator), .filled_vertices_indices = std.ArrayList(u16).init(ctx.label.allocator), .concave_vertices = std.ArrayList(u16).init(ctx.label.allocator), .convex_vertices = VertexList.init(ctx.label.allocator), .convex_vertices_indices = std.ArrayList(u16).init(ctx.label.allocator), }; var outline_ctx = OutlineContext{ .outline_verts = std.ArrayList(std.ArrayList(Vec2)).init(ctx.label.allocator), .inside_verts = std.ArrayList(Vec2).init(ctx.label.allocator), .concave_vertices = std.ArrayList(Vec2).init(ctx.label.allocator), .convex_vertices = std.ArrayList(Vec2).init(ctx.label.allocator), }; defer outline_ctx.outline_verts.deinit(); defer { for (outline_ctx.outline_verts.items) |*item| { item.deinit(); } } defer outline_ctx.inside_verts.deinit(); defer outline_ctx.concave_vertices.deinit(); defer outline_ctx.convex_vertices.deinit(); const callbacks = ft.Outline.Funcs(*OutlineContext){ .move_to = moveToFunction, .line_to = lineToFunction, .conic_to = conicToFunction, .cubic_to = cubicToFunction, .shift = 0, .delta = 0, }; try ctx.label.face.glyph().outline().?.decompose(&outline_ctx, callbacks); uniteOutsideAndInsideVertices(&outline_ctx); // Tessellator.triangulatePolygons() doesn't seem to work, so just // call triangulatePolygon() for each polygon, and put the results all // in all_outlines and all_indices var all_outlines = std.ArrayList(Vec2).init(ctx.label.allocator); defer all_outlines.deinit(); var all_indices = std.ArrayList(u16).init(ctx.label.allocator); defer all_indices.deinit(); var idx_offset: u16 = 0; for (outline_ctx.outline_verts.items) |item| { ctx.label.tessellator.triangulatePolygon(item.items); defer ctx.label.tessellator.clearBuffers(); try all_outlines.appendSlice(ctx.label.tessellator.out_verts.items); for (ctx.label.tessellator.out_idxes.items) |idx| { try all_indices.append(idx + idx_offset); } idx_offset += @intCast(u16, ctx.label.tessellator.out_verts.items.len); } for (all_outlines.items) |item| { // FIXME: The uv_data is wrong, should be pushed up by the lowest a character can be const vertex_uv = item / @splat(2, @as(f32, 1024 << 6)); const vertex_pos = Vec4{ item[0], item[1], 0, 1 }; try v.value_ptr.filled_vertices.append(Vertex{ .pos = vertex_pos, .uv = vertex_uv }); } try v.value_ptr.filled_vertices_indices.appendSlice(all_indices.items); // FIXME: instead of finding the closest vertex and use its index maybe use indices directly in the moveTo,... functions var i: usize = 0; while (i < outline_ctx.concave_vertices.items.len) : (i += 1) { for (all_outlines.items) |item, j| { const dist = @reduce(.Add, (item - outline_ctx.concave_vertices.items[i]) * (item - outline_ctx.concave_vertices.items[i])); if (dist < 0.1) { try v.value_ptr.concave_vertices.append(@truncate(u16, j)); break; } } } i = 0; while (i < outline_ctx.convex_vertices.items.len) : (i += 3) { const vert = outline_ctx.convex_vertices.items[i]; const vertex_uv = vert / @splat(2, @as(f32, 1024 << 6)); const vertex_pos = Vec4{ vert[0], vert[1], 0, 1 }; try v.value_ptr.convex_vertices.append(Vertex{ .pos = vertex_pos, .uv = vertex_uv }); for (all_outlines.items) |item, j| { const dist1 = @reduce(.Add, (item - outline_ctx.convex_vertices.items[i + 1]) * (item - outline_ctx.convex_vertices.items[i + 1])); if (dist1 < 0.1) { try v.value_ptr.convex_vertices_indices.append(@truncate(u16, j)); } const dist2 = @reduce(.Add, (item - outline_ctx.convex_vertices.items[i + 2]) * (item - outline_ctx.convex_vertices.items[i + 2])); if (dist2 < 0.1) { try v.value_ptr.convex_vertices_indices.append(@truncate(u16, j)); } } } ctx.label.tessellator.clearBuffers(); } // Read the data and apply resizing of pos and uv var filled_vertices_after_offset = try ctx.label.allocator.alloc(Vertex, v.value_ptr.filled_vertices.items.len); defer ctx.label.allocator.free(filled_vertices_after_offset); for (filled_vertices_after_offset) |*vert, i| { vert.* = v.value_ptr.filled_vertices.items[i]; vert.pos *= Vec4{ @intToFloat(f32, ctx.text_size) / 1024, @intToFloat(f32, ctx.text_size) / 1024, 0, 1 }; vert.pos += ctx.position + offset; vert.uv = vert.uv * ctx.label.white_texture.width_and_height + ctx.label.white_texture.bottom_left; } var actual_filled_vertices_to_use = try ctx.label.allocator.alloc(Vertex, v.value_ptr.filled_vertices_indices.items.len); defer ctx.label.allocator.free(actual_filled_vertices_to_use); for (actual_filled_vertices_to_use) |*vert, i| { vert.* = filled_vertices_after_offset[v.value_ptr.filled_vertices_indices.items[i]]; } try ctx.app.vertices.appendSlice(actual_filled_vertices_to_use); if (debug_colors) { try ctx.app.fragment_uniform_list.appendNTimes(.{ .blend_color = .{ 0, 1, 0, 1 } }, actual_filled_vertices_to_use.len / 3); } else { try ctx.app.fragment_uniform_list.appendNTimes(.{ .blend_color = ctx.text_color }, actual_filled_vertices_to_use.len / 3); } var convex_vertices_after_offset = try ctx.label.allocator.alloc(Vertex, v.value_ptr.convex_vertices.items.len + v.value_ptr.convex_vertices_indices.items.len); defer ctx.label.allocator.free(convex_vertices_after_offset); var j: u16 = 0; var k: u16 = 0; while (j < convex_vertices_after_offset.len) : (j += 3) { convex_vertices_after_offset[j] = v.value_ptr.convex_vertices.items[j / 3]; convex_vertices_after_offset[j].pos *= Vec4{ @intToFloat(f32, ctx.text_size) / 1024, @intToFloat(f32, ctx.text_size) / 1024, 0, 1 }; convex_vertices_after_offset[j].pos += ctx.position + offset; convex_vertices_after_offset[j].uv = convex_vertices_after_offset[j].uv * ctx.label.white_texture.width_and_height + ctx.label.white_texture.bottom_left; convex_vertices_after_offset[j + 1] = filled_vertices_after_offset[v.value_ptr.convex_vertices_indices.items[k]]; convex_vertices_after_offset[j + 2] = filled_vertices_after_offset[v.value_ptr.convex_vertices_indices.items[k + 1]]; k += 2; } try ctx.app.vertices.appendSlice(convex_vertices_after_offset); if (debug_colors) { try ctx.app.fragment_uniform_list.appendNTimes(.{ .type = .convex, .blend_color = .{ 1, 0, 0, 1 } }, convex_vertices_after_offset.len / 3); } else { try ctx.app.fragment_uniform_list.appendNTimes(.{ .type = .convex, .blend_color = ctx.text_color }, convex_vertices_after_offset.len / 3); } var concave_vertices_after_offset = try ctx.label.allocator.alloc(Vertex, v.value_ptr.concave_vertices.items.len); defer ctx.label.allocator.free(concave_vertices_after_offset); for (concave_vertices_after_offset) |*vert, i| { vert.* = filled_vertices_after_offset[v.value_ptr.concave_vertices.items[i]]; } try ctx.app.vertices.appendSlice(concave_vertices_after_offset); if (debug_colors) { try ctx.app.fragment_uniform_list.appendNTimes(.{ .type = .concave, .blend_color = .{ 0, 0, 1, 1 } }, concave_vertices_after_offset.len / 3); } else { try ctx.app.fragment_uniform_list.appendNTimes(.{ .type = .concave, .blend_color = ctx.text_color }, concave_vertices_after_offset.len / 3); } ctx.app.update_vertex_buffer = true; ctx.app.update_frag_uniform_buffer = true; // offset[0] += @intToFloat(f32, v.value_ptr.metrics.horiAdvance >> 6); }, } } return bytes.len; } // First move to initialize the outline, (first point), // After many Q L or C, we will come back to the first point and then call M again if we need to hollow // On the second M, we instead use an L to connect the first point to the start of the hollow path. // We then follow like normal and at the end of the hollow path we use another L to close the path. // This is basically how an o would be drawn, each β”Œ... character is a Vertex // β”Œ--------┐ // | | // | | // | | // | β”Œ----┐ | // β””-β”˜ | | Consider the vertices here and below to be at the same height, they are coincident // β”Œ-┐ | | // | β””----β”˜ | // | | // | | // | | // β””--------β”˜ const OutlineContext = struct { // There may be more than one polygon (for example with 'i' we have the polygon of the base and another for the circle) outline_verts: std.ArrayList(std.ArrayList(Vec2)), // The internal outline, used for carving the shape (for example in a, we would first get the outline of the a, but if we stopped there, it woul // be filled, so we need another outline for carving the filled polygon) inside_verts: std.ArrayList(Vec2), // For the concave and convex beziers concave_vertices: std.ArrayList(Vec2), convex_vertices: std.ArrayList(Vec2), }; // If there are elements in inside_verts, unite them with the outline_verts, effectively carving the shape fn uniteOutsideAndInsideVertices(ctx: *OutlineContext) void { if (ctx.inside_verts.items.len != 0) { // Check which point of outline is closer to the first of inside var last_outline = &ctx.outline_verts.items[ctx.outline_verts.items.len - 1]; const closest_to_inside: usize = blk: { const first_point_inside = ctx.inside_verts.items[0]; var min: f32 = std.math.f32_max; var closest_index: usize = undefined; for (last_outline.items) |item, i| { const dist = @reduce(.Add, (item - first_point_inside) * (item - first_point_inside)); if (dist < min) { min = dist; closest_index = i; } } break :blk closest_index; }; ctx.inside_verts.append(last_outline.items[closest_to_inside]) catch unreachable; last_outline.insertSlice(closest_to_inside + 1, ctx.inside_verts.items) catch unreachable; ctx.inside_verts.clearRetainingCapacity(); } } // TODO: Return also allocation error fn moveToFunction(ctx: *OutlineContext, _to: ft.Vector) ft.Error!void { uniteOutsideAndInsideVertices(ctx); const to = Vec2{ @intToFloat(f32, _to.x), @intToFloat(f32, _to.y) }; // To check wether a point is carving a polygon, // Cast a ray to the right of the point and check // when this ray intersects the edges of the polygons, // if the number of intersections is odd -> inside, // if it's even -> outside var new_point_is_inside = false; for (ctx.outline_verts.items) |polygon| { var i: usize = 1; while (i < polygon.items.len) : (i += 1) { const v1 = polygon.items[i - 1]; const v2 = polygon.items[i]; const min_y = @minimum(v1[1], v2[1]); const max_y = @maximum(v1[1], v2[1]); const min_x = @minimum(v1[0], v2[0]); // If the point is at the same y as another, it may be counted twice, // That's why we add the last != if (to[1] >= min_y and to[1] <= max_y and to[0] >= min_x and to[1] != v2[1]) { new_point_is_inside = !new_point_is_inside; } } } // If the point is inside, put it in the inside verts if (new_point_is_inside) { ctx.inside_verts.append(to) catch unreachable; } else { // Otherwise create a new polygon var new_outline_list = std.ArrayList(Vec2).init(ctx.outline_verts.allocator); new_outline_list.append(to) catch unreachable; ctx.outline_verts.append(new_outline_list) catch unreachable; } } fn lineToFunction(ctx: *OutlineContext, to: ft.Vector) ft.Error!void { // std.log.info("L {} {}", .{ to.x, to.y }); // If inside_verts is not empty, we need to fill it if (ctx.inside_verts.items.len != 0) { ctx.inside_verts.append(.{ @intToFloat(f32, to.x), @intToFloat(f32, to.y) }) catch unreachable; } else { // Otherwise append the new point to the last polygon ctx.outline_verts.items[ctx.outline_verts.items.len - 1].append(.{ @intToFloat(f32, to.x), @intToFloat(f32, to.y) }) catch unreachable; } } fn conicToFunction(ctx: *OutlineContext, _control: ft.Vector, _to: ft.Vector) ft.Error!void { // std.log.info("C {} {} {} {}", .{ control.x, control.y, to.x, to.y }); const control = Vec2{ @intToFloat(f32, _control.x), @intToFloat(f32, _control.y) }; const to = Vec2{ @intToFloat(f32, _to.x), @intToFloat(f32, _to.y) }; // Either the inside verts or the outine ones var verts_to_write = if (ctx.inside_verts.items.len != 0) &ctx.inside_verts else &ctx.outline_verts.items[ctx.outline_verts.items.len - 1]; const previous_point = verts_to_write.items[verts_to_write.items.len - 1]; const vertices = [_]Vec2{ control, to, previous_point }; const vec1 = control - previous_point; const vec2 = to - control; // if ccw, it's concave, else it's convex if ((vec1[0] * vec2[1] - vec1[1] * vec2[0]) > 0) { ctx.concave_vertices.appendSlice(&vertices) catch unreachable; verts_to_write.append(control) catch unreachable; } else { ctx.convex_vertices.appendSlice(&vertices) catch unreachable; } verts_to_write.append(to) catch unreachable; } // Doesn't seem to be used much fn cubicToFunction(ctx: *OutlineContext, control_0: ft.Vector, control_1: ft.Vector, to: ft.Vector) ft.Error!void { _ = ctx; _ = control_0; _ = control_1; _ = to; @panic("TODO: search how to approximate cubic bezier with quadratic ones"); } pub fn print(label: *ResizableLabel, app: *App, comptime fmt: []const u8, args: anytype, position: Vec4, text_color: Vec4, text_size: u32) !void { const w = writer(label, app, position, text_color, text_size); try w.print(fmt, args); }
examples/gkurve/resizable_label.zig
const std = @import("std"); const Fundude = @import("main.zig"); const Cpu = @import("Cpu.zig"); const joypad = @import("joypad.zig"); const serial = @import("serial.zig"); const timer = @import("timer.zig"); const audio = @import("audio.zig"); const video = @import("video.zig"); const BEYOND_CART = 0x8000; const BANK_SIZE = 0x4000; const Mmu = @This(); dyn: extern struct { rom: [0x8000]u8 align(8), vram: video.Vram, // [$8000 - $A000) switchable_ram: [0x2000]u8, // [$A000 - $C000) ram: [0x2000]u8, // [$C000 - $E000) ram_echo: [0x1E00]u8, // [$E000 - $FE00) oam: [40]video.SpriteAttr, // [$FE00 - $FEA0) _pad_fea0_ff00: [0x0060]u8, // [$FEA0 - $FF00) io: Io, // [$FF00 - $FF80) high_ram: [0x007F]u8, // [$FF80 - $FFFF) interrupt_enable: Cpu.Irq, // [$FFFF] }, cart: []const u8, bank: u9, cart_meta: struct { mbc: Mbc, rumble: bool = false, timer: bool = false, ram: bool = false, battery: bool = false, }, pub const Io = extern struct { joypad: joypad.Io, // [$FF00] serial: serial.Io, // [$FF01 - $FF02] _pad_ff03: u8, timer: timer.Io, // [$FF04 - $FF07] _pad_ff08_0e: [7]u8, // [$FF08 - $FF0E] IF: Cpu.Irq, // [$FF0F] audio: audio.Io, // [$FF10 - $FF3F] video: video.Io, // [$FF40 - $FF4C] _pad_ff4d_4f: [4]u8, // [$FF4D - $FF4F] boot_complete: u8, // [$FF50] Bootloader sets this on 0x00FE _pad_ff51: u8, _pad_ff52_53: [2]u8, _pad_ff54_57: [4]u8, _pad_ff54_5f: [8]u8, _pad_ff60_7f: [0x0020]u8, // [$FF60 - $FF7F] }; test "offsets" { const Linear = std.meta.fieldInfo(Mmu, .dyn).field_type; std.testing.expectEqual(0x10000, @sizeOf(Linear)); std.testing.expectEqual(0x0000, @byteOffsetOf(Linear, "rom")); std.testing.expectEqual(0x8000, @byteOffsetOf(Linear, "vram")); std.testing.expectEqual(0xA000, @byteOffsetOf(Linear, "switchable_ram")); std.testing.expectEqual(0xC000, @byteOffsetOf(Linear, "ram")); std.testing.expectEqual(0xE000, @byteOffsetOf(Linear, "ram_echo")); std.testing.expectEqual(0xFE00, @byteOffsetOf(Linear, "oam")); std.testing.expectEqual(0xFF00, @byteOffsetOf(Linear, "io")); std.testing.expectEqual(0xFF80, @byteOffsetOf(Linear, "high_ram")); std.testing.expectEqual(0xFFFF, @byteOffsetOf(Linear, "interrupt_enable")); } fn ptrOffsetOf(ref: anytype, target: anytype) usize { return @ptrToInt(target) - @ptrToInt(ref); } test "Io offsets" { var mmu: Mmu = undefined; std.testing.expectEqual(@as(usize, 0xFF04), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.timer)); std.testing.expectEqual(@as(usize, 0xFF0F), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.IF)); std.testing.expectEqual(@as(usize, 0xFF10), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.audio.NR10)); std.testing.expectEqual(@as(usize, 0xFF1E), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.audio.NR34)); std.testing.expectEqual(@as(usize, 0xFF20), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.audio.NR41)); std.testing.expectEqual(@as(usize, 0xFF26), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.audio.NR52)); std.testing.expectEqual(@as(usize, 0xFF30), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.audio.wave_pattern)); std.testing.expectEqual(@as(usize, 0xFF40), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.video.LCDC)); std.testing.expectEqual(@as(usize, 0xFF49), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.video.OBP1)); std.testing.expectEqual(@as(usize, 0xFF4A), ptrOffsetOf(&mmu.dyn, &mmu.dyn.io.video.WY)); } const CartHeaderError = error{ CartTypeError, RomSizeError, RamSizeError, }; const RomSize = enum(u8) { _32k = 0, _64k = 1, _128k = 2, _256k = 3, _512k = 4, _1m = 5, _2m = 6, _4m = 7, _8m = 8, pub fn init(raw: u8) !RomSize { return std.meta.intToEnum(RomSize, raw) catch error.RomSizeError; } pub fn bytes(self: RomSize) usize { return switch (self) { ._32k => 32 * 1024, ._64k => 64 * 1024, ._128k => 128 * 1024, ._256k => 256 * 1024, ._512k => 512 * 1024, ._1m => 1024 * 1024, ._2m => 2 * 1024 * 1024, ._4m => 4 * 1024 * 1024, ._8m => 8 * 1024 * 1024, }; } }; const RamSize = enum(u8) { _0 = 0, _2k = 1, _8k = 2, _32k = 3, _128k = 4, _64k = 5, }; pub const Mbc = enum { None, Mbc1, Mbc3, Mbc5, }; pub fn reset(self: *Mmu) void { // @memset(@ptrCast([*]u8, &self.io), 0, @sizeOf(@typeOf(self.io))); @memset(@ptrCast([*]u8, &self.dyn.vram), 0, 0x8000); } pub fn load(self: *Mmu, cart: []const u8) CartHeaderError!void { const size = try RomSize.init(cart[0x148]); if (cart.len != size.bytes()) { return error.RomSizeError; } self.cart_meta = switch (cart[0x147]) { 0x00 => .{ .mbc = .None }, 0x01 => .{ .mbc = .Mbc1 }, 0x02 => .{ .mbc = .Mbc1, .ram = true }, 0x03 => .{ .mbc = .Mbc1, .ram = true, .battery = true }, 0x0F => .{ .mbc = .Mbc3, .timer = true, .battery = true }, 0x10 => .{ .mbc = .Mbc3, .timer = true, .ram = true, .battery = true }, 0x11 => .{ .mbc = .Mbc3 }, 0x12 => .{ .mbc = .Mbc3, .ram = true }, 0x13 => .{ .mbc = .Mbc3, .ram = true, .battery = true }, 0x19 => .{ .mbc = .Mbc5 }, 0x1A => .{ .mbc = .Mbc5, .ram = true }, 0x1B => .{ .mbc = .Mbc5, .ram = true, .battery = true }, 0x1C => .{ .mbc = .Mbc5, .rumble = true }, 0x1D => .{ .mbc = .Mbc5, .rumble = true, .ram = true }, 0x1E => .{ .mbc = .Mbc5, .rumble = true, .ram = true, .battery = true }, else => return error.CartTypeError, }; // TODO: validate RAM self.cart = cart; self.bank = 1; std.mem.copy(u8, &self.dyn.rom, Bootloaders.dmg); std.mem.copy(u8, self.dyn.rom[Bootloaders.len..], cart[Bootloaders.len..0x8000]); } pub fn loadBootloader(self: *Mmu, bootloader: *const [0x100]u8) void { std.mem.copy(u8, &self.dyn.rom, bootloader); } pub fn instrBytes(self: Mmu, addr: u16) [3]u8 { return std.mem.asBytes(&self.dyn)[addr..][0..3].*; } pub fn get(self: Mmu, addr: u16) u8 { return std.mem.asBytes(&self.dyn)[addr]; } pub fn set(self: *Mmu, addr: u16, val: u8) void { if (addr < BEYOND_CART) { return @call(Fundude.profiling_call, self.setRom, .{ @intCast(u15, addr), val }); } const bytes = std.mem.asBytes(&self.dyn); const old = bytes[addr]; if (old == val) return; bytes[addr] = val; // TODO: replace magic with sibling references const fd = @fieldParentPtr(Fundude, "mmu", self); switch (addr) { 0x8000...0xA000 - 1 => fd.video.updatedVram(self, addr, val), 0xC000...0xDE00 - 1 => self.dyn.ram_echo[addr - 0xC000] = val, // Echo of 8kB Internal RAM 0xE000...0xFE00 - 1 => self.dyn.ram[addr - 0xE000] = val, // Echo of 8kB Internal RAM 0xFE00...0xFEA0 - 1 => fd.video.updatedOam(self, addr, val), 0xFF00 => fd.inputs.sync(self), 0xFF40...0xFF4C - 1 => fd.video.updatedIo(self, addr, val), 0xFF50 => std.mem.copy(u8, &self.dyn.rom, self.cart[0..Bootloaders.len]), else => {}, } } test "RAM echo" { var mmu: Mmu = undefined; mmu.set(0xC000, 'A'); std.testing.expectEqual(@as(u8, 'A'), mmu.get(0xE000)); mmu.set(0xC000, 'z'); std.testing.expectEqual(@as(u8, 'z'), mmu.get(0xE000)); mmu.set(0xC777, '?'); std.testing.expectEqual(@as(u8, '?'), mmu.get(0xE777)); // Don't echo OAM mmu.set(0xFE00, 69); mmu.set(0xDE00, 123); std.testing.expectEqual(@as(u8, 69), mmu.get(0xFE00)); } // TODO: RAM banking fn setRom(self: *Mmu, addr: u15, val: u8) void { switch (self.cart_meta.mbc) { .None => {}, .Mbc1 => { switch (addr) { 0x0000...0x1FFF => {}, // RAM enable 0x2000...0x3FFF => { var bank = val & 0x7F; if (bank % 0x20 == 0) { bank += 1; } self.selectRomBank(bank); }, 0x4000...0x5FFF => {}, // RAM bank 0x6000...0x7FFF => {}, // ROM/RAM Mode Select } }, .Mbc3 => { switch (addr) { 0x0000...0x1FFF => {}, // RAM/Timer enable 0x2000...0x3FFF => { const bank = std.math.max(1, val & 0x7F); self.selectRomBank(bank); }, 0x4000...0x5FFF => {}, // RAM bank 0x6000...0x7FFF => {}, // Latch clock } }, .Mbc5 => { switch (addr) { 0x0000...0x1FFF => {}, // RAM enable 0x2000...0x2FFF => { const mask = @as(u9, 1) << 8; const bank = (self.bank & mask) | val; self.selectRomBank(bank); }, 0x3000...0x3FFF => { const mask = @as(u9, 1) << 8; const bank = (@as(u9, val) << 8) | (self.bank & ~mask); self.selectRomBank(bank); }, 0x4000...0x5FFF => {}, // RAM bank 0x6000...0x7FFF => {}, // Latch clock } }, } } fn selectRomBank(self: *Mmu, bank: u9) void { const total_banks = self.cart.len / BANK_SIZE; const target = std.math.min(bank, total_banks); if (self.bank == bank) return; self.bank = bank; const offset = @as(usize, BANK_SIZE) * bank; // std.mem.copy(u8, self.dyn.rom[BANK_SIZE..], self.cart[offset..][0..BANK_SIZE]); // Not sure why Zig isn't rolling these up -- manually convert to 8 byte copies instead std.mem.copy( u64, @alignCast(8, std.mem.bytesAsSlice(u64, self.dyn.rom[BANK_SIZE..])), @alignCast(8, std.mem.bytesAsSlice(u64, self.cart[offset..][0..BANK_SIZE])), ); } pub const Bootloaders = struct { const len = 0x100; pub const dmg = &[len]u8{ 0x31, 0xFE, 0xFF, 0xAF, 0x21, 0xFF, 0x9F, 0x32, 0xCB, 0x7C, 0x20, 0xFB, 0x21, 0x26, 0xFF, 0x0E, 0x11, 0x3E, 0x80, 0x32, 0xE2, 0x0C, 0x3E, 0xF3, 0xE2, 0x32, 0x3E, 0x77, 0x77, 0x3E, 0xFC, 0xE0, 0x47, 0x11, 0x04, 0x01, 0x21, 0x10, 0x80, 0x1A, 0xCD, 0x95, 0x00, 0xCD, 0x96, 0x00, 0x13, 0x7B, 0xFE, 0x34, 0x20, 0xF3, 0x11, 0xD8, 0x00, 0x06, 0x08, 0x1A, 0x13, 0x22, 0x23, 0x05, 0x20, 0xF9, 0x3E, 0x19, 0xEA, 0x10, 0x99, 0x21, 0x2F, 0x99, 0x0E, 0x0C, 0x3D, 0x28, 0x08, 0x32, 0x0D, 0x20, 0xF9, 0x2E, 0x0F, 0x18, 0xF3, 0x67, 0x3E, 0x64, 0x57, 0xE0, 0x42, 0x3E, 0x91, 0xE0, 0x40, 0x04, 0x1E, 0x02, 0x0E, 0x0C, 0xF0, 0x44, 0xFE, 0x90, 0x20, 0xFA, 0x0D, 0x20, 0xF7, 0x1D, 0x20, 0xF2, 0x0E, 0x13, 0x24, 0x7C, 0x1E, 0x83, 0xFE, 0x62, 0x28, 0x06, 0x1E, 0xC1, 0xFE, 0x64, 0x20, 0x06, 0x7B, 0xE2, 0x0C, 0x3E, 0x87, 0xE2, 0xF0, 0x42, 0x90, 0xE0, 0x42, 0x15, 0x20, 0xD2, 0x05, 0x20, 0x4F, 0x16, 0x20, 0x18, 0xCB, 0x4F, 0x06, 0x04, 0xC5, 0xCB, 0x11, 0x17, 0xC1, 0xCB, 0x11, 0x17, 0x05, 0x20, 0xF5, 0x22, 0x23, 0x22, 0x23, 0xC9, 0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B, 0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E, 0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99, 0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC, 0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E, 0x3C, 0x42, 0xB9, 0xA5, 0xB9, 0xA5, 0x42, 0x3C, 0x21, 0x04, 0x01, 0x11, 0xA8, 0x00, 0x1A, 0x13, 0xBE, 0x20, 0xFE, 0x23, 0x7D, 0xFE, 0x34, 0x20, 0xF5, 0x06, 0x19, 0x78, 0x86, 0x23, 0x05, 0x20, 0xFB, 0x86, 0x20, 0xFE, 0x3E, 0x01, 0xE0, 0x50, }; pub const mini = &[len]u8{ 0xF3, 0xAF, 0xE0, 0x40, 0xE0, 0x26, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x01, 0xE0, 0x50, }; };
src/Mmu.zig
pub const struct_SceNetMallocStat = extern struct { pool: c_int, maximum: c_int, free: c_int, }; pub const SceNetMallocStat = struct_SceNetMallocStat; pub extern fn sceNetInit(poolsize: c_int, calloutprio: c_int, calloutstack: c_int, netintrprio: c_int, netintrstack: c_int) c_int; pub extern fn sceNetTerm() c_int; pub extern fn sceNetFreeThreadinfo(thid: c_int) c_int; pub extern fn sceNetThreadAbort(thid: c_int) c_int; pub extern fn sceNetEtherStrton(name: [*c]u8, mac: [*c]u8) void; pub extern fn sceNetEtherNtostr(mac: [*c]u8, name: [*c]u8) void; pub extern fn sceNetGetLocalEtherAddr(mac: [*c]u8) c_int; pub extern fn sceNetGetMallocStat(stat: [*c]SceNetMallocStat) c_int; pub extern fn sceNetAdhocInit() c_int; pub extern fn sceNetAdhocTerm() c_int; pub extern fn sceNetAdhocPdpCreate(mac: [*c]u8, port: c_ushort, bufsize: c_uint, unk1: c_int) c_int; pub extern fn sceNetAdhocPdpDelete(id: c_int, unk1: c_int) c_int; pub extern fn sceNetAdhocPdpSend(id: c_int, destMacAddr: [*c]u8, port: c_ushort, data: ?*c_void, len: c_uint, timeout: c_uint, nonblock: c_int) c_int; pub extern fn sceNetAdhocPdpRecv(id: c_int, srcMacAddr: [*c]u8, port: [*c]c_ushort, data: ?*c_void, dataLength: ?*c_void, timeout: c_uint, nonblock: c_int) c_int; pub const struct_pdpStatStruct = extern struct { next: [*c]struct_pdpStatStruct, pdpId: c_int, mac: [6]u8, port: c_ushort, rcvdData: c_uint, }; pub const pdpStatStruct = struct_pdpStatStruct; pub extern fn sceNetAdhocGetPdpStat(size: [*c]c_int, stat: [*c]pdpStatStruct) c_int; pub extern fn sceNetAdhocGameModeCreateMaster(data: ?*c_void, size: c_int) c_int; pub extern fn sceNetAdhocGameModeCreateReplica(mac: [*c]u8, data: ?*c_void, size: c_int) c_int; pub extern fn sceNetAdhocGameModeUpdateMaster() c_int; pub extern fn sceNetAdhocGameModeUpdateReplica(id: c_int, unk1: c_int) c_int; pub extern fn sceNetAdhocGameModeDeleteMaster() c_int; pub extern fn sceNetAdhocGameModeDeleteReplica(id: c_int) c_int; pub extern fn sceNetAdhocPtpOpen(srcmac: [*c]u8, srcport: c_ushort, destmac: [*c]u8, destport: c_ushort, bufsize: c_uint, delay: c_uint, count: c_int, unk1: c_int) c_int; pub extern fn sceNetAdhocPtpConnect(id: c_int, timeout: c_uint, nonblock: c_int) c_int; pub extern fn sceNetAdhocPtpListen(srcmac: [*c]u8, srcport: c_ushort, bufsize: c_uint, delay: c_uint, count: c_int, queue: c_int, unk1: c_int) c_int; pub extern fn sceNetAdhocPtpAccept(id: c_int, mac: [*c]u8, port: [*c]c_ushort, timeout: c_uint, nonblock: c_int) c_int; pub extern fn sceNetAdhocPtpSend(id: c_int, data: ?*c_void, datasize: [*c]c_int, timeout: c_uint, nonblock: c_int) c_int; pub extern fn sceNetAdhocPtpRecv(id: c_int, data: ?*c_void, datasize: [*c]c_int, timeout: c_uint, nonblock: c_int) c_int; pub extern fn sceNetAdhocPtpFlush(id: c_int, timeout: c_uint, nonblock: c_int) c_int; pub extern fn sceNetAdhocPtpClose(id: c_int, unk1: c_int) c_int; pub const struct_ptpStatStruct = extern struct { next: [*c]struct_ptpStatStruct, ptpId: c_int, mac: [6]u8, peermac: [6]u8, port: c_ushort, peerport: c_ushort, sentData: c_uint, rcvdData: c_uint, unk1: c_int, }; pub const ptpStatStruct = struct_ptpStatStruct; pub extern fn sceNetAdhocGetPtpStat(size: [*c]c_int, stat: [*c]ptpStatStruct) c_int; pub const struct_productStruct = extern struct { unknown: c_int, product: [9]u8, unk: [3]u8, }; pub const struct_SceNetAdhocctlPeerInfo = extern struct { next: [*c]struct_SceNetAdhocctlPeerInfo, nickname: [128]u8, mac: [6]u8, unknown: [6]u8, timestamp: c_ulong, }; pub const struct_SceNetAdhocctlScanInfo = extern struct { next: [*c]struct_SceNetAdhocctlScanInfo, channel: c_int, name: [8]u8, bssid: [6]u8, unknown: [2]u8, unknown2: c_int, }; pub const struct_SceNetAdhocctlGameModeInfo = extern struct { count: c_int, macs: [16][6]u8, }; pub const struct_SceNetAdhocctlParams = extern struct { channel: c_int, name: [8]u8, bssid: [6]u8, nickname: [128]u8, }; pub extern fn sceNetAdhocctlInit(stacksize: c_int, priority: c_int, product: [*c]struct_productStruct) c_int; pub extern fn sceNetAdhocctlTerm() c_int; pub extern fn sceNetAdhocctlConnect(name: [*c]const u8) c_int; pub extern fn sceNetAdhocctlDisconnect() c_int; pub extern fn sceNetAdhocctlGetState(event: [*c]c_int) c_int; pub extern fn sceNetAdhocctlCreate(name: [*c]const u8) c_int; pub extern fn sceNetAdhocctlJoin(scaninfo: [*c]struct_SceNetAdhocctlScanInfo) c_int; pub extern fn sceNetAdhocctlGetAdhocId(product: [*c]struct_productStruct) c_int; pub extern fn sceNetAdhocctlCreateEnterGameMode(name: [*c]const u8, unknown: c_int, num: c_int, macs: [*c]u8, timeout: c_uint, unknown2: c_int) c_int; pub extern fn sceNetAdhocctlJoinEnterGameMode(name: [*c]const u8, hostmac: [*c]u8, timeout: c_uint, unknown: c_int) c_int; pub extern fn sceNetAdhocctlGetGameModeInfo(gamemodeinfo: [*c]struct_SceNetAdhocctlGameModeInfo) c_int; pub extern fn sceNetAdhocctlExitGameMode() c_int; pub extern fn sceNetAdhocctlGetPeerList(length: [*c]c_int, buf: ?*c_void) c_int; pub extern fn sceNetAdhocctlGetPeerInfo(mac: [*c]u8, size: c_int, peerinfo: [*c]struct_SceNetAdhocctlPeerInfo) c_int; pub extern fn sceNetAdhocctlScan() c_int; pub extern fn sceNetAdhocctlGetScanInfo(length: [*c]c_int, buf: ?*c_void) c_int; pub const sceNetAdhocctlHandler = ?fn (c_int, c_int, ?*c_void) callconv(.C) void; pub extern fn sceNetAdhocctlAddHandler(handler: sceNetAdhocctlHandler, unknown: ?*c_void) c_int; pub extern fn sceNetAdhocctlDelHandler(id: c_int) c_int; pub extern fn sceNetAdhocctlGetNameByAddr(mac: [*c]u8, nickname: [*c]u8) c_int; pub extern fn sceNetAdhocctlGetAddrByName(nickname: [*c]u8, length: [*c]c_int, buf: ?*c_void) c_int; pub extern fn sceNetAdhocctlGetParameter(params: [*c]struct_SceNetAdhocctlParams) c_int; pub const enum_pspAdhocMatchingEvents = extern enum(c_int) { PSP_ADHOC_MATCHING_EVENT_HELLO = 1, PSP_ADHOC_MATCHING_EVENT_JOIN = 2, PSP_ADHOC_MATCHING_EVENT_LEFT = 3, PSP_ADHOC_MATCHING_EVENT_REJECT = 4, PSP_ADHOC_MATCHING_EVENT_CANCEL = 5, PSP_ADHOC_MATCHING_EVENT_ACCEPT = 6, PSP_ADHOC_MATCHING_EVENT_COMPLETE = 7, PSP_ADHOC_MATCHING_EVENT_TIMEOUT = 8, PSP_ADHOC_MATCHING_EVENT_ERROR = 9, PSP_ADHOC_MATCHING_EVENT_DISCONNECT = 10, PSP_ADHOC_MATCHING_EVENT_DATA = 11, PSP_ADHOC_MATCHING_EVENT_DATA_CONFIRM = 12, PSP_ADHOC_MATCHING_EVENT_DATA_TIMEOUT = 13, _, }; pub const enum_pspAdhocMatchingModes = extern enum(c_int) { PSP_ADHOC_MATCHING_MODE_HOST = 1, PSP_ADHOC_MATCHING_MODE_CLIENT = 2, PSP_ADHOC_MATCHING_MODE_PTP = 3, _, }; pub const struct_pspAdhocMatchingMember = extern struct { next: [*c]struct_pspAdhocMatchingMember, mac: [6]u8, unknown: [2]u8, }; pub const struct_pspAdhocPoolStat = extern struct { size: c_int, maxsize: c_int, freesize: c_int, }; pub extern fn sceNetAdhocMatchingInit(memsize: c_int) c_int; pub extern fn sceNetAdhocMatchingTerm() c_int; pub const pspAdhocMatchingCallback = ?fn (c_int, c_int, [*c]u8, c_int, ?*c_void) callconv(.C) void; pub extern fn sceNetAdhocMatchingCreate(mode: c_int, maxpeers: c_int, port: c_ushort, bufsize: c_int, hellodelay: c_uint, pingdelay: c_uint, initcount: c_int, msgdelay: c_uint, callback: pspAdhocMatchingCallback) c_int; pub extern fn sceNetAdhocMatchingDelete(matchingid: c_int) c_int; pub extern fn sceNetAdhocMatchingStart(matchingid: c_int, evthpri: c_int, evthstack: c_int, inthpri: c_int, inthstack: c_int, optlen: c_int, optdata: ?*c_void) c_int; pub extern fn sceNetAdhocMatchingStop(matchingid: c_int) c_int; pub extern fn sceNetAdhocMatchingSelectTarget(matchingid: c_int, mac: [*c]u8, optlen: c_int, optdata: ?*c_void) c_int; pub extern fn sceNetAdhocMatchingCancelTarget(matchingid: c_int, mac: [*c]u8) c_int; pub extern fn sceNetAdhocMatchingCancelTargetWithOpt(matchingid: c_int, mac: [*c]u8, optlen: c_int, optdata: ?*c_void) c_int; pub extern fn sceNetAdhocMatchingSendData(matchingid: c_int, mac: [*c]u8, datalen: c_int, data: ?*c_void) c_int; pub extern fn sceNetAdhocMatchingAbortSendData(matchingid: c_int, mac: [*c]u8) c_int; pub extern fn sceNetAdhocMatchingSetHelloOpt(matchingid: c_int, optlen: c_int, optdata: ?*c_void) c_int; pub extern fn sceNetAdhocMatchingGetHelloOpt(matchingid: c_int, optlen: [*c]c_int, optdata: ?*c_void) c_int; pub extern fn sceNetAdhocMatchingGetMembers(matchingid: c_int, length: [*c]c_int, buf: ?*c_void) c_int; pub extern fn sceNetAdhocMatchingGetPoolMaxAlloc() c_int; pub extern fn sceNetAdhocMatchingGetPoolStat(poolstat: [*c]struct_pspAdhocPoolStat) c_int; pub const union_SceNetApctlInfo = extern union { name: [64]u8, bssid: [6]u8, ssid: [32]u8, ssidLength: c_uint, securityType: c_uint, strength: u8, channel: u8, powerSave: u8, ip: [16]u8, subNetMask: [16]u8, gateway: [16]u8, primaryDns: [16]u8, secondaryDns: [16]u8, useProxy: c_uint, proxyUrl: [128]u8, proxyPort: c_ushort, eapType: c_uint, startBrowser: c_uint, wifisp: c_uint, }; pub const sceNetApctlHandler = ?fn (c_int, c_int, c_int, c_int, ?*c_void) callconv(.C) void; pub extern fn sceNetApctlInit(stackSize: c_int, initPriority: c_int) c_int; pub extern fn sceNetApctlTerm() c_int; pub extern fn sceNetApctlGetInfo(code: c_int, pInfo: [*c]union_SceNetApctlInfo) c_int; pub extern fn sceNetApctlAddHandler(handler: sceNetApctlHandler, pArg: ?*c_void) c_int; pub extern fn sceNetApctlDelHandler(handlerId: c_int) c_int; pub extern fn sceNetApctlConnect(connIndex: c_int) c_int; pub extern fn sceNetApctlDisconnect() c_int; pub extern fn sceNetApctlGetState(pState: [*c]c_int) c_int; pub extern fn sceNetInetInit() c_int; pub extern fn sceNetInetTerm() c_int; pub const ApctlState = extern enum(c_int) { Disconnected, Scanning, Joining, GettingIp, GotIp, EapAuth, KeyExchange, }; pub const ApctlEvent = extern enum(c_int) { ConnectRequest, ScanRequest, ScanComplete, Established, GetIp, DisconnectRequest, Error, Info, EapAuth, KeyExchange, Reconnect, }; pub const ApctlInfo = extern enum(c_int) { ProfileName, Bssid, Ssid, SsidLength, SecurityType, Strength, Channel, PowerSave, Ip, SubnetMask, Gateway, PrimaryDns, SecondaryDns, UseProxy, ProxyUrl, ProxyPort, EapType, StartBrowser, Wifisp, }; pub const ApctlInfoSecurityType = extern enum(c_int) { None, Wep, Wpa, }; pub const productStruct = struct_productStruct; pub const SceNetAdhocctlPeerInfo = struct_SceNetAdhocctlPeerInfo; pub const SceNetAdhocctlScanInfo = struct_SceNetAdhocctlScanInfo; pub const SceNetAdhocctlGameModeInfo = struct_SceNetAdhocctlGameModeInfo; pub const SceNetAdhocctlParams = struct_SceNetAdhocctlParams; pub const pspAdhocMatchingEvents = enum_pspAdhocMatchingEvents; pub const pspAdhocMatchingModes = enum_pspAdhocMatchingModes; pub const pspAdhocMatchingMember = struct_pspAdhocMatchingMember; pub const pspAdhocPoolStat = struct_pspAdhocPoolStat; pub const SceNetApctlInfo = union_SceNetApctlInfo; pub const socklen_t = u32; pub const sa_family_t = u8; pub const struct_sockaddr = extern struct { sa_len: u8, sa_family: sa_family_t, sa_data: [14]u8, }; pub const sockaddr = struct_sockaddr; pub extern fn sceNetInetAccept(s: c_int, addr: [*c]struct_sockaddr, addrlen: [*c]socklen_t) c_int; pub extern fn sceNetInetBind(s: c_int, my_addr: [*c]const struct_sockaddr, addrlen: socklen_t) c_int; pub extern fn sceNetInetConnect(s: c_int, serv_addr: [*c]const struct_sockaddr, addrlen: socklen_t) c_int; pub extern fn sceNetInetGetsockopt(s: c_int, level: c_int, optname: c_int, optval: ?*c_void, optlen: [*c]socklen_t) c_int; pub extern fn sceNetInetListen(s: c_int, backlog: c_int) c_int; pub extern fn sceNetInetRecv(s: c_int, buf: ?*c_void, len: u32, flags: c_int) u32; pub extern fn sceNetInetRecvfrom(s: c_int, buf: ?*c_void, flags: u32, c_int, from: [*c]struct_sockaddr, fromlen: [*c]socklen_t) u32; pub extern fn sceNetInetSend(s: c_int, buf: ?*const c_void, len: u32, flags: c_int) u32; pub extern fn sceNetInetSendto(s: c_int, buf: ?*const c_void, len: u32, flags: c_int, to: [*c]const struct_sockaddr, tolen: socklen_t) u32; pub extern fn sceNetInetSetsockopt(s: c_int, level: c_int, optname: c_int, optval: ?*const c_void, optlen: socklen_t) c_int; pub extern fn sceNetInetShutdown(s: c_int, how: c_int) c_int; pub extern fn sceNetInetSocket(domain: c_int, type: c_int, protocol: c_int) c_int; pub extern fn sceNetInetClose(s: c_int) c_int; pub extern fn sceNetInetGetErrno() c_int; pub const in_addr_t = u32; pub const struct_in_addr = packed struct { s_addr: in_addr_t, }; pub extern fn sceNetResolverInit() c_int; pub extern fn sceNetResolverCreate(rid: [*c]c_int, buf: ?*c_void, buflen: SceSize) c_int; pub extern fn sceNetResolverDelete(rid: c_int) c_int; pub extern fn sceNetResolverStartNtoA(rid: c_int, hostname: [*c]const u8, addr: [*c]struct_in_addr, timeout: c_uint, retry: c_int) c_int; pub extern fn sceNetResolverStartAtoN(rid: c_int, addr: [*c]const struct_in_addr, hostname: [*c]u8, hostname_len: SceSize, timeout: c_uint, retry: c_int) c_int; pub extern fn sceNetResolverStop(rid: c_int) c_int; pub extern fn sceNetResolverTerm() c_int;
src/psp/sdk/pspnet.zig
const std = @import("std"); const upaya = @import("upaya"); usingnamespace upaya.imgui; pub const SlideList = std.ArrayList(*Slide); pub const SlideShow = struct { slides: SlideList = undefined, // defaults that can be overridden while parsing default_font: []const u8 = "assets/Calibri Regular.ttf", default_font_bold: []const u8 = "assets/Calibri Regular.ttf", default_font_italic: []const u8 = "assets/Calibri Regular.ttf", default_font_bold_italic: []const u8 = "assets/Calibri Regular.ttf", default_fontsize: i32 = 16, default_underline_width: i32 = 1, default_color: ImVec4 = .{ .w = 0.9 }, default_bullet_color: ImVec4 = .{ .x = 1, .w = 1 }, default_bullet_symbol: []const u8 = ">", // TODO: maybe later: font encountered while parsing fonts: std.ArrayList([]u8) = undefined, fontsizes: std.ArrayList(i32) = undefined, pub fn new(a: *std.mem.Allocator) !*SlideShow { var self = try a.create(SlideShow); self.* = .{}; self.slides = SlideList.init(a); // TODO: init font, fontsize arraylists return self; } pub fn deinit(self: *SlideShow) void { self.slides.deinit(); } }; // . // Slides // . pub const Slide = struct { pos_in_editor: usize = 0, line_in_editor: usize = 0, // TODO: don't we want to store pointers? items: std.ArrayList(SlideItem) = undefined, fontsize: i32 = 16, text_color: ImVec4 = .{ .w = 1 }, bullet_color: ImVec4 = ImVec4{ .x = 1, .w = 1 }, bullet_symbol: ?[]const u8 = null, underline_width: i32 = 1, // . pub fn new(a: *std.mem.Allocator) !*Slide { var self = try a.create(Slide); self.* = .{}; self.items = std.ArrayList(SlideItem).init(a); return self; } pub fn deinit(self: *Slide) void { self.items.deinit(); } pub fn applyContext(self: *Slide, ctx: *ItemContext) void { if (ctx.fontSize) |fs| self.fontsize = fs; if (ctx.color) |col| self.text_color = col; if (ctx.bullet_color) |bul| self.bullet_color = bul; if (ctx.underline_width) |uw| self.underline_width = uw; if (ctx.bullet_symbol) |bs| self.bullet_symbol = bs; } pub fn fromSlide(orig: *Slide, a: *std.mem.Allocator) !*Slide { var n = try new(a); try n.items.appendSlice(orig.items.items); return n; } }; pub const SlideItemKind = enum { background, textbox, img, }; pub const SlideItemError = error{ TextNull, ImgPathNull, FontSizeNull, ColorNull, UnderlineWidthNull, BulletColorNull, BulletSymbolNull, }; pub const SlideItem = struct { kind: SlideItemKind = .background, text: ?[]const u8 = null, fontSize: ?i32 = null, color: ?ImVec4 = ImVec4{}, img_path: ?[]const u8 = null, position: ImVec2 = ImVec2{}, size: ImVec2 = ImVec2{}, underline_width: ?i32 = null, bullet_color: ?ImVec4 = null, bullet_symbol: ?[]const u8 = null, pub fn new(a: *std.mem.Allocator) !*SlideItem { var self = try a.create(SlideItem); self.* = .{}; return self; } pub fn deinit(self: *Slide) void { // empty } pub fn applyContext(self: *SlideItem, context: ItemContext) void { if (context.text) |text| self.text = text; if (context.img_path) |img_path| self.img_path = img_path; if (context.fontSize) |fontsize| self.fontSize = fontsize; if (context.color) |color| self.color = color; if (context.position) |position| self.position = position; if (context.size) |size| self.size = size; if (context.underline_width) |w| self.underline_width = w; if (context.bullet_color) |color| self.bullet_color = color; if (context.bullet_symbol) |symbol| self.bullet_symbol = symbol; } pub fn applySlideDefaultsIfNecessary(self: *SlideItem, slide: *Slide) void { if (self.fontSize == null) self.fontSize = slide.fontsize; if (self.color == null) self.color = slide.text_color; if (self.underline_width == null) self.underline_width = slide.underline_width; if (self.bullet_color == null) self.bullet_color = slide.bullet_color; if (self.bullet_symbol == null) self.bullet_symbol = slide.bullet_symbol; } pub fn applySlideShowDefaultsIfNecessary(self: *SlideItem, slideshow: *SlideShow) void { if (self.fontSize == null) { self.fontSize = slideshow.default_fontsize; } if (self.color == null) { self.color = slideshow.default_color; } // TODO: BUG BUG compiler BUG ?!?!?!?!?! // if(self.underline_width == null) { A } else { B } // does not work. Even when it is null, the B branch is always executed // -- I am not sure whether it is really a bug or if I just got the concept // of optionals wrong back then if (self.underline_width) |w| {} else { self.underline_width = slideshow.default_underline_width; } if (self.bullet_color) |bc| {} else { self.bullet_color = slideshow.default_bullet_color; } if (self.bullet_symbol) |bs| {} else { self.bullet_symbol = slideshow.default_bullet_symbol; } } pub fn sanityCheck(self: *SlideItem) SlideItemError!void { if (self.text == null and self.kind == .textbox) return SlideItemError.TextNull; if (self.fontSize == null and self.kind == .textbox) return SlideItemError.FontSizeNull; if (self.color == null and self.kind == .textbox) return SlideItemError.ColorNull; if (self.underline_width == null and self.kind == .textbox) return SlideItemError.UnderlineWidthNull; if (self.bullet_color == null and self.kind == .textbox) return SlideItemError.BulletColorNull; if (self.bullet_symbol == null and self.kind == .textbox) return SlideItemError.BulletSymbolNull; if (self.img_path == null and (self.kind == .img or self.kind == .background)) return SlideItemError.ImgPathNull; } pub fn printToLog(self: *const SlideItem) void { const indent = " "; switch (self.kind) { .background => { std.log.info(indent ++ "Kind: Background", .{}); if (self.img_path) |img| { std.log.info(indent ++ " img: {any}", .{self.img_path}); std.log.info(indent ++ " pos: {any}", .{self.position}); std.log.info(indent ++ " size: {any}", .{self.size}); } else { std.log.info(indent ++ " color: {any}", .{self.color}); } }, .img => { std.log.info(indent ++ "Kind: Image", .{}); std.log.info(indent ++ " img: {any}", .{self.img_path}); std.log.info(indent ++ " pos: {any}", .{self.position}); std.log.info(indent ++ " size: {any}", .{self.size}); }, .textbox => { std.log.info(indent ++ "Kind: TextBox", .{}); std.log.info(indent ++ " pos: {any}", .{self.position}); std.log.info(indent ++ " size: {any}", .{self.size}); if (self.text) |text| { std.log.info(indent ++ " text:({d}) `{s}`", .{ std.mem.len(text), text }); } else { std.log.info(indent ++ " text: (null)", .{}); } std.log.info(indent ++ " fsize: {any}", .{self.fontSize}); std.log.info(indent ++ "uwidth: {any}", .{self.underline_width}); std.log.info(indent ++ "bcolor: {any}", .{self.bullet_color}); std.log.info(indent ++ "bsymbl: {any}", .{self.bullet_symbol}); }, } std.log.info(indent ++ "-----------------------", .{}); } }; pub const ItemContext = struct { directive: []const u8 = undefined, // @push, @slide, ... context_name: ?[]const u8 = null, text: ?[]const u8 = null, fontSize: ?i32 = null, color: ?ImVec4 = null, img_path: ?[]const u8 = null, position: ?ImVec2 = null, size: ?ImVec2 = null, underline_width: ?i32 = null, bullet_color: ?ImVec4 = null, bullet_symbol: ?[]const u8 = null, line_number: usize = 0, line_offset: usize = 0, pub fn applyOtherIfNull(self: *ItemContext, other: ItemContext) void { if (self.text == null) { if (other.text) |text| self.text = text; } if (self.img_path == null) { if (other.img_path) |img_path| self.img_path = img_path; } if (self.fontSize == null) { if (other.fontSize) |fontsize| self.fontSize = fontsize; } if (self.color == null) { if (other.color) |color| self.color = color; } if (self.position == null) { if (other.position) |position| self.position = position; } if (self.size == null) { if (other.size) |size| self.size = size; } if (self.underline_width == null) { if (other.underline_width) |w| self.underline_width = w; } if (self.bullet_color == null) { if (other.bullet_color) |color| self.bullet_color = color; } if (self.bullet_symbol == null) { if (other.bullet_symbol) |symbol| self.bullet_symbol = symbol; } } };
src/slides.zig
const std = @import("std"); const vk = @import("vulkan"); const c = @import("c.zig"); const Allocator = std.mem.Allocator; const required_device_extensions = [_][]const u8{ vk.extension_info.khr_swapchain.name }; const BaseDispatch = struct { vkCreateInstance: vk.PfnCreateInstance, usingnamespace vk.BaseWrapper(@This()); }; const InstanceDispatch = struct { vkDestroyInstance: vk.PfnDestroyInstance, vkCreateDevice: vk.PfnCreateDevice, vkDestroySurfaceKHR: vk.PfnDestroySurfaceKHR, vkEnumeratePhysicalDevices: vk.PfnEnumeratePhysicalDevices, vkGetPhysicalDeviceProperties: vk.PfnGetPhysicalDeviceProperties, vkEnumerateDeviceExtensionProperties: vk.PfnEnumerateDeviceExtensionProperties, vkGetPhysicalDeviceSurfaceFormatsKHR: vk.PfnGetPhysicalDeviceSurfaceFormatsKHR, vkGetPhysicalDeviceSurfacePresentModesKHR: vk.PfnGetPhysicalDeviceSurfacePresentModesKHR, vkGetPhysicalDeviceSurfaceCapabilitiesKHR: vk.PfnGetPhysicalDeviceSurfaceCapabilitiesKHR, vkGetPhysicalDeviceQueueFamilyProperties: vk.PfnGetPhysicalDeviceQueueFamilyProperties, vkGetPhysicalDeviceSurfaceSupportKHR: vk.PfnGetPhysicalDeviceSurfaceSupportKHR, vkGetPhysicalDeviceMemoryProperties: vk.PfnGetPhysicalDeviceMemoryProperties, vkGetDeviceProcAddr: vk.PfnGetDeviceProcAddr, usingnamespace vk.InstanceWrapper(@This()); }; const DeviceDispatch = struct { vkDestroyDevice: vk.PfnDestroyDevice, vkGetDeviceQueue: vk.PfnGetDeviceQueue, vkCreateSemaphore: vk.PfnCreateSemaphore, vkCreateFence: vk.PfnCreateFence, vkCreateImageView: vk.PfnCreateImageView, vkDestroyImageView: vk.PfnDestroyImageView, vkDestroySemaphore: vk.PfnDestroySemaphore, vkDestroyFence: vk.PfnDestroyFence, vkGetSwapchainImagesKHR: vk.PfnGetSwapchainImagesKHR, vkCreateSwapchainKHR: vk.PfnCreateSwapchainKHR, vkDestroySwapchainKHR: vk.PfnDestroySwapchainKHR, vkAcquireNextImageKHR: vk.PfnAcquireNextImageKHR, vkDeviceWaitIdle: vk.PfnDeviceWaitIdle, vkWaitForFences: vk.PfnWaitForFences, vkResetFences: vk.PfnResetFences, vkQueueSubmit: vk.PfnQueueSubmit, vkQueuePresentKHR: vk.PfnQueuePresentKHR, vkCreateCommandPool: vk.PfnCreateCommandPool, vkDestroyCommandPool: vk.PfnDestroyCommandPool, vkAllocateCommandBuffers: vk.PfnAllocateCommandBuffers, vkFreeCommandBuffers: vk.PfnFreeCommandBuffers, vkQueueWaitIdle: vk.PfnQueueWaitIdle, vkCreateShaderModule: vk.PfnCreateShaderModule, vkDestroyShaderModule: vk.PfnDestroyShaderModule, vkCreatePipelineLayout: vk.PfnCreatePipelineLayout, vkDestroyPipelineLayout: vk.PfnDestroyPipelineLayout, vkCreateRenderPass: vk.PfnCreateRenderPass, vkDestroyRenderPass: vk.PfnDestroyRenderPass, vkCreateGraphicsPipelines: vk.PfnCreateGraphicsPipelines, vkDestroyPipeline: vk.PfnDestroyPipeline, vkCreateFramebuffer: vk.PfnCreateFramebuffer, vkDestroyFramebuffer: vk.PfnDestroyFramebuffer, vkBeginCommandBuffer: vk.PfnBeginCommandBuffer, vkEndCommandBuffer: vk.PfnEndCommandBuffer, vkAllocateMemory: vk.PfnAllocateMemory, vkFreeMemory: vk.PfnFreeMemory, vkCreateBuffer: vk.PfnCreateBuffer, vkDestroyBuffer: vk.PfnDestroyBuffer, vkGetBufferMemoryRequirements: vk.PfnGetBufferMemoryRequirements, vkMapMemory: vk.PfnMapMemory, vkUnmapMemory: vk.PfnUnmapMemory, vkBindBufferMemory: vk.PfnBindBufferMemory, vkCmdBeginRenderPass: vk.PfnCmdBeginRenderPass, vkCmdEndRenderPass: vk.PfnCmdEndRenderPass, vkCmdBindPipeline: vk.PfnCmdBindPipeline, vkCmdDraw: vk.PfnCmdDraw, vkCmdSetViewport: vk.PfnCmdSetViewport, vkCmdSetScissor: vk.PfnCmdSetScissor, vkCmdBindVertexBuffers: vk.PfnCmdBindVertexBuffers, vkCmdCopyBuffer: vk.PfnCmdCopyBuffer, usingnamespace vk.DeviceWrapper(@This()); }; pub const GraphicsContext = struct { vkb: BaseDispatch, vki: InstanceDispatch, vkd: DeviceDispatch, instance: vk.Instance, surface: vk.SurfaceKHR, pdev: vk.PhysicalDevice, props: vk.PhysicalDeviceProperties, mem_props: vk.PhysicalDeviceMemoryProperties, dev: vk.Device, graphics_queue: Queue, present_queue: Queue, pub fn init(allocator: *Allocator, app_name: [*:0]const u8, window: *c.GLFWwindow) !GraphicsContext { var self: GraphicsContext = undefined; self.vkb = try BaseDispatch.load(c.glfwGetInstanceProcAddress); var glfw_exts_count: u32 = 0; const glfw_exts = c.glfwGetRequiredInstanceExtensions(&glfw_exts_count); const app_info = vk.ApplicationInfo{ .p_application_name = app_name, .application_version = vk.makeVersion(0, 0, 0), .p_engine_name = app_name, .engine_version = vk.makeVersion(0, 0, 0), .api_version = vk.API_VERSION_1_2, }; self.instance = try self.vkb.createInstance(.{ .flags = .{}, .p_application_info = &app_info, .enabled_layer_count = 0, .pp_enabled_layer_names = undefined, .enabled_extension_count = glfw_exts_count, .pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, glfw_exts), }, null); self.vki = try InstanceDispatch.load(self.instance, c.glfwGetInstanceProcAddress); errdefer self.vki.destroyInstance(self.instance, null); self.surface = try createSurface(self.vki, self.instance, window); errdefer self.vki.destroySurfaceKHR(self.instance, self.surface, null); const candidate = try pickPhysicalDevice(self.vki, self.instance, allocator, self.surface); self.pdev = candidate.pdev; self.props = candidate.props; self.dev = try initializeCandidate(self.vki, candidate); self.vkd = try DeviceDispatch.load(self.dev, self.vki.vkGetDeviceProcAddr); errdefer self.vkd.destroyDevice(self.dev, null); self.graphics_queue = Queue.init(self.vkd, self.dev, candidate.queues.graphics_family); self.present_queue = Queue.init(self.vkd, self.dev, candidate.queues.graphics_family); self.mem_props = self.vki.getPhysicalDeviceMemoryProperties(self.pdev); return self; } pub fn deinit(self: GraphicsContext) void { self.vkd.destroyDevice(self.dev, null); self.vki.destroySurfaceKHR(self.instance, self.surface, null); self.vki.destroyInstance(self.instance, null); } pub fn deviceName(self: GraphicsContext) []const u8 { const len = std.mem.indexOfScalar(u8, &self.props.device_name, 0).?; return self.props.device_name[0 .. len]; } pub fn findMemoryTypeIndex(self: GraphicsContext, memory_type_bits: u32, flags: vk.MemoryPropertyFlags) !u32 { for (self.mem_props.memory_types[0 .. self.mem_props.memory_type_count]) |mem_type, i| { if (memory_type_bits & (@as(u32, 1) << @truncate(u5, i)) != 0 and mem_type.property_flags.contains(flags)) { return @truncate(u32, i); } } return error.NoSuitableMemoryType; } pub fn allocate(self: GraphicsContext, requirements: vk.MemoryRequirements, flags: vk.MemoryPropertyFlags) !vk.DeviceMemory { return try self.vkd.allocateMemory(self.dev, .{ .allocation_size = requirements.size, .memory_type_index = try self.findMemoryTypeIndex(requirements.memory_type_bits, flags), }, null); } }; pub const Queue = struct { handle: vk.Queue, family: u32, fn init(vkd: DeviceDispatch, dev: vk.Device, family: u32) Queue { return .{ .handle = vkd.getDeviceQueue(dev, family, 0), .family = family, }; } }; fn createSurface(vki: InstanceDispatch, instance: vk.Instance, window: *c.GLFWwindow) !vk.SurfaceKHR { var surface: vk.SurfaceKHR = undefined; if (c.glfwCreateWindowSurface(instance, window, null, &surface) != .success) { return error.SurfaceInitFailed; } return surface; } fn initializeCandidate(vki: InstanceDispatch, candidate: DeviceCandidate) !vk.Device { const priority = [_]f32{1}; const qci = [_]vk.DeviceQueueCreateInfo{ .{ .flags = .{}, .queue_family_index = candidate.queues.graphics_family, .queue_count = 1, .p_queue_priorities = &priority, }, .{ .flags = .{}, .queue_family_index = candidate.queues.present_family, .queue_count = 1, .p_queue_priorities = &priority, } }; const queue_count: u32 = if (candidate.queues.graphics_family == candidate.queues.present_family) 1 else 2; return try vki.createDevice(candidate.pdev, .{ .flags = .{}, .queue_create_info_count = queue_count, .p_queue_create_infos = &qci, .enabled_layer_count = 0, .pp_enabled_layer_names = undefined, .enabled_extension_count = required_device_extensions.len, .pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, &required_device_extensions), .p_enabled_features = null, }, null); } const DeviceCandidate = struct { pdev: vk.PhysicalDevice, props: vk.PhysicalDeviceProperties, queues: QueueAllocation, }; const QueueAllocation = struct { graphics_family: u32, present_family: u32, }; fn pickPhysicalDevice( vki: InstanceDispatch, instance: vk.Instance, allocator: *Allocator, surface: vk.SurfaceKHR, ) !DeviceCandidate { var device_count: u32 = undefined; _ = try vki.enumeratePhysicalDevices(instance, &device_count, null); const pdevs = try allocator.alloc(vk.PhysicalDevice, device_count); defer allocator.free(pdevs); _ = try vki.enumeratePhysicalDevices(instance, &device_count, pdevs.ptr); for (pdevs) |pdev| { if (try checkSuitable(vki, pdev, allocator, surface)) |candidate| { return candidate; } } return error.NoSuitableDevice; } fn checkSuitable( vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: *Allocator, surface: vk.SurfaceKHR, ) !?DeviceCandidate { const props = vki.getPhysicalDeviceProperties(pdev); if (!try checkExtensionSupport(vki, pdev, allocator)) { return null; } if (!try checkSurfaceSupport(vki, pdev, surface)) { return null; } if (try allocateQueues(vki, pdev, allocator, surface)) |allocation| { return DeviceCandidate{ .pdev = pdev, .props = props, .queues = allocation }; } return null; } fn allocateQueues( vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: *Allocator, surface: vk.SurfaceKHR ) !?QueueAllocation { var family_count: u32 = undefined; vki.getPhysicalDeviceQueueFamilyProperties(pdev, &family_count, null); const families = try allocator.alloc(vk.QueueFamilyProperties, family_count); defer allocator.free(families); vki.getPhysicalDeviceQueueFamilyProperties(pdev, &family_count, families.ptr); var graphics_family: ?u32 = null; var present_family: ?u32 = null; for (families) |properties, i| { const family = @intCast(u32, i); if (graphics_family == null and properties.queue_flags.contains(.{.graphics_bit = true})) { graphics_family = family; } if (present_family == null and (try vki.getPhysicalDeviceSurfaceSupportKHR(pdev, family, surface)) == vk.TRUE) { present_family = family; } } if (graphics_family != null and present_family != null) { return QueueAllocation{ .graphics_family = graphics_family.?, .present_family = present_family.? }; } return null; } fn checkSurfaceSupport(vki: InstanceDispatch, pdev: vk.PhysicalDevice, surface: vk.SurfaceKHR) !bool { var format_count: u32 = undefined; _ = try vki.getPhysicalDeviceSurfaceFormatsKHR(pdev, surface, &format_count, null); var present_mode_count: u32 = undefined; _ = try vki.getPhysicalDeviceSurfacePresentModesKHR(pdev, surface, &present_mode_count, null); return format_count > 0 and present_mode_count > 0; } fn checkExtensionSupport( vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: *Allocator, ) !bool { var count: u32 = undefined; _ = try vki.enumerateDeviceExtensionProperties(pdev, null, &count, null); const propsv = try allocator.alloc(vk.ExtensionProperties, count); defer allocator.free(propsv); _ = try vki.enumerateDeviceExtensionProperties(pdev, null, &count, propsv.ptr); for (required_device_extensions) |ext| { for (propsv) |props| { const len = std.mem.indexOfScalar(u8, &props.extension_name, 0).?; const prop_ext_name = props.extension_name[0 .. len]; if (std.mem.eql(u8, ext, prop_ext_name)) { break; } } else { return false; } } return true; }
examples/graphics-context.zig
pub const va_list = __builtin_va_list; pub const __gnuc_va_list = __builtin_va_list; pub const __u_char = u8; pub const __u_short = c_ushort; pub const __u_int = c_uint; pub const __u_long = c_ulong; pub const __int8_t = i8; pub const __uint8_t = u8; pub const __int16_t = c_short; pub const __uint16_t = c_ushort; pub const __int32_t = c_int; pub const __uint32_t = c_uint; pub const __int64_t = c_long; pub const __uint64_t = c_ulong; pub const __int_least8_t = __int8_t; pub const __uint_least8_t = __uint8_t; pub const __int_least16_t = __int16_t; pub const __uint_least16_t = __uint16_t; pub const __int_least32_t = __int32_t; pub const __uint_least32_t = __uint32_t; pub const __int_least64_t = __int64_t; pub const __uint_least64_t = __uint64_t; pub const __quad_t = c_long; pub const __u_quad_t = c_ulong; pub const __intmax_t = c_long; pub const __uintmax_t = c_ulong; pub const __dev_t = c_ulong; pub const __uid_t = c_uint; pub const __gid_t = c_uint; pub const __ino_t = c_ulong; pub const __ino64_t = c_ulong; pub const __mode_t = c_uint; pub const __nlink_t = c_ulong; pub const __off_t = c_long; pub const __off64_t = c_long; pub const __pid_t = c_int; const struct_unnamed_1 = extern struct { __val: [2]c_int, }; pub const __fsid_t = struct_unnamed_1; pub const __clock_t = c_long; pub const __rlim_t = c_ulong; pub const __rlim64_t = c_ulong; pub const __id_t = c_uint; pub const __time_t = c_long; pub const __useconds_t = c_uint; pub const __suseconds_t = c_long; pub const __daddr_t = c_int; pub const __key_t = c_int; pub const __clockid_t = c_int; pub const __timer_t = ?*c_void; pub const __blksize_t = c_long; pub const __blkcnt_t = c_long; pub const __blkcnt64_t = c_long; pub const __fsblkcnt_t = c_ulong; pub const __fsblkcnt64_t = c_ulong; pub const __fsfilcnt_t = c_ulong; pub const __fsfilcnt64_t = c_ulong; pub const __fsword_t = c_long; pub const __ssize_t = c_long; pub const __syscall_slong_t = c_long; pub const __syscall_ulong_t = c_ulong; pub const __loff_t = __off64_t; pub const __caddr_t = [*c]u8; pub const __intptr_t = c_long; pub const __socklen_t = c_uint; pub const __sig_atomic_t = c_int; const union_unnamed_3 = extern union { __wch: c_uint, __wchb: [4]u8, }; const struct_unnamed_2 = extern struct { __count: c_int, __value: union_unnamed_3, }; pub const __mbstate_t = struct_unnamed_2; pub const struct__G_fpos_t = extern struct { __pos: __off_t, __state: __mbstate_t, }; pub const __fpos_t = struct__G_fpos_t; pub const struct__G_fpos64_t = extern struct { __pos: __off64_t, __state: __mbstate_t, }; pub const __fpos64_t = struct__G_fpos64_t; pub const struct__IO_marker = @OpaqueType(); pub const struct__IO_codecvt = @OpaqueType(); pub const struct__IO_wide_data = @OpaqueType(); pub const struct__IO_FILE = extern struct { _flags: c_int, _IO_read_ptr: [*c]u8, _IO_read_end: [*c]u8, _IO_read_base: [*c]u8, _IO_write_base: [*c]u8, _IO_write_ptr: [*c]u8, _IO_write_end: [*c]u8, _IO_buf_base: [*c]u8, _IO_buf_end: [*c]u8, _IO_save_base: [*c]u8, _IO_backup_base: [*c]u8, _IO_save_end: [*c]u8, _markers: ?*struct__IO_marker, _chain: [*c]struct__IO_FILE, _fileno: c_int, _flags2: c_int, _old_offset: __off_t, _cur_column: c_ushort, _vtable_offset: i8, _shortbuf: [1]u8, _lock: ?*_IO_lock_t, _offset: __off64_t, _codecvt: ?*struct__IO_codecvt, _wide_data: ?*struct__IO_wide_data, _freeres_list: [*c]struct__IO_FILE, _freeres_buf: ?*c_void, __pad5: usize, _mode: c_int, _unused2: [20]u8, }; pub const __FILE = struct__IO_FILE; pub const FILE = struct__IO_FILE; pub const _IO_lock_t = c_void; pub const off_t = __off_t; pub const fpos_t = __fpos_t; pub extern var stdin: [*c]FILE; pub extern var stdout: [*c]FILE; pub extern var stderr: [*c]FILE; pub extern fn remove(__filename: [*c]const u8) c_int; pub extern fn rename(__old: [*c]const u8, __new: [*c]const u8) c_int; pub extern fn renameat(__oldfd: c_int, __old: [*c]const u8, __newfd: c_int, __new: [*c]const u8) c_int; pub extern fn tmpfile() [*c]FILE; pub extern fn tmpnam(__s: [*c]u8) [*c]u8; pub extern fn tmpnam_r(__s: [*c]u8) [*c]u8; pub extern fn tempnam(__dir: [*c]const u8, __pfx: [*c]const u8) [*c]u8; pub extern fn fclose(__stream: [*c]FILE) c_int; pub extern fn fflush(__stream: [*c]FILE) c_int; pub extern fn fflush_unlocked(__stream: [*c]FILE) c_int; pub extern fn fopen(__filename: [*c]const u8, __modes: [*c]const u8) [*c]FILE; pub extern fn freopen(noalias __filename: [*c]const u8, noalias __modes: [*c]const u8, noalias __stream: [*c]FILE) [*c]FILE; pub extern fn fdopen(__fd: c_int, __modes: [*c]const u8) [*c]FILE; pub extern fn fmemopen(__s: ?*c_void, __len: usize, __modes: [*c]const u8) [*c]FILE; pub extern fn open_memstream(__bufloc: [*c][*c]u8, __sizeloc: [*c]usize) [*c]FILE; pub extern fn setbuf(noalias __stream: [*c]FILE, noalias __buf: [*c]u8) void; pub extern fn setvbuf(noalias __stream: [*c]FILE, noalias __buf: [*c]u8, __modes: c_int, __n: usize) c_int; pub extern fn setbuffer(noalias __stream: [*c]FILE, noalias __buf: [*c]u8, __size: usize) void; pub extern fn setlinebuf(__stream: [*c]FILE) void; pub extern fn fprintf(__stream: [*c]FILE, __format: [*c]const u8, ...) c_int; pub extern fn printf(__format: [*c]const u8, ...) c_int; pub extern fn sprintf(__s: [*c]u8, __format: [*c]const u8, ...) c_int; pub const struct___va_list_tag = extern struct { gp_offset: c_uint, fp_offset: c_uint, overflow_arg_area: ?*c_void, reg_save_area: ?*c_void, }; pub extern fn vfprintf(__s: [*c]FILE, __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn vprintf(__format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn vsprintf(__s: [*c]u8, __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn snprintf(__s: [*c]u8, __maxlen: c_ulong, __format: [*c]const u8, ...) c_int; pub extern fn vsnprintf(__s: [*c]u8, __maxlen: c_ulong, __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn vdprintf(__fd: c_int, noalias __fmt: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn dprintf(__fd: c_int, noalias __fmt: [*c]const u8, ...) c_int; pub extern fn fscanf(noalias __stream: [*c]FILE, noalias __format: [*c]const u8, ...) c_int; pub extern fn scanf(noalias __format: [*c]const u8, ...) c_int; pub extern fn sscanf(noalias __s: [*c]const u8, noalias __format: [*c]const u8, ...) c_int; pub extern fn vfscanf(noalias __s: [*c]FILE, noalias __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn vscanf(noalias __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn vsscanf(noalias __s: [*c]const u8, noalias __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn fgetc(__stream: [*c]FILE) c_int; pub extern fn getc(__stream: [*c]FILE) c_int; pub extern fn getchar() c_int; pub extern fn getc_unlocked(__stream: [*c]FILE) c_int; pub extern fn getchar_unlocked() c_int; pub extern fn fgetc_unlocked(__stream: [*c]FILE) c_int; pub extern fn fputc(__c: c_int, __stream: [*c]FILE) c_int; pub extern fn putc(__c: c_int, __stream: [*c]FILE) c_int; pub extern fn putchar(__c: c_int) c_int; pub extern fn fputc_unlocked(__c: c_int, __stream: [*c]FILE) c_int; pub extern fn putc_unlocked(__c: c_int, __stream: [*c]FILE) c_int; pub extern fn putchar_unlocked(__c: c_int) c_int; pub extern fn getw(__stream: [*c]FILE) c_int; pub extern fn putw(__w: c_int, __stream: [*c]FILE) c_int; pub extern fn fgets(noalias __s: [*c]u8, __n: c_int, noalias __stream: [*c]FILE) [*c]u8; pub extern fn __getdelim(noalias __lineptr: [*c][*c]u8, noalias __n: [*c]usize, __delimiter: c_int, noalias __stream: [*c]FILE) __ssize_t; pub extern fn getdelim(noalias __lineptr: [*c][*c]u8, noalias __n: [*c]usize, __delimiter: c_int, noalias __stream: [*c]FILE) __ssize_t; pub extern fn getline(noalias __lineptr: [*c][*c]u8, noalias __n: [*c]usize, noalias __stream: [*c]FILE) __ssize_t; pub extern fn fputs(noalias __s: [*c]const u8, noalias __stream: [*c]FILE) c_int; pub extern fn puts(__s: [*c]const u8) c_int; pub extern fn ungetc(__c: c_int, __stream: [*c]FILE) c_int; pub extern fn fread(__ptr: ?*c_void, __size: c_ulong, __n: c_ulong, __stream: [*c]FILE) c_ulong; pub extern fn fwrite(__ptr: ?*const c_void, __size: c_ulong, __n: c_ulong, __s: [*c]FILE) c_ulong; pub extern fn fread_unlocked(noalias __ptr: ?*c_void, __size: usize, __n: usize, noalias __stream: [*c]FILE) usize; pub extern fn fwrite_unlocked(noalias __ptr: ?*const c_void, __size: usize, __n: usize, noalias __stream: [*c]FILE) usize; pub extern fn fseek(__stream: [*c]FILE, __off: c_long, __whence: c_int) c_int; pub extern fn ftell(__stream: [*c]FILE) c_long; pub extern fn rewind(__stream: [*c]FILE) void; pub extern fn fseeko(__stream: [*c]FILE, __off: __off_t, __whence: c_int) c_int; pub extern fn ftello(__stream: [*c]FILE) __off_t; pub extern fn fgetpos(noalias __stream: [*c]FILE, noalias __pos: [*c]fpos_t) c_int; pub extern fn fsetpos(__stream: [*c]FILE, __pos: [*c]const fpos_t) c_int; pub extern fn clearerr(__stream: [*c]FILE) void; pub extern fn feof(__stream: [*c]FILE) c_int; pub extern fn ferror(__stream: [*c]FILE) c_int; pub extern fn clearerr_unlocked(__stream: [*c]FILE) void; pub extern fn feof_unlocked(__stream: [*c]FILE) c_int; pub extern fn ferror_unlocked(__stream: [*c]FILE) c_int; pub extern fn perror(__s: [*c]const u8) void; pub extern var sys_nerr: c_int; pub extern const sys_errlist: [*c]const [*c]const u8; pub extern fn fileno(__stream: [*c]FILE) c_int; pub extern fn fileno_unlocked(__stream: [*c]FILE) c_int; pub extern fn popen(__command: [*c]const u8, __modes: [*c]const u8) [*c]FILE; pub extern fn pclose(__stream: [*c]FILE) c_int; pub extern fn ctermid(__s: [*c]u8) [*c]u8; pub extern fn flockfile(__stream: [*c]FILE) void; pub extern fn ftrylockfile(__stream: [*c]FILE) c_int; pub extern fn funlockfile(__stream: [*c]FILE) void; pub extern fn __uflow([*c]FILE) c_int; pub extern fn __overflow([*c]FILE, c_int) c_int; pub const MQTTPROPERTY_CODE_PAYLOAD_FORMAT_INDICATOR = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_PAYLOAD_FORMAT_INDICATOR); pub const MQTTPROPERTY_CODE_MESSAGE_EXPIRY_INTERVAL = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_MESSAGE_EXPIRY_INTERVAL); pub const MQTTPROPERTY_CODE_CONTENT_TYPE = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_CONTENT_TYPE); pub const MQTTPROPERTY_CODE_RESPONSE_TOPIC = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_RESPONSE_TOPIC); pub const MQTTPROPERTY_CODE_CORRELATION_DATA = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_CORRELATION_DATA); pub const MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIER = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIER); pub const MQTTPROPERTY_CODE_SESSION_EXPIRY_INTERVAL = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_SESSION_EXPIRY_INTERVAL); pub const MQTTPROPERTY_CODE_ASSIGNED_CLIENT_IDENTIFER = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_ASSIGNED_CLIENT_IDENTIFER); pub const MQTTPROPERTY_CODE_SERVER_KEEP_ALIVE = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_SERVER_KEEP_ALIVE); pub const MQTTPROPERTY_CODE_AUTHENTICATION_METHOD = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_AUTHENTICATION_METHOD); pub const MQTTPROPERTY_CODE_AUTHENTICATION_DATA = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_AUTHENTICATION_DATA); pub const MQTTPROPERTY_CODE_REQUEST_PROBLEM_INFORMATION = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_REQUEST_PROBLEM_INFORMATION); pub const MQTTPROPERTY_CODE_WILL_DELAY_INTERVAL = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_WILL_DELAY_INTERVAL); pub const MQTTPROPERTY_CODE_REQUEST_RESPONSE_INFORMATION = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_REQUEST_RESPONSE_INFORMATION); pub const MQTTPROPERTY_CODE_RESPONSE_INFORMATION = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_RESPONSE_INFORMATION); pub const MQTTPROPERTY_CODE_SERVER_REFERENCE = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_SERVER_REFERENCE); pub const MQTTPROPERTY_CODE_REASON_STRING = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_REASON_STRING); pub const MQTTPROPERTY_CODE_RECEIVE_MAXIMUM = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_RECEIVE_MAXIMUM); pub const MQTTPROPERTY_CODE_TOPIC_ALIAS_MAXIMUM = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_TOPIC_ALIAS_MAXIMUM); pub const MQTTPROPERTY_CODE_TOPIC_ALIAS = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_TOPIC_ALIAS); pub const MQTTPROPERTY_CODE_MAXIMUM_QOS = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_MAXIMUM_QOS); pub const MQTTPROPERTY_CODE_RETAIN_AVAILABLE = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_RETAIN_AVAILABLE); pub const MQTTPROPERTY_CODE_USER_PROPERTY = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_USER_PROPERTY); pub const MQTTPROPERTY_CODE_MAXIMUM_PACKET_SIZE = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_MAXIMUM_PACKET_SIZE); pub const MQTTPROPERTY_CODE_WILDCARD_SUBSCRIPTION_AVAILABLE = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_WILDCARD_SUBSCRIPTION_AVAILABLE); pub const MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIERS_AVAILABLE = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIERS_AVAILABLE); pub const MQTTPROPERTY_CODE_SHARED_SUBSCRIPTION_AVAILABLE = @enumToInt(enum_MQTTPropertyCodes.MQTTPROPERTY_CODE_SHARED_SUBSCRIPTION_AVAILABLE); pub const enum_MQTTPropertyCodes = extern enum(c_int) { MQTTPROPERTY_CODE_PAYLOAD_FORMAT_INDICATOR = 1, MQTTPROPERTY_CODE_MESSAGE_EXPIRY_INTERVAL = 2, MQTTPROPERTY_CODE_CONTENT_TYPE = 3, MQTTPROPERTY_CODE_RESPONSE_TOPIC = 8, MQTTPROPERTY_CODE_CORRELATION_DATA = 9, MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIER = 11, MQTTPROPERTY_CODE_SESSION_EXPIRY_INTERVAL = 17, MQTTPROPERTY_CODE_ASSIGNED_CLIENT_IDENTIFER = 18, MQTTPROPERTY_CODE_SERVER_KEEP_ALIVE = 19, MQTTPROPERTY_CODE_AUTHENTICATION_METHOD = 21, MQTTPROPERTY_CODE_AUTHENTICATION_DATA = 22, MQTTPROPERTY_CODE_REQUEST_PROBLEM_INFORMATION = 23, MQTTPROPERTY_CODE_WILL_DELAY_INTERVAL = 24, MQTTPROPERTY_CODE_REQUEST_RESPONSE_INFORMATION = 25, MQTTPROPERTY_CODE_RESPONSE_INFORMATION = 26, MQTTPROPERTY_CODE_SERVER_REFERENCE = 28, MQTTPROPERTY_CODE_REASON_STRING = 31, MQTTPROPERTY_CODE_RECEIVE_MAXIMUM = 33, MQTTPROPERTY_CODE_TOPIC_ALIAS_MAXIMUM = 34, MQTTPROPERTY_CODE_TOPIC_ALIAS = 35, MQTTPROPERTY_CODE_MAXIMUM_QOS = 36, MQTTPROPERTY_CODE_RETAIN_AVAILABLE = 37, MQTTPROPERTY_CODE_USER_PROPERTY = 38, MQTTPROPERTY_CODE_MAXIMUM_PACKET_SIZE = 39, MQTTPROPERTY_CODE_WILDCARD_SUBSCRIPTION_AVAILABLE = 40, MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIERS_AVAILABLE = 41, MQTTPROPERTY_CODE_SHARED_SUBSCRIPTION_AVAILABLE = 42, _, }; pub extern fn MQTTPropertyName(value: enum_MQTTPropertyCodes) [*c]const u8; pub const MQTTPROPERTY_TYPE_BYTE = @enumToInt(enum_MQTTPropertyTypes.MQTTPROPERTY_TYPE_BYTE); pub const MQTTPROPERTY_TYPE_TWO_BYTE_INTEGER = @enumToInt(enum_MQTTPropertyTypes.MQTTPROPERTY_TYPE_TWO_BYTE_INTEGER); pub const MQTTPROPERTY_TYPE_FOUR_BYTE_INTEGER = @enumToInt(enum_MQTTPropertyTypes.MQTTPROPERTY_TYPE_FOUR_BYTE_INTEGER); pub const MQTTPROPERTY_TYPE_VARIABLE_BYTE_INTEGER = @enumToInt(enum_MQTTPropertyTypes.MQTTPROPERTY_TYPE_VARIABLE_BYTE_INTEGER); pub const MQTTPROPERTY_TYPE_BINARY_DATA = @enumToInt(enum_MQTTPropertyTypes.MQTTPROPERTY_TYPE_BINARY_DATA); pub const MQTTPROPERTY_TYPE_UTF_8_ENCODED_STRING = @enumToInt(enum_MQTTPropertyTypes.MQTTPROPERTY_TYPE_UTF_8_ENCODED_STRING); pub const MQTTPROPERTY_TYPE_UTF_8_STRING_PAIR = @enumToInt(enum_MQTTPropertyTypes.MQTTPROPERTY_TYPE_UTF_8_STRING_PAIR); pub const enum_MQTTPropertyTypes = extern enum(c_int) { MQTTPROPERTY_TYPE_BYTE, MQTTPROPERTY_TYPE_TWO_BYTE_INTEGER, MQTTPROPERTY_TYPE_FOUR_BYTE_INTEGER, MQTTPROPERTY_TYPE_VARIABLE_BYTE_INTEGER, MQTTPROPERTY_TYPE_BINARY_DATA, MQTTPROPERTY_TYPE_UTF_8_ENCODED_STRING, MQTTPROPERTY_TYPE_UTF_8_STRING_PAIR, _, }; pub extern fn MQTTProperty_getType(value: enum_MQTTPropertyCodes) c_int; const struct_unnamed_4 = extern struct { len: c_int, data: [*c]u8, }; pub const MQTTLenString = struct_unnamed_4; const struct_unnamed_8 = extern struct { data: MQTTLenString, value: MQTTLenString, }; const union_unnamed_6 = extern union { byte: u8, integer2: c_ushort, integer4: c_uint, unnamed_7: struct_unnamed_8, }; const struct_unnamed_5 = extern struct { identifier: enum_MQTTPropertyCodes, value: union_unnamed_6, }; pub const MQTTProperty = struct_unnamed_5; pub const struct_MQTTProperties = extern struct { count: c_int, max_count: c_int, length: c_int, array: [*c]MQTTProperty, }; pub const MQTTProperties = struct_MQTTProperties; pub extern fn MQTTProperties_len(props: [*c]MQTTProperties) c_int; pub extern fn MQTTProperties_add(props: [*c]MQTTProperties, prop: [*c]const MQTTProperty) c_int; pub extern fn MQTTProperties_write(pptr: [*c][*c]u8, properties: [*c]const MQTTProperties) c_int; pub extern fn MQTTProperties_read(properties: [*c]MQTTProperties, pptr: [*c][*c]u8, enddata: [*c]u8) c_int; pub extern fn MQTTProperties_free(properties: [*c]MQTTProperties) void; pub extern fn MQTTProperties_copy(props: [*c]const MQTTProperties) MQTTProperties; pub extern fn MQTTProperties_hasProperty(props: [*c]MQTTProperties, propid: enum_MQTTPropertyCodes) c_int; pub extern fn MQTTProperties_propertyCount(props: [*c]MQTTProperties, propid: enum_MQTTPropertyCodes) c_int; pub extern fn MQTTProperties_getNumericValue(props: [*c]MQTTProperties, propid: enum_MQTTPropertyCodes) c_int; pub extern fn MQTTProperties_getNumericValueAt(props: [*c]MQTTProperties, propid: enum_MQTTPropertyCodes, index: c_int) c_int; pub extern fn MQTTProperties_getProperty(props: [*c]MQTTProperties, propid: enum_MQTTPropertyCodes) [*c]MQTTProperty; pub extern fn MQTTProperties_getPropertyAt(props: [*c]MQTTProperties, propid: enum_MQTTPropertyCodes, index: c_int) [*c]MQTTProperty; pub const MQTTREASONCODE_SUCCESS = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_SUCCESS); pub const MQTTREASONCODE_NORMAL_DISCONNECTION = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_NORMAL_DISCONNECTION); pub const MQTTREASONCODE_GRANTED_QOS_0 = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_GRANTED_QOS_0); pub const MQTTREASONCODE_GRANTED_QOS_1 = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_GRANTED_QOS_1); pub const MQTTREASONCODE_GRANTED_QOS_2 = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_GRANTED_QOS_2); pub const MQTTREASONCODE_DISCONNECT_WITH_WILL_MESSAGE = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_DISCONNECT_WITH_WILL_MESSAGE); pub const MQTTREASONCODE_NO_MATCHING_SUBSCRIBERS = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_NO_MATCHING_SUBSCRIBERS); pub const MQTTREASONCODE_NO_SUBSCRIPTION_FOUND = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_NO_SUBSCRIPTION_FOUND); pub const MQTTREASONCODE_CONTINUE_AUTHENTICATION = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_CONTINUE_AUTHENTICATION); pub const MQTTREASONCODE_RE_AUTHENTICATE = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_RE_AUTHENTICATE); pub const MQTTREASONCODE_UNSPECIFIED_ERROR = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_UNSPECIFIED_ERROR); pub const MQTTREASONCODE_MALFORMED_PACKET = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_MALFORMED_PACKET); pub const MQTTREASONCODE_PROTOCOL_ERROR = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_PROTOCOL_ERROR); pub const MQTTREASONCODE_IMPLEMENTATION_SPECIFIC_ERROR = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_IMPLEMENTATION_SPECIFIC_ERROR); pub const MQTTREASONCODE_UNSUPPORTED_PROTOCOL_VERSION = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_UNSUPPORTED_PROTOCOL_VERSION); pub const MQTTREASONCODE_CLIENT_IDENTIFIER_NOT_VALID = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_CLIENT_IDENTIFIER_NOT_VALID); pub const MQTTREASONCODE_BAD_USER_NAME_OR_PASSWORD = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_BAD_USER_NAME_OR_PASSWORD); pub const MQTTREASONCODE_NOT_AUTHORIZED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_NOT_AUTHORIZED); pub const MQTTREASONCODE_SERVER_UNAVAILABLE = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_SERVER_UNAVAILABLE); pub const MQTTREASONCODE_SERVER_BUSY = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_SERVER_BUSY); pub const MQTTREASONCODE_BANNED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_BANNED); pub const MQTTREASONCODE_SERVER_SHUTTING_DOWN = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_SERVER_SHUTTING_DOWN); pub const MQTTREASONCODE_BAD_AUTHENTICATION_METHOD = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_BAD_AUTHENTICATION_METHOD); pub const MQTTREASONCODE_KEEP_ALIVE_TIMEOUT = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_KEEP_ALIVE_TIMEOUT); pub const MQTTREASONCODE_SESSION_TAKEN_OVER = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_SESSION_TAKEN_OVER); pub const MQTTREASONCODE_TOPIC_FILTER_INVALID = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_TOPIC_FILTER_INVALID); pub const MQTTREASONCODE_TOPIC_NAME_INVALID = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_TOPIC_NAME_INVALID); pub const MQTTREASONCODE_PACKET_IDENTIFIER_IN_USE = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_PACKET_IDENTIFIER_IN_USE); pub const MQTTREASONCODE_PACKET_IDENTIFIER_NOT_FOUND = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_PACKET_IDENTIFIER_NOT_FOUND); pub const MQTTREASONCODE_RECEIVE_MAXIMUM_EXCEEDED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_RECEIVE_MAXIMUM_EXCEEDED); pub const MQTTREASONCODE_TOPIC_ALIAS_INVALID = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_TOPIC_ALIAS_INVALID); pub const MQTTREASONCODE_PACKET_TOO_LARGE = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_PACKET_TOO_LARGE); pub const MQTTREASONCODE_MESSAGE_RATE_TOO_HIGH = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_MESSAGE_RATE_TOO_HIGH); pub const MQTTREASONCODE_QUOTA_EXCEEDED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_QUOTA_EXCEEDED); pub const MQTTREASONCODE_ADMINISTRATIVE_ACTION = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_ADMINISTRATIVE_ACTION); pub const MQTTREASONCODE_PAYLOAD_FORMAT_INVALID = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_PAYLOAD_FORMAT_INVALID); pub const MQTTREASONCODE_RETAIN_NOT_SUPPORTED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_RETAIN_NOT_SUPPORTED); pub const MQTTREASONCODE_QOS_NOT_SUPPORTED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_QOS_NOT_SUPPORTED); pub const MQTTREASONCODE_USE_ANOTHER_SERVER = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_USE_ANOTHER_SERVER); pub const MQTTREASONCODE_SERVER_MOVED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_SERVER_MOVED); pub const MQTTREASONCODE_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED); pub const MQTTREASONCODE_CONNECTION_RATE_EXCEEDED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_CONNECTION_RATE_EXCEEDED); pub const MQTTREASONCODE_MAXIMUM_CONNECT_TIME = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_MAXIMUM_CONNECT_TIME); pub const MQTTREASONCODE_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED); pub const MQTTREASONCODE_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = @enumToInt(enum_MQTTReasonCodes.MQTTREASONCODE_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED); pub const enum_MQTTReasonCodes = extern enum(c_int) { MQTTREASONCODE_SUCCESS = 0, MQTTREASONCODE_NORMAL_DISCONNECTION = 0, MQTTREASONCODE_GRANTED_QOS_0 = 0, MQTTREASONCODE_GRANTED_QOS_1 = 1, MQTTREASONCODE_GRANTED_QOS_2 = 2, MQTTREASONCODE_DISCONNECT_WITH_WILL_MESSAGE = 4, MQTTREASONCODE_NO_MATCHING_SUBSCRIBERS = 16, MQTTREASONCODE_NO_SUBSCRIPTION_FOUND = 17, MQTTREASONCODE_CONTINUE_AUTHENTICATION = 24, MQTTREASONCODE_RE_AUTHENTICATE = 25, MQTTREASONCODE_UNSPECIFIED_ERROR = 128, MQTTREASONCODE_MALFORMED_PACKET = 129, MQTTREASONCODE_PROTOCOL_ERROR = 130, MQTTREASONCODE_IMPLEMENTATION_SPECIFIC_ERROR = 131, MQTTREASONCODE_UNSUPPORTED_PROTOCOL_VERSION = 132, MQTTREASONCODE_CLIENT_IDENTIFIER_NOT_VALID = 133, MQTTREASONCODE_BAD_USER_NAME_OR_PASSWORD = 134, MQTTREASONCODE_NOT_AUTHORIZED = 135, MQTTREASONCODE_SERVER_UNAVAILABLE = 136, MQTTREASONCODE_SERVER_BUSY = 137, MQTTREASONCODE_BANNED = 138, MQTTREASONCODE_SERVER_SHUTTING_DOWN = 139, MQTTREASONCODE_BAD_AUTHENTICATION_METHOD = 140, MQTTREASONCODE_KEEP_ALIVE_TIMEOUT = 141, MQTTREASONCODE_SESSION_TAKEN_OVER = 142, MQTTREASONCODE_TOPIC_FILTER_INVALID = 143, MQTTREASONCODE_TOPIC_NAME_INVALID = 144, MQTTREASONCODE_PACKET_IDENTIFIER_IN_USE = 145, MQTTREASONCODE_PACKET_IDENTIFIER_NOT_FOUND = 146, MQTTREASONCODE_RECEIVE_MAXIMUM_EXCEEDED = 147, MQTTREASONCODE_TOPIC_ALIAS_INVALID = 148, MQTTREASONCODE_PACKET_TOO_LARGE = 149, MQTTREASONCODE_MESSAGE_RATE_TOO_HIGH = 150, MQTTREASONCODE_QUOTA_EXCEEDED = 151, MQTTREASONCODE_ADMINISTRATIVE_ACTION = 152, MQTTREASONCODE_PAYLOAD_FORMAT_INVALID = 153, MQTTREASONCODE_RETAIN_NOT_SUPPORTED = 154, MQTTREASONCODE_QOS_NOT_SUPPORTED = 155, MQTTREASONCODE_USE_ANOTHER_SERVER = 156, MQTTREASONCODE_SERVER_MOVED = 157, MQTTREASONCODE_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = 158, MQTTREASONCODE_CONNECTION_RATE_EXCEEDED = 159, MQTTREASONCODE_MAXIMUM_CONNECT_TIME = 160, MQTTREASONCODE_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = 161, MQTTREASONCODE_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = 162, _, }; pub extern fn MQTTReasonCode_toString(value: enum_MQTTReasonCodes) [*c]const u8; pub const struct_MQTTSubscribe_options = extern struct { struct_id: [4]u8, struct_version: c_int, noLocal: u8, retainAsPublished: u8, retainHandling: u8, }; pub const MQTTSubscribe_options = struct_MQTTSubscribe_options; pub const Persistence_open = ?fn ([*c]?*c_void, [*c]const u8, [*c]const u8, ?*c_void) callconv(.C) c_int; pub const Persistence_close = ?fn (?*c_void) callconv(.C) c_int; pub const Persistence_put = ?fn (?*c_void, [*c]u8, c_int, [*c][*c]u8, [*c]c_int) callconv(.C) c_int; pub const Persistence_get = ?fn (?*c_void, [*c]u8, [*c][*c]u8, [*c]c_int) callconv(.C) c_int; pub const Persistence_remove = ?fn (?*c_void, [*c]u8) callconv(.C) c_int; pub const Persistence_keys = ?fn (?*c_void, [*c][*c][*c]u8, [*c]c_int) callconv(.C) c_int; pub const Persistence_clear = ?fn (?*c_void) callconv(.C) c_int; pub const Persistence_containskey = ?fn (?*c_void, [*c]u8) callconv(.C) c_int; const struct_unnamed_9 = extern struct { context: ?*c_void, popen: Persistence_open, pclose: Persistence_close, pput: Persistence_put, pget: Persistence_get, premove: Persistence_remove, pkeys: Persistence_keys, pclear: Persistence_clear, pcontainskey: Persistence_containskey, }; pub const MQTTClient_persistence = struct_unnamed_9; const struct_unnamed_10 = extern struct { struct_id: [4]u8, struct_version: c_int, do_openssl_init: c_int, }; pub const MQTTClient_init_options = struct_unnamed_10; pub extern fn MQTTClient_global_init(inits: [*c]MQTTClient_init_options) void; pub const MQTTClient = ?*c_void; pub const MQTTClient_deliveryToken = c_int; pub const MQTTClient_token = c_int; const struct_unnamed_11 = extern struct { struct_id: [4]u8, struct_version: c_int, payloadlen: c_int, payload: ?*c_void, qos: c_int, retained: c_int, dup: c_int, msgid: c_int, properties: MQTTProperties, }; pub const MQTTClient_message = struct_unnamed_11; pub const MQTTClient_messageArrived = fn (?*c_void, [*c]u8, c_int, [*c]MQTTClient_message) callconv(.C) c_int; pub const MQTTClient_deliveryComplete = fn (?*c_void, MQTTClient_deliveryToken) callconv(.C) void; pub const MQTTClient_connectionLost = fn (?*c_void, [*c]u8) callconv(.C) void; pub extern fn MQTTClient_setCallbacks(handle: MQTTClient, context: ?*c_void, cl: ?MQTTClient_connectionLost, ma: ?MQTTClient_messageArrived, dc: ?MQTTClient_deliveryComplete) c_int; pub const MQTTClient_disconnected = fn (?*c_void, [*c]MQTTProperties, enum_MQTTReasonCodes) callconv(.C) void; pub extern fn MQTTClient_setDisconnected(handle: MQTTClient, context: ?*c_void, co: ?MQTTClient_disconnected) c_int; pub const MQTTClient_published = fn (?*c_void, c_int, c_int, [*c]MQTTProperties, enum_MQTTReasonCodes) callconv(.C) void; pub extern fn MQTTClient_setPublished(handle: MQTTClient, context: ?*c_void, co: ?MQTTClient_published) c_int; pub extern fn MQTTClient_create(handle: [*c]MQTTClient, serverURI: [*c]const u8, clientId: [*c]const u8, persistence_type: c_int, persistence_context: ?*c_void) c_int; const struct_unnamed_12 = extern struct { struct_id: [4]u8, struct_version: c_int, MQTTVersion: c_int, }; pub const MQTTClient_createOptions = struct_unnamed_12; pub extern fn MQTTClient_createWithOptions(handle: [*c]MQTTClient, serverURI: [*c]const u8, clientId: [*c]const u8, persistence_type: c_int, persistence_context: ?*c_void, options: [*c]MQTTClient_createOptions) c_int; const struct_unnamed_14 = extern struct { len: c_int, data: ?*const c_void, }; const struct_unnamed_13 = extern struct { struct_id: [4]u8, struct_version: c_int, topicName: [*c]const u8, message: [*c]const u8, retained: c_int, qos: c_int, payload: struct_unnamed_14, }; pub const MQTTClient_willOptions = struct_unnamed_13; const struct_unnamed_15 = extern struct { struct_id: [4]u8, struct_version: c_int, trustStore: [*c]const u8, keyStore: [*c]const u8, privateKey: [*c]const u8, privateKeyPassword: [*c]const u8, enabledCipherSuites: [*c]const u8, enableServerCertAuth: c_int, sslVersion: c_int, verify: c_int, CApath: [*c]const u8, ssl_error_cb: ?fn ([*c]const u8, usize, ?*c_void) callconv(.C) c_int, ssl_error_context: ?*c_void, ssl_psk_cb: ?fn ([*c]const u8, [*c]u8, c_uint, [*c]u8, c_uint, ?*c_void) callconv(.C) c_uint, ssl_psk_context: ?*c_void, disableDefaultTrustStore: c_int, }; pub const MQTTClient_SSLOptions = struct_unnamed_15; const struct_unnamed_17 = extern struct { serverURI: [*c]const u8, MQTTVersion: c_int, sessionPresent: c_int, }; const struct_unnamed_18 = extern struct { len: c_int, data: ?*const c_void, }; const struct_unnamed_16 = extern struct { struct_id: [4]u8, struct_version: c_int, keepAliveInterval: c_int, cleansession: c_int, reliable: c_int, will: [*c]MQTTClient_willOptions, username: [*c]const u8, password: <PASSWORD>]const u8, connectTimeout: c_int, retryInterval: c_int, ssl: [*c]MQTTClient_SSLOptions, serverURIcount: c_int, serverURIs: [*c]const [*c]u8, MQTTVersion: c_int, returned: struct_unnamed_17, binarypwd: struct_unnamed_18, maxInflightMessages: c_int, cleanstart: c_int, }; pub const MQTTClient_connectOptions = struct_unnamed_16; const struct_unnamed_19 = extern struct { name: [*c]const u8, value: [*c]const u8, }; pub const MQTTClient_nameValue = struct_unnamed_19; pub extern fn MQTTClient_getVersionInfo() [*c]MQTTClient_nameValue; pub extern fn MQTTClient_connect(handle: MQTTClient, options: [*c]MQTTClient_connectOptions) c_int; pub const struct_MQTTResponse = extern struct { version: c_int, reasonCode: enum_MQTTReasonCodes, reasonCodeCount: c_int, reasonCodes: [*c]enum_MQTTReasonCodes, properties: [*c]MQTTProperties, }; pub const MQTTResponse = struct_MQTTResponse; pub extern fn MQTTResponse_free(response: MQTTResponse) void; pub extern fn MQTTClient_connect5(handle: MQTTClient, options: [*c]MQTTClient_connectOptions, connectProperties: [*c]MQTTProperties, willProperties: [*c]MQTTProperties) MQTTResponse; pub extern fn MQTTClient_disconnect(handle: MQTTClient, timeout: c_int) c_int; pub extern fn MQTTClient_disconnect5(handle: MQTTClient, timeout: c_int, reason: enum_MQTTReasonCodes, props: [*c]MQTTProperties) c_int; pub extern fn MQTTClient_isConnected(handle: MQTTClient) c_int; pub extern fn MQTTClient_subscribe(handle: MQTTClient, topic: [*c]const u8, qos: c_int) c_int; pub extern fn MQTTClient_subscribe5(handle: MQTTClient, topic: [*c]const u8, qos: c_int, opts: [*c]MQTTSubscribe_options, props: [*c]MQTTProperties) MQTTResponse; pub extern fn MQTTClient_subscribeMany(handle: MQTTClient, count: c_int, topic: [*c]const [*c]u8, qos: [*c]c_int) c_int; pub extern fn MQTTClient_subscribeMany5(handle: MQTTClient, count: c_int, topic: [*c]const [*c]u8, qos: [*c]c_int, opts: [*c]MQTTSubscribe_options, props: [*c]MQTTProperties) MQTTResponse; pub extern fn MQTTClient_unsubscribe(handle: MQTTClient, topic: [*c]const u8) c_int; pub extern fn MQTTClient_unsubscribe5(handle: MQTTClient, topic: [*c]const u8, props: [*c]MQTTProperties) MQTTResponse; pub extern fn MQTTClient_unsubscribeMany(handle: MQTTClient, count: c_int, topic: [*c]const [*c]u8) c_int; pub extern fn MQTTClient_unsubscribeMany5(handle: MQTTClient, count: c_int, topic: [*c]const [*c]u8, props: [*c]MQTTProperties) MQTTResponse; pub extern fn MQTTClient_publish(handle: MQTTClient, topicName: [*c]const u8, payloadlen: c_int, payload: ?*const c_void, qos: c_int, retained: c_int, dt: [*c]MQTTClient_deliveryToken) c_int; pub extern fn MQTTClient_publish5(handle: MQTTClient, topicName: [*c]const u8, payloadlen: c_int, payload: ?*const c_void, qos: c_int, retained: c_int, properties: [*c]MQTTProperties, dt: [*c]MQTTClient_deliveryToken) MQTTResponse; pub extern fn MQTTClient_publishMessage(handle: MQTTClient, topicName: [*c]const u8, msg: [*c]MQTTClient_message, dt: [*c]MQTTClient_deliveryToken) c_int; pub extern fn MQTTClient_publishMessage5(handle: MQTTClient, topicName: [*c]const u8, msg: [*c]MQTTClient_message, dt: [*c]MQTTClient_deliveryToken) MQTTResponse; pub extern fn MQTTClient_waitForCompletion(handle: MQTTClient, dt: MQTTClient_deliveryToken, timeout: c_ulong) c_int; pub extern fn MQTTClient_getPendingDeliveryTokens(handle: MQTTClient, tokens: [*c][*c]MQTTClient_deliveryToken) c_int; pub extern fn MQTTClient_yield() void; pub extern fn MQTTClient_receive(handle: MQTTClient, topicName: [*c][*c]u8, topicLen: [*c]c_int, message: [*c][*c]MQTTClient_message, timeout: c_ulong) c_int; pub extern fn MQTTClient_freeMessage(msg: [*c][*c]MQTTClient_message) void; pub extern fn MQTTClient_free(ptr: ?*c_void) void; pub extern fn MQTTClient_destroy(handle: [*c]MQTTClient) void; pub const MQTTCLIENT_TRACE_MAXIMUM = @enumToInt(enum_MQTTCLIENT_TRACE_LEVELS.MQTTCLIENT_TRACE_MAXIMUM); pub const MQTTCLIENT_TRACE_MEDIUM = @enumToInt(enum_MQTTCLIENT_TRACE_LEVELS.MQTTCLIENT_TRACE_MEDIUM); pub const MQTTCLIENT_TRACE_MINIMUM = @enumToInt(enum_MQTTCLIENT_TRACE_LEVELS.MQTTCLIENT_TRACE_MINIMUM); pub const MQTTCLIENT_TRACE_PROTOCOL = @enumToInt(enum_MQTTCLIENT_TRACE_LEVELS.MQTTCLIENT_TRACE_PROTOCOL); pub const MQTTCLIENT_TRACE_ERROR = @enumToInt(enum_MQTTCLIENT_TRACE_LEVELS.MQTTCLIENT_TRACE_ERROR); pub const MQTTCLIENT_TRACE_SEVERE = @enumToInt(enum_MQTTCLIENT_TRACE_LEVELS.MQTTCLIENT_TRACE_SEVERE); pub const MQTTCLIENT_TRACE_FATAL = @enumToInt(enum_MQTTCLIENT_TRACE_LEVELS.MQTTCLIENT_TRACE_FATAL); pub const enum_MQTTCLIENT_TRACE_LEVELS = extern enum(c_int) { MQTTCLIENT_TRACE_MAXIMUM = 1, MQTTCLIENT_TRACE_MEDIUM = 2, MQTTCLIENT_TRACE_MINIMUM = 3, MQTTCLIENT_TRACE_PROTOCOL = 4, MQTTCLIENT_TRACE_ERROR = 5, MQTTCLIENT_TRACE_SEVERE = 6, MQTTCLIENT_TRACE_FATAL = 7, _, }; pub extern fn MQTTClient_setTraceLevel(level: enum_MQTTCLIENT_TRACE_LEVELS) void; pub const MQTTClient_traceCallback = fn (enum_MQTTCLIENT_TRACE_LEVELS, [*c]u8) callconv(.C) void; pub extern fn MQTTClient_setTraceCallback(callback: ?MQTTClient_traceCallback) void; pub extern fn MQTTClient_strerror(code: c_int) [*c]const u8; pub const __INTMAX_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINTMAX_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __PTRDIFF_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __INTPTR_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __SIZE_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __WINT_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __CHAR16_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __CHAR32_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINTPTR_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __INT8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_signed = void }"); pub const __INT64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINT8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_char = void }"); pub const __UINT16_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __UINT32_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINT64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __INT_LEAST8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_signed = void }"); pub const __UINT_LEAST8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_char = void }"); pub const __UINT_LEAST16_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __UINT_LEAST32_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __INT_LEAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINT_LEAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const __INT_FAST8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_signed = void }"); pub const __UINT_FAST8_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_char = void }"); pub const __UINT_FAST16_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __UINT_FAST32_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __INT_FAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UINT_FAST64_TYPE__ = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_unsigned = void }"); pub const DLLImport = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_extern = void }"); pub const __GLIBC_USE = @compileError("unable to translate C expr: unexpected token Id{ .HashHash = void }"); pub const __THROW = @compileError("unable to translate C expr: expected ')'' here"); pub const __NTH = @compileError("unable to translate C expr: expected ')'' here"); pub const __NTHNL = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __CONCAT = @compileError("unable to translate C expr: unexpected token Id{ .HashHash = void }"); pub const __STRING = @compileError("unable to translate C expr: unexpected token Id{ .Hash = void }"); pub const __ptr_t = @compileError("unable to translate C expr: unexpected token Id{ .Nl = void }"); pub const __warndecl = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_extern = void }"); pub const __warnattr = @compileError("unable to translate C expr: unexpected token Id{ .Nl = void }"); pub const __errordecl = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_extern = void }"); pub const __flexarr = @compileError("unable to translate C expr: unexpected token Id{ .LBracket = void }"); pub const __REDIRECT = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __REDIRECT_NTH = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __REDIRECT_NTHNL = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __ASMNAME2 = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __attribute_alloc_size__ = @compileError("unable to translate C expr: unexpected token Id{ .Nl = void }"); pub const __nonnull = @compileError("unable to translate C expr: expected ')'' here"); pub const __always_inline = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __extern_inline = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_extern = void }"); pub const __extern_always_inline = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_extern = void }"); pub const __fortify_function = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __attribute_copy__ = @compileError("unable to translate C expr: unexpected token Id{ .Nl = void }"); pub const __LDBL_REDIR1 = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __LDBL_REDIR = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __LDBL_REDIR1_NTH = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __LDBL_REDIR_NTH = @compileError("unable to translate C expr: unexpected token Id{ .Identifier = void }"); pub const __LDBL_REDIR_DECL = @compileError("unable to translate C expr: unexpected token Id{ .Nl = void }"); pub const __glibc_macro_warning1 = @compileError("unable to translate C expr: unexpected token Id{ .Hash = void }"); pub const __glibc_macro_warning = @compileError("unable to translate C expr: expected ',' or ')'"); pub const NULL = @compileError("unable to translate C expr: expected ')'' here"); pub const __S16_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __U16_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_short = void }"); pub const __U32_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __SLONGWORD_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __ULONGWORD_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_long = void }"); pub const __SQUAD_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UQUAD_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_long = void }"); pub const __SWORD_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __UWORD_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_long = void }"); pub const __ULONG32_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __S64_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_int = void }"); pub const __U64_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_long = void }"); pub const __STD_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_typedef = void }"); pub const __TIMER_T_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Nl = void }"); pub const __FSID_T_TYPE = @compileError("unable to translate C expr: unexpected token Id{ .Keyword_struct = void }"); pub const __getc_unlocked_body = @compileError("unable to translate C expr: expected ':'"); pub const __putc_unlocked_body = @compileError("unable to translate C expr: expected ':'"); pub const __feof_unlocked_body = @compileError("unable to translate C expr: expected ')'' here"); pub const __ferror_unlocked_body = @compileError("unable to translate C expr: expected ')'' here"); pub const MQTTProperties_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTSubscribe_options_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTClient_init_options_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTClient_message_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTClient_createOptions_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTClient_willOptions_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTClient_SSLOptions_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTClient_connectOptions_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTClient_connectOptions_initializer5 = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const MQTTResponse_initializer = @compileError("unable to translate C expr: unexpected token Id{ .LBrace = void }"); pub const __UINT64_MAX__ = @as(c_ulong, 18446744073709551615); pub const __WORDSIZE_TIME64_COMPAT32 = 1; pub const MQTTCLIENT_BAD_MQTT_VERSION = -11; pub const __FINITE_MATH_ONLY__ = 0; pub const __SYSCALL_WORDSIZE = 64; pub const __SIZEOF_FLOAT__ = 4; pub const __SEG_GS = 1; pub const __UINT_LEAST64_FMTX__ = "lX"; pub const __INT_FAST8_MAX__ = 127; pub const __OBJC_BOOL_IS_BOOL = 0; pub const __CLOCKID_T_TYPE = __S32_TYPE; pub const __INT_LEAST8_FMTi__ = "hhi"; pub const __USE_POSIX2 = 1; pub const __UINT64_FMTX__ = "lX"; pub inline fn va_start(ap: anytype, param: anytype) @TypeOf(__builtin_va_start(ap, param)) { return __builtin_va_start(ap, param); } pub const __SIG_ATOMIC_MAX__ = 2147483647; pub const __SSE__ = 1; pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__; pub const __NO_MATH_INLINES = 1; pub const __SIZEOF_FLOAT128__ = 16; pub inline fn __GNUC_PREREQ(maj: anytype, min: anytype) @TypeOf(__GNUC__ << 16 + __GNUC_MINOR__ >= maj << 16 + min) { return __GNUC__ << 16 + __GNUC_MINOR__ >= maj << 16 + min; } pub const __INT_FAST32_FMTd__ = "d"; pub const _POSIX_C_SOURCE = @as(c_long, 200809); pub const __STDC_UTF_16__ = 1; pub const __UINT_FAST16_MAX__ = 65535; pub const __ATOMIC_ACQUIRE = 2; pub const _FEATURES_H = 1; pub const __LDBL_HAS_DENORM__ = 1; pub const __INTMAX_FMTi__ = "li"; pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7); pub const __UINT_FAST32_FMTo__ = "o"; pub const __UINT32_MAX__ = @as(c_uint, 4294967295); pub const MQTTCLIENT_TOPICNAME_TRUNCATED = -7; pub const __INT_MAX__ = 2147483647; pub const __INT_LEAST64_MAX__ = @as(c_long, 9223372036854775807); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = 1; pub const __USE_FORTIFY_LEVEL = 0; pub const __RLIM_T_MATCHES_RLIM64_T = 1; pub const __SIZEOF_INT128__ = 16; pub const __INT64_MAX__ = @as(c_long, 9223372036854775807); pub const __DBL_MIN_10_EXP__ = -307; pub const MQTTCLIENT_WRONG_MQTT_VERSION = -16; pub const __INT_LEAST32_MAX__ = 2147483647; pub const __INT_FAST16_FMTd__ = "hd"; pub const MQTT_SSL_VERSION_TLS_1_1 = 2; pub const __attribute_pure__ = __attribute__(__pure__); pub const __UINT_LEAST64_FMTu__ = "lu"; pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324; pub const __UINT8_FMTu__ = "hhu"; pub const __INT_FAST16_MAX__ = 32767; pub inline fn __bos0(ptr: anytype) @TypeOf(__builtin_object_size(ptr, 0)) { return __builtin_object_size(ptr, 0); } pub const __LP64__ = 1; pub const __SIZE_FMTx__ = "lx"; pub const __ORDER_PDP_ENDIAN__ = 3412; pub const __UINT8_FMTX__ = "hhX"; pub const __LDBL_MIN_10_EXP__ = -4931; pub const __LDBL_MAX_10_EXP__ = 4932; pub const __DBL_MAX_10_EXP__ = 308; pub const __PTRDIFF_FMTi__ = "li"; pub const __STDC_IEC_559__ = 1; pub const MQTT_BAD_SUBSCRIBE = 0x80; pub inline fn __REDIRECT_NTH_LDBL(name: anytype, proto: anytype, alias: anytype) @TypeOf(__REDIRECT_NTH(name, proto, alias)) { return __REDIRECT_NTH(name, proto, alias); } pub const __FLT_MIN_EXP__ = -125; pub const __SIZEOF_LONG__ = 8; pub const __FLT_MIN__ = @as(f32, 1.17549435e-38); pub const __FLT_EVAL_METHOD__ = 0; pub const P_tmpdir = "/tmp"; pub const __UINTMAX_FMTx__ = "lx"; pub const __UINT_LEAST8_FMTo__ = "hho"; pub const __code_model_small_ = 1; pub const __ELF__ = 1; pub const __UINT_FAST8_FMTu__ = "hhu"; pub const __DADDR_T_TYPE = __S32_TYPE; pub const _LP64 = 1; pub const MQTTVERSION_3_1 = 3; pub const __FLT_MAX_EXP__ = 128; pub const __DBL_HAS_DENORM__ = 1; pub const __WINT_UNSIGNED__ = 1; pub const __INT_LEAST64_FMTd__ = "ld"; pub const __GNU_LIBRARY__ = 6; pub const __UINT_LEAST8_FMTu__ = "hhu"; pub const __FLT_MAX__ = @as(f32, 3.40282347e+38); pub inline fn __glibc_likely(cond: anytype) @TypeOf(__builtin_expect(cond, 1)) { return __builtin_expect(cond, 1); } pub const __CPU_MASK_TYPE = __SYSCALL_ULONG_TYPE; pub const __UINT_FAST8_FMTX__ = "hhX"; pub const __UINT_FAST16_FMTu__ = "hu"; pub const __amdfam10 = 1; pub const SEEK_END = 2; pub const MQTTVERSION_5 = 5; pub const __UINT_FAST32_FMTX__ = "X"; pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__; pub const __LZCNT__ = 1; pub inline fn __glibc_clang_has_extension(ext: anytype) @TypeOf(__has_extension(ext)) { return __has_extension(ext); } pub const __BLKCNT_T_TYPE = __SYSCALL_SLONG_TYPE; pub const _BITS_TYPES_H = 1; pub const __SSP_STRONG__ = 2; pub const __clang_patchlevel__ = 0; pub const __UINT64_FMTu__ = "lu"; pub const _IONBF = 2; pub const MQTTCLIENT_PERSISTENCE_USER = 2; pub const __SIZEOF_SHORT__ = 2; pub const __LDBL_DIG__ = 18; pub const __OPENCL_MEMORY_SCOPE_DEVICE = 2; pub const __INT_FAST8_FMTd__ = "hhd"; pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45); pub const __MMX__ = 1; pub const __NO_INLINE__ = 1; pub const __SIZEOF_WINT_T__ = 4; pub inline fn __GLIBC_PREREQ(maj: anytype, min: anytype) @TypeOf(__GLIBC__ << 16 + __GLIBC_MINOR__ >= maj << 16 + min) { return __GLIBC__ << 16 + __GLIBC_MINOR__ >= maj << 16 + min; } pub const __STDC_IEC_559_COMPLEX__ = 1; pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = 2; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = 1; pub const __INTMAX_C_SUFFIX__ = L; pub const __UINT_LEAST32_FMTu__ = "u"; pub const __INT_LEAST16_FMTi__ = "hi"; pub const __LITTLE_ENDIAN__ = 1; pub const MQTTCLIENT_DISCONNECTED = -3; pub const __UINTMAX_C_SUFFIX__ = UL; pub const __INO_T_MATCHES_INO64_T = 1; pub inline fn __attribute_deprecated_msg__(msg: anytype) @TypeOf(__attribute__(__deprecated__(msg))) { return __attribute__(__deprecated__(msg)); } pub const _IO_USER_LOCK = 0x8000; pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = 0; pub const __VERSION__ = "Clang 9.0.0 (tags/RELEASE_900/final)"; pub const __DBL_HAS_INFINITY__ = 1; pub const __INT_LEAST16_MAX__ = 32767; pub const __SCHAR_MAX__ = 127; pub const __GNUC_MINOR__ = 2; pub const __UINT32_FMTx__ = "x"; pub const __LDBL_HAS_QUIET_NAN__ = 1; pub const __UINT_FAST32_FMTu__ = "u"; pub const __UINT8_FMTx__ = "hhx"; pub const __UINT_LEAST8_FMTX__ = "hhX"; pub const _DEFAULT_SOURCE = 1; pub const __UINT_LEAST64_FMTx__ = "lx"; pub const __UINT_LEAST64_MAX__ = @as(c_ulong, 18446744073709551615); pub const MQTT_SSL_VERSION_DEFAULT = 0; pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = 2; pub const __pic__ = 2; pub const __clang__ = 1; pub const __FLT_HAS_INFINITY__ = 1; pub const __GLIBC__ = 2; pub const __USE_XOPEN2K8 = 1; pub const __UINTPTR_FMTu__ = "lu"; pub const __3dNOW__ = 1; pub const __unix__ = 1; pub const EOF = -1; pub const __UID_T_TYPE = __U32_TYPE; pub const __INT_FAST32_TYPE__ = c_int; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = 1; pub inline fn __va_copy(d: anytype, s: anytype) @TypeOf(__builtin_va_copy(d, s)) { return __builtin_va_copy(d, s); } pub const __restrict_arr = __restrict; pub const __UINT16_FMTx__ = "hx"; pub const __UINT_LEAST32_FMTo__ = "o"; pub const __glibc_c99_flexarr_available = 1; pub const SEEK_SET = 0; pub const __FLT_MIN_10_EXP__ = -37; pub const __UINT_LEAST16_FMTX__ = "hX"; pub const __UINT_LEAST32_MAX__ = @as(c_uint, 4294967295); pub const __RLIM64_T_TYPE = __UQUAD_TYPE; pub const __FSFILCNT_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __GNUC_VA_LIST = 1; pub const __UINT_FAST8_FMTx__ = "hhx"; pub const __SIZE_FMTu__ = "lu"; pub const __SIZEOF_POINTER__ = 8; pub const __SIZE_FMTX__ = "lX"; pub const __USE_XOPEN2K = 1; pub const __INT16_FMTd__ = "hd"; pub const __clang_version__ = "9.0.0 (tags/RELEASE_900/final)"; pub const __ATOMIC_RELEASE = 3; pub const __UINT_FAST64_FMTX__ = "lX"; pub const __INTMAX_FMTd__ = "ld"; pub const __SEG_FS = 1; pub const __USE_POSIX199309 = 1; pub const TMP_MAX = 238328; pub const __UINT_FAST8_FMTo__ = "hho"; pub const __WINT_WIDTH__ = 32; pub const SEEK_CUR = 1; pub const __FLT_MAX_10_EXP__ = 38; pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176502e+4932); pub const __GCC_ATOMIC_LONG_LOCK_FREE = 2; pub const __gnu_linux__ = 1; pub const _DEBUG = 1; pub const _____fpos64_t_defined = 1; pub const _IO_EOF_SEEN = 0x0010; pub inline fn __PMT(args: anytype) @TypeOf(args) { return args; } pub const __UINTPTR_WIDTH__ = 64; pub const __INT_LEAST32_FMTi__ = "i"; pub const __WCHAR_WIDTH__ = 32; pub const __UINT16_FMTX__ = "hX"; pub const __OFF64_T_TYPE = __SQUAD_TYPE; pub const unix = 1; pub const __STDC_ISO_10646__ = @as(c_long, 201706); pub const __SYSCALL_ULONG_TYPE = __ULONGWORD_TYPE; pub const __BLKSIZE_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __GNUC_PATCHLEVEL__ = 1; pub const _IO_ERR_SEEN = 0x0020; pub const __INT_LEAST16_TYPE__ = c_short; pub const __INT64_FMTd__ = "ld"; pub const __SSE3__ = 1; pub const __SYSCALL_SLONG_TYPE = __SLONGWORD_TYPE; pub const __UINT16_MAX__ = 65535; pub const __ATOMIC_RELAXED = 0; pub const FOPEN_MAX = 16; pub const _POSIX_SOURCE = 1; pub const __SSE4A__ = 1; pub const __GCC_ATOMIC_CHAR_LOCK_FREE = 2; pub const __UINT_LEAST16_FMTx__ = "hx"; pub const __UINT_FAST64_FMTu__ = "lu"; pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = 2; pub const __SSE2__ = 1; pub const _ATFILE_SOURCE = 1; pub const __STDC__ = 1; pub const __attribute_warn_unused_result__ = __attribute__(__warn_unused_result__); pub const ____FILE_defined = 1; pub const __GLIBC_USE_IEC_60559_BFP_EXT = 0; pub const __INT_FAST16_TYPE__ = c_short; pub const __UINT64_C_SUFFIX__ = UL; pub const MQTTCLIENT_SUCCESS = 0; pub const __LONG_MAX__ = @as(c_long, 9223372036854775807); pub const __DBL_MAX__ = 1.7976931348623157e+308; pub const __MODE_T_TYPE = __U32_TYPE; pub const __CHAR_BIT__ = 8; pub const __DBL_DECIMAL_DIG__ = 17; pub const __UINT_LEAST8_FMTx__ = "hhx"; pub const __FSBLKCNT64_T_TYPE = __UQUAD_TYPE; pub const MQTTCLIENT_MAX_MESSAGES_INFLIGHT = -4; pub const MQTTCLIENT_PERSISTENCE_ERROR = -2; pub const linux = 1; pub const __ORDER_BIG_ENDIAN__ = 4321; pub const MQTT_SSL_VERSION_TLS_1_0 = 1; pub const __INTPTR_MAX__ = @as(c_long, 9223372036854775807); pub const __INT_LEAST8_FMTd__ = "hhd"; pub const __INTMAX_WIDTH__ = 64; pub const MQTTCLIENT_PERSISTENCE_NONE = 1; pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = 2; pub const _BITS_STDIO_LIM_H = 1; pub const __FLOAT128__ = 1; pub const __attribute_deprecated__ = __attribute__(__deprecated__); pub const MQTTCLIENT_FAILURE = -1; pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 3.64519953188247460253e-4951); pub const __GLIBC_MINOR__ = 30; pub const __PID_T_TYPE = __S32_TYPE; pub const __x86_64 = 1; pub const __CLANG_ATOMIC_LONG_LOCK_FREE = 2; pub const __INTMAX_MAX__ = @as(c_long, 9223372036854775807); pub const __INT8_FMTd__ = "hhd"; pub const __UINTMAX_WIDTH__ = 64; pub const __UINT8_MAX__ = 255; pub const __DBL_MIN__ = 2.2250738585072014e-308; pub const __GLIBC_USE_IEC_60559_FUNCS_EXT = 0; pub const __PRAGMA_REDEFINE_EXTNAME = 1; pub const __DBL_HAS_QUIET_NAN__ = 1; pub const __clang_minor__ = 0; pub const __LDBL_DECIMAL_DIG__ = 21; pub const MQTTCLIENT_BAD_UTF8_STRING = -5; pub const __USE_MISC = 1; pub const __WCHAR_TYPE__ = c_int; pub const __INT_FAST64_FMTd__ = "ld"; pub const _STDIO_H = 1; pub const __KEY_T_TYPE = __S32_TYPE; pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = 2; pub const __seg_fs = __attribute__(address_space(257)); pub const __attribute_malloc__ = __attribute__(__malloc__); pub const __HAVE_GENERIC_SELECTION = 1; pub const __INT16_FMTi__ = "hi"; pub const __UINTMAX_FMTX__ = "lX"; pub const __LDBL_MIN_EXP__ = -16381; pub const __PRFCHW__ = 1; pub const __ID_T_TYPE = __U32_TYPE; pub const __UINTMAX_FMTu__ = "lu"; pub const __UINT_LEAST16_FMTo__ = "ho"; pub const L_tmpnam = 20; pub const __glibc_has_include = __has_include; pub const _STDC_PREDEF_H = 1; pub const __UINT32_FMTu__ = "u"; pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = 1; pub const __SIG_ATOMIC_WIDTH__ = 32; pub const MQTTCLIENT_PERSISTENCE_DEFAULT = 0; pub const __amd64__ = 1; pub const __INT64_C_SUFFIX__ = L; pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.08420217248550443401e-19); pub const __CLANG_ATOMIC_INT_LOCK_FREE = 2; pub const _BITS_TYPESIZES_H = 1; pub const _IOLBF = 1; pub const __SSE2_MATH__ = 1; pub const __GCC_ATOMIC_SHORT_LOCK_FREE = 2; pub inline fn __P(args: anytype) @TypeOf(args) { return args; } pub const __TIME_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __POPCNT__ = 1; pub const __POINTER_WIDTH__ = 64; pub const __UINT64_FMTx__ = "lx"; pub const __ATOMIC_ACQ_REL = 4; pub const __UINT_LEAST32_FMTx__ = "x"; pub const __OFF_T_MATCHES_OFF64_T = 1; pub const __STDC_HOSTED__ = 1; pub const __INO64_T_TYPE = __UQUAD_TYPE; pub const __GNUC__ = 4; pub const __INT_FAST32_FMTi__ = "i"; pub const __PIC__ = 2; pub const __BLKCNT64_T_TYPE = __SQUAD_TYPE; pub const __GCC_ATOMIC_BOOL_LOCK_FREE = 2; pub const __seg_gs = __attribute__(address_space(256)); pub const __FXSR__ = 1; pub const __UINT64_FMTo__ = "lo"; pub const MQTTVERSION_DEFAULT = 0; pub const __UINT_FAST16_FMTx__ = "hx"; pub const MQTT_SSL_VERSION_TLS_1_2 = 3; pub const MQTTCLIENT_SSL_NOT_SUPPORTED = -10; pub const __CLOCK_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __GLIBC_USE_DEPRECATED_SCANF = 0; pub const __UINT_LEAST64_FMTo__ = "lo"; pub const __attribute_used__ = __attribute__(__used__); pub const __STDC_UTF_32__ = 1; pub const __FSFILCNT64_T_TYPE = __UQUAD_TYPE; pub const __PTRDIFF_WIDTH__ = 64; pub const __SIZE_WIDTH__ = 64; pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626e-4932); pub const __UINTMAX_MAX__ = @as(c_ulong, 18446744073709551615); pub const _SYS_CDEFS_H = 1; pub const __INT_LEAST16_FMTd__ = "hd"; pub const __SIZEOF_PTRDIFF_T__ = 8; pub inline fn __glibc_clang_prereq(maj: anytype, min: anytype) @TypeOf(__clang_major__ << 16 + __clang_minor__ >= maj << 16 + min) { return __clang_major__ << 16 + __clang_minor__ >= maj << 16 + min; } pub const __UINT_LEAST16_FMTu__ = "hu"; pub const __UINT16_FMTu__ = "hu"; pub const MQTTVERSION_3_1_1 = 4; pub const __DBL_MANT_DIG__ = 53; pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = 2; pub const __INT_LEAST64_FMTi__ = "li"; pub const __GNUC_STDC_INLINE__ = 1; pub const __UINT32_FMTX__ = "X"; pub const __DBL_DIG__ = 15; pub const __SHRT_MAX__ = 32767; pub inline fn va_copy(dest: anytype, src: anytype) @TypeOf(__builtin_va_copy(dest, src)) { return __builtin_va_copy(dest, src); } pub const __ATOMIC_CONSUME = 1; pub const __GLIBC_USE_DEPRECATED_GETS = 0; pub const __UINT_FAST16_FMTX__ = "hX"; pub const MQTTCLIENT_BAD_STRUCTURE = -8; pub const __FSBLKCNT_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __INT_FAST16_FMTi__ = "hi"; pub const __INT32_FMTd__ = "d"; pub const __INT8_MAX__ = 127; pub const __FLT_DECIMAL_DIG__ = 9; pub const __INT_LEAST32_FMTd__ = "d"; pub const MQTTCLIENT_BAD_PROTOCOL = -14; pub const __UINT8_FMTo__ = "hho"; pub const __USE_POSIX199506 = 1; pub const __struct_FILE_defined = 1; pub const __amdfam10__ = 1; pub inline fn __bos(ptr: anytype) @TypeOf(__builtin_object_size(ptr, __USE_FORTIFY_LEVEL > 1)) { return __builtin_object_size(ptr, __USE_FORTIFY_LEVEL > 1); } pub const __FLT_HAS_DENORM__ = 1; pub const __FLT_DIG__ = 6; pub const DLLExport = __attribute__(visibility("default")); pub const __INTPTR_FMTi__ = "li"; pub const __UINT32_FMTo__ = "o"; pub const __UINT_FAST64_MAX__ = @as(c_ulong, 18446744073709551615); pub const __GID_T_TYPE = __U32_TYPE; pub const MQTTCLIENT_NULL_PARAMETER = -6; pub const _____fpos_t_defined = 1; pub const __UINT_FAST64_FMTo__ = "lo"; pub const __GXX_ABI_VERSION = 1002; pub const __tune_amdfam10__ = 1; pub const __SIZEOF_LONG_LONG__ = 8; pub const __INT32_TYPE__ = c_int; pub inline fn __ASMNAME(cname: anytype) @TypeOf(__ASMNAME2(__USER_LABEL_PREFIX__, cname)) { return __ASMNAME2(__USER_LABEL_PREFIX__, cname); } pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = 3; pub const __UINTPTR_FMTX__ = "lX"; pub const __INT8_FMTi__ = "hhi"; pub const __SIZEOF_LONG_DOUBLE__ = 16; pub const __DBL_MIN_EXP__ = -1021; pub const __INT64_FMTi__ = "li"; pub const __INT_FAST64_FMTi__ = "li"; pub const __RLIM_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __attribute_const__ = __attribute__(__const__); pub inline fn __attribute_format_arg__(x: anytype) @TypeOf(__attribute__(__format_arg__(x))) { return __attribute__(__format_arg__(x)); } pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = 1; pub const __clang_major__ = 9; pub const __USE_ISOC95 = 1; pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = 4; pub const __INT16_MAX__ = 32767; pub const __linux = 1; pub const __OFF_T_TYPE = __SYSCALL_SLONG_TYPE; pub const MQTTCLIENT_BAD_QOS = -9; pub const __GCC_ATOMIC_LLONG_LOCK_FREE = 2; pub const FILENAME_MAX = 4096; pub const __UINT16_FMTo__ = "ho"; pub const BUFSIZ = 8192; pub const __INT_FAST8_FMTi__ = "hhi"; pub const __NLINK_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __UINT_FAST64_FMTx__ = "lx"; pub const __GLIBC_USE_LIB_EXT2 = 0; pub const __UINT_LEAST8_MAX__ = 255; pub const __LDBL_HAS_INFINITY__ = 1; pub const __UINT_LEAST32_FMTX__ = "X"; pub const __WORDSIZE = 64; pub const __USE_POSIX = 1; pub const __UINT_LEAST16_MAX__ = 65535; pub const __unix = 1; pub const __CONSTANT_CFSTRINGS__ = 1; pub const __SSE_MATH__ = 1; pub const __DBL_EPSILON__ = 2.2204460492503131e-16; pub const __TIME64_T_TYPE = __TIME_T_TYPE; pub const __llvm__ = 1; pub const __SLONG32_TYPE = c_int; pub const __DBL_MAX_EXP__ = 1024; pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = 2; pub const MQTTCLIENT_BAD_MQTT_OPTION = -15; pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = 2; pub inline fn __glibc_unlikely(cond: anytype) @TypeOf(__builtin_expect(cond, 0)) { return __builtin_expect(cond, 0); } pub const __GCC_ASM_FLAG_OUTPUTS__ = 1; pub inline fn __glibc_has_attribute(attr: anytype) @TypeOf(__has_attribute(attr)) { return __has_attribute(attr); } pub const __PTRDIFF_MAX__ = @as(c_long, 9223372036854775807); pub const __ORDER_LITTLE_ENDIAN__ = 1234; pub const __linux__ = 1; pub const __INT16_TYPE__ = c_short; pub const __attribute_noinline__ = __attribute__(__noinline__); pub const __FSWORD_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __UINTPTR_FMTx__ = "lx"; pub const __USE_ISOC99 = 1; pub const __LDBL_MAX_EXP__ = 16384; pub const __UINT_FAST32_MAX__ = @as(c_uint, 4294967295); pub const __3dNOW_A__ = 1; pub const __S32_TYPE = c_int; pub const __FLT_RADIX__ = 2; pub const __FD_SETSIZE = 1024; pub const __amd64 = 1; pub const __WINT_MAX__ = @as(c_uint, 4294967295); pub const _IOFBF = 0; pub inline fn __attribute_format_strfmon__(a: anytype, b: anytype) @TypeOf(__attribute__(__format__(__strfmon__, a, b))) { return __attribute__(__format__(__strfmon__, a, b)); } pub const __UINTPTR_FMTo__ = "lo"; pub const __INT32_MAX__ = 2147483647; pub const __INTPTR_FMTd__ = "ld"; pub inline fn va_arg(ap: anytype, type_1: anytype) @TypeOf(__builtin_va_arg(ap, type_1)) { return __builtin_va_arg(ap, type_1); } pub const __USECONDS_T_TYPE = __U32_TYPE; pub const __INTPTR_WIDTH__ = 64; pub const MQTT_INVALID_PROPERTY_ID = -2; pub const __INT_FAST32_MAX__ = 2147483647; pub const _BITS_TIME64_H = 1; pub const __INT32_FMTi__ = "i"; pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = 2; pub const __UINT_FAST16_FMTo__ = "ho"; pub const __USE_ISOC11 = 1; pub const __GCC_ATOMIC_INT_LOCK_FREE = 2; pub const __FILE_defined = 1; pub const __FLT_HAS_QUIET_NAN__ = 1; pub const __INT_LEAST32_TYPE__ = c_int; pub const __BIGGEST_ALIGNMENT__ = 16; pub inline fn __REDIRECT_LDBL(name: anytype, proto: anytype, alias: anytype) @TypeOf(__REDIRECT(name, proto, alias)) { return __REDIRECT(name, proto, alias); } pub const __GCC_ATOMIC_POINTER_LOCK_FREE = 2; pub const __SIZE_MAX__ = @as(c_ulong, 18446744073709551615); pub const __INT_FAST64_MAX__ = @as(c_long, 9223372036854775807); pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = 2; pub const __UINTPTR_MAX__ = @as(c_ulong, 18446744073709551615); pub const __UINT_FAST32_FMTx__ = "x"; pub const __PTRDIFF_FMTd__ = "ld"; pub const __INO_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807); pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = 2; pub const __WCHAR_MAX__ = 2147483647; pub const __ATOMIC_SEQ_CST = 5; pub const __LDBL_MANT_DIG__ = 64; pub const __UINT_FAST8_MAX__ = 255; pub const __SIZEOF_SIZE_T__ = 8; pub const __STDC_VERSION__ = @as(c_long, 201112); pub const __THROWNL = __attribute__(__nothrow__); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = 1; pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = 1; pub const __SSIZE_T_TYPE = __SWORD_TYPE; pub const L_ctermid = 9; pub const __DEV_T_TYPE = __UQUAD_TYPE; pub const __SIZEOF_INT__ = 4; pub const __TIMESIZE = __WORDSIZE; pub const __UINT32_C_SUFFIX__ = U; pub const __x86_64__ = 1; pub inline fn va_end(ap: anytype) @TypeOf(__builtin_va_end(ap)) { return __builtin_va_end(ap); } pub const __SUSECONDS_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __FLT_MANT_DIG__ = 24; pub const __INT_LEAST8_MAX__ = 127; pub const __GLIBC_USE_IEC_60559_TYPES_EXT = 0; pub const __UINTMAX_FMTo__ = "lo"; pub const ____mbstate_t_defined = 1; pub const __SIZE_FMTo__ = "lo"; pub const __SIZEOF_DOUBLE__ = 8; pub const __USE_ATFILE = 1; pub const __USE_POSIX_IMPLICITLY = 1; pub const __SIZEOF_WCHAR_T__ = 4; pub const _G_fpos_t = struct__G_fpos_t; pub const _G_fpos64_t = struct__G_fpos64_t; pub const _IO_marker = struct__IO_marker; pub const _IO_codecvt = struct__IO_codecvt; pub const _IO_wide_data = struct__IO_wide_data; pub const _IO_FILE = struct__IO_FILE; pub const __va_list_tag = struct___va_list_tag; pub const MQTTPropertyCodes = enum_MQTTPropertyCodes; pub const MQTTPropertyTypes = enum_MQTTPropertyTypes; pub const MQTTReasonCodes = enum_MQTTReasonCodes; pub const MQTTCLIENT_TRACE_LEVELS = enum_MQTTCLIENT_TRACE_LEVELS;
mqtt_paho.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/day15.txt", run); fn computeLowestExitLevel(alloc: std.mem.Allocator, width: usize, height: usize, ctx: anytype, comptime getIndividualLevel: fn (self: @TypeOf(ctx), x: u32, y: u32) u8) !u32 { const Step = packed struct { x: u16, y: u16, level: u16, fn compare(_: void, a: @This(), b: @This()) std.math.Order { //return std.math.order(a.level, b.level); plus lent. bizarre // testΓ© avec prio = level + k*((width-x)+(hight-y)) -> moins bien. Facteur limitant = taille de la queue. if (a.level < b.level) return .lt; if (a.level > b.level) return .gt; //if (a.x < b.x or a.y < b.y) return .gt; //if (a.x > b.x or a.y > b.y) return .lt; return .eq; } }; var queue = std.PriorityDequeue(Step, void, Step.compare).init(alloc, {}); // dequeue way faster than queue defer queue.deinit(); const acculevels = try alloc.alloc(u16, width * height); defer alloc.free(acculevels); std.mem.set(u16, acculevels, 0x7FFF); //var best: u16 = 0x7FFF; // useless, pas grand chose Γ  Γ©laguer // start point try queue.add(Step{ .x = 0, .y = 0, .level = 0 }); while (queue.removeMinOrNull()) |step| { //if (step.level >= best) continue; const x = step.x; const y = step.y; const index = x + width * y; const this = &acculevels[index]; if (step.level >= this.*) continue; this.* = step.level; if (x > 0) { const l = step.level + getIndividualLevel(ctx, x - 1, y); if (l < acculevels[index - 1]) { // and (l < best) acculevels[index - 1] = l + 1; // (+1 to make sure than when the step is popped from the queue it is not ignored) try queue.add(Step{ .x = (x - 1), .y = (y + 0), .level = l }); } } if (y > 0) { const l = step.level + getIndividualLevel(ctx, x, y - 1); if (l < acculevels[index - width]) { // and (l < best) acculevels[index - width] = l + 1; try queue.add(Step{ .x = (x + 0), .y = (y - 1), .level = l }); } } if (x + 1 < width) { const l = step.level + getIndividualLevel(ctx, x + 1, y); if (l < acculevels[index + 1]) { // and (l < best) acculevels[index + 1] = l + 1; try queue.add(Step{ .x = (x + 1), .y = (y + 0), .level = l }); } } if (y + 1 < height) { const l = step.level + getIndividualLevel(ctx, x, y + 1); if (l < acculevels[index + width]) { // and (l < best) acculevels[index + width] = l + 1; try queue.add(Step{ .x = (x + 0), .y = (y + 1), .level = l }); } } //if (index == width * height - 1) { // // En fait vu qu'on a prio == level, on fait un best-first-search, et donc on sait que tous les levels suivants seront >= best. // // Mais Γ§a ne compense pas le test en plus // break; //} } if (false) { var y: u32 = 0; while (y < height) : (y += 1) { var x: u32 = 0; while (x < width) : (x += 1) { trace("{d:2} ", .{@minimum(99, acculevels[x + width * y])}); } trace("\n", .{}); } } return acculevels[width * height - 1]; } 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 stride_in = std.mem.indexOfScalar(u8, input, '\n').? + 1; const height = (input.len + 1) / stride_in; const width = stride_in - 1; trace("input: {}x{}\n", .{ width, height }); const ans1 = ans: { const context: struct { risk: []const u8, stride: usize, fn entryRisk(ctx: *const @This(), x: u32, y: u32) u8 { return ctx.risk[x + y * ctx.stride] - '0'; } } = .{ .risk = input, .stride = stride_in }; break :ans computeLowestExitLevel(gpa, width, height, &context, @TypeOf(context).entryRisk); // context.entryRisk == "BoundFn"? comment Γ§a s'utilise? }; const ans2 = ans: { const context: struct { risk: []const u8, stride: usize, w: usize, h: usize, fn entryRisk(ctx: *const @This(), x: u32, y: u32) u8 { // nb: hardcoder w,h = 100x100 ne gagne pas tant que Γ§a (15%) const x0 = x % ctx.w; const y0 = y % ctx.h; const dist = (x / ctx.w) + (y / ctx.h); const v = ctx.risk[x0 + y0 * ctx.stride] - '0'; return @intCast(u8, (v + dist - 1) % 9 + 1); } } = .{ .risk = input, .w = width, .h = height, .stride = stride_in }; break :ans computeLowestExitLevel(gpa, 5 * width, 5 * height, &context, @TypeOf(context).entryRisk); // context.entryRisk == "BoundFn"? comment Γ§a s'utilise? }; return [_][]const u8{ try std.fmt.allocPrint(gpa, "{}", .{ans1}), try std.fmt.allocPrint(gpa, "{}", .{ans2}), }; } test { const res0 = try run( \\1163751742 \\1381373672 \\2136511328 \\3694931569 \\7463417111 \\1319128137 \\1359912421 \\3125421639 \\1293138521 \\2311944581 , std.testing.allocator); defer std.testing.allocator.free(res0[0]); defer std.testing.allocator.free(res0[1]); try std.testing.expectEqualStrings("40", res0[0]); try std.testing.expectEqualStrings("315", res0[1]); }
2021/day15.zig
const w4 = @import("../wasm4.zig"); const sprites = @import("../assets/sprites.zig"); const gamepad = @import("../gamepad.zig"); const statemachine = @import("../state-machine.zig"); var start_ticks: u32 = 0; pub fn handleInput(state: *statemachine.StateMachine, pl: *const gamepad.GamePad) void { if (pl.isPressed(w4.BUTTON_DOWN) or pl.isPressed(w4.BUTTON_UP) or pl.isPressed(w4.BUTTON_LEFT) or pl.isPressed(w4.BUTTON_RIGHT) or pl.isPressed(w4.BUTTON_1) or pl.isPressed(w4.BUTTON_2)) { state.change(.IN_MENU); } } pub fn update(state: *statemachine.StateMachine, pl: *const gamepad.GamePad) void { handleInput(state, pl); var xOff: u32 = 0; if (start_ticks % 20 > 10) { xOff = 16; } w4.DRAW_COLORS.* = 0x0432; w4.blit(sprites.title.data, 7, 0, // x, y sprites.title.width, sprites.title.height, sprites.title.flags); for ([_]i32{ 0, 1, 2, 3, 4 }) |i| { w4.blit(sprites.pavement.data, i * (32), 100, sprites.pavement.height, sprites.pavement.height, sprites.pavement.flags); } w4.blitSub(sprites.flag.data, 79, 72 - (32 / 2), // x, y sprites.flag.height, sprites.flag.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.flag.width, // Assumes stride and width are equal sprites.flag.flags); for ([_]i32{ 0, 1, 3, 4 }) |i| { w4.blit(sprites.house.data, i * (32), 72, sprites.house.width, sprites.house.height, sprites.house.flags); } w4.blit(sprites.noten.data, 72 - (sprites.noten.width / 4), 72, // x, y sprites.noten.width, sprites.noten.height, sprites.noten.flags); w4.blitSub(sprites.boris.data, 45, 78 + (32 / 2), // x, y sprites.boris.height, sprites.boris.height, // w, h; Assumes square xOff, 0, // src_x, src_y sprites.boris.width, // Assumes stride and width are equal sprites.boris.flags); // The text is 1bpp, so it gets its own palette w4.DRAW_COLORS.* = 0x0002; w4.blit(sprites.pab.data, 53, 140, // x, y sprites.pab.width, sprites.pab.height, sprites.pab.flags); start_ticks += 1; }
src/screens/start-screen.zig
const std = @import("std"); const assert = std.debug.assert; const math = std.math; const mem = std.mem; const sort = std.sort; const testing = std.testing; const Allocator = std.mem.Allocator; const bu = @import("bits_utils.zig"); const deflate_const = @import("deflate_const.zig"); const max_bits_limit = 16; const LiteralNode = struct { literal: u16, freq: u16, }; // Describes the state of the constructed tree for a given depth. const LevelInfo = struct { // Our level. for better printing level: u32, // The frequency of the last node at this level last_freq: u32, // The frequency of the next character to add to this level next_char_freq: u32, // The frequency of the next pair (from level below) to add to this level. // Only valid if the "needed" value of the next lower level is 0. next_pair_freq: u32, // The number of chains remaining to generate for this level before moving // up to the next level needed: u32, }; // hcode is a huffman code with a bit code and bit length. pub const HuffCode = struct { code: u16 = 0, len: u16 = 0, // set sets the code and length of an hcode. fn set(self: *HuffCode, code: u16, length: u16) void { self.len = length; self.code = code; } }; pub const HuffmanEncoder = struct { codes: []HuffCode, freq_cache: []LiteralNode = undefined, bit_count: [17]u32 = undefined, lns: []LiteralNode = undefined, // sorted by literal, stored to avoid repeated allocation in generate lfs: []LiteralNode = undefined, // sorted by frequency, stored to avoid repeated allocation in generate allocator: Allocator, pub fn deinit(self: *HuffmanEncoder) void { self.allocator.free(self.codes); self.allocator.free(self.freq_cache); } // Update this Huffman Code object to be the minimum code for the specified frequency count. // // freq An array of frequencies, in which frequency[i] gives the frequency of literal i. // max_bits The maximum number of bits to use for any literal. pub fn generate(self: *HuffmanEncoder, freq: []u16, max_bits: u32) void { var list = self.freq_cache[0 .. freq.len + 1]; // Number of non-zero literals var count: u32 = 0; // Set list to be the set of all non-zero literals and their frequencies for (freq) |f, i| { if (f != 0) { list[count] = LiteralNode{ .literal = @intCast(u16, i), .freq = f }; count += 1; } else { list[count] = LiteralNode{ .literal = 0x00, .freq = 0 }; self.codes[i].len = 0; } } list[freq.len] = LiteralNode{ .literal = 0x00, .freq = 0 }; list = list[0..count]; if (count <= 2) { // Handle the small cases here, because they are awkward for the general case code. With // two or fewer literals, everything has bit length 1. for (list) |node, i| { // "list" is in order of increasing literal value. self.codes[node.literal].set(@intCast(u16, i), 1); } return; } self.lfs = list; sort.sort(LiteralNode, self.lfs, {}, byFreq); // Get the number of literals for each bit count var bit_count = self.bitCounts(list, max_bits); // And do the assignment self.assignEncodingAndSize(bit_count, list); } pub fn bitLength(self: *HuffmanEncoder, freq: []u16) u32 { var total: u32 = 0; for (freq) |f, i| { if (f != 0) { total += @intCast(u32, f) * @intCast(u32, self.codes[i].len); } } return total; } // Return the number of literals assigned to each bit size in the Huffman encoding // // This method is only called when list.len >= 3 // The cases of 0, 1, and 2 literals are handled by special case code. // // list: An array of the literals with non-zero frequencies // and their associated frequencies. The array is in order of increasing // frequency, and has as its last element a special element with frequency // std.math.maxInt(i32) // // max_bits: The maximum number of bits that should be used to encode any literal. // Must be less than 16. // // Returns an integer array in which array[i] indicates the number of literals // that should be encoded in i bits. fn bitCounts(self: *HuffmanEncoder, list: []LiteralNode, max_bits_to_use: usize) []u32 { var max_bits = max_bits_to_use; var n = list.len; assert(max_bits < max_bits_limit); // The tree can't have greater depth than n - 1, no matter what. This // saves a little bit of work in some small cases max_bits = @minimum(max_bits, n - 1); // Create information about each of the levels. // A bogus "Level 0" whose sole purpose is so that // level1.prev.needed == 0. This makes level1.next_pair_freq // be a legitimate value that never gets chosen. var levels: [max_bits_limit]LevelInfo = mem.zeroes([max_bits_limit]LevelInfo); // leaf_counts[i] counts the number of literals at the left // of ancestors of the rightmost node at level i. // leaf_counts[i][j] is the number of literals at the left // of the level j ancestor. var leaf_counts: [max_bits_limit][max_bits_limit]u32 = mem.zeroes([max_bits_limit][max_bits_limit]u32); { var level = @as(u32, 1); while (level <= max_bits) : (level += 1) { // For every level, the first two items are the first two characters. // We initialize the levels as if we had already figured this out. levels[level] = LevelInfo{ .level = level, .last_freq = list[1].freq, .next_char_freq = list[2].freq, .next_pair_freq = list[0].freq + list[1].freq, .needed = 0, }; leaf_counts[level][level] = 2; if (level == 1) { levels[level].next_pair_freq = math.maxInt(i32); } } } // We need a total of 2*n - 2 items at top level and have already generated 2. levels[max_bits].needed = 2 * @intCast(u32, n) - 4; { var level = max_bits; while (true) { var l = &levels[level]; if (l.next_pair_freq == math.maxInt(i32) and l.next_char_freq == math.maxInt(i32)) { // We've run out of both leafs and pairs. // End all calculations for this level. // To make sure we never come back to this level or any lower level, // set next_pair_freq impossibly large. l.needed = 0; levels[level + 1].next_pair_freq = math.maxInt(i32); level += 1; continue; } var prev_freq = l.last_freq; if (l.next_char_freq < l.next_pair_freq) { // The next item on this row is a leaf node. var next = leaf_counts[level][level] + 1; l.last_freq = l.next_char_freq; // Lower leaf_counts are the same of the previous node. leaf_counts[level][level] = next; if (next >= list.len) { l.next_char_freq = maxNode().freq; } else { l.next_char_freq = list[next].freq; } } else { // The next item on this row is a pair from the previous row. // next_pair_freq isn't valid until we generate two // more values in the level below l.last_freq = l.next_pair_freq; // Take leaf counts from the lower level, except counts[level] remains the same. mem.copy(u32, leaf_counts[level][0..level], leaf_counts[level - 1][0..level]); levels[l.level - 1].needed = 2; } l.needed -= 1; if (l.needed == 0) { // We've done everything we need to do for this level. // Continue calculating one level up. Fill in next_pair_freq // of that level with the sum of the two nodes we've just calculated on // this level. if (l.level == max_bits) { // All done! break; } levels[l.level + 1].next_pair_freq = prev_freq + l.last_freq; level += 1; } else { // If we stole from below, move down temporarily to replenish it. while (levels[level - 1].needed > 0) { level -= 1; if (level == 0) { break; } } } } } // Somethings is wrong if at the end, the top level is null or hasn't used // all of the leaves. assert(leaf_counts[max_bits][max_bits] == n); var bit_count = self.bit_count[0 .. max_bits + 1]; var bits: u32 = 1; var counts = &leaf_counts[max_bits]; { var level = max_bits; while (level > 0) : (level -= 1) { // counts[level] gives the number of literals requiring at least "bits" // bits to encode. bit_count[bits] = counts[level] - counts[level - 1]; bits += 1; if (level == 0) { break; } } } return bit_count; } // Look at the leaves and assign them a bit count and an encoding as specified // in RFC 1951 3.2.2 fn assignEncodingAndSize(self: *HuffmanEncoder, bit_count: []u32, list_arg: []LiteralNode) void { var code = @as(u16, 0); var list = list_arg; for (bit_count) |bits, n| { code <<= 1; if (n == 0 or bits == 0) { continue; } // The literals list[list.len-bits] .. list[list.len-bits] // are encoded using "bits" bits, and get the values // code, code + 1, .... The code values are // assigned in literal order (not frequency order). var chunk = list[list.len - @intCast(u32, bits) ..]; self.lns = chunk; sort.sort(LiteralNode, self.lns, {}, byLiteral); for (chunk) |node| { self.codes[node.literal] = HuffCode{ .code = bu.bitReverse(u16, code, @intCast(u5, n)), .len = @intCast(u16, n), }; code += 1; } list = list[0 .. list.len - @intCast(u32, bits)]; } } }; fn maxNode() LiteralNode { return LiteralNode{ .literal = math.maxInt(u16), .freq = math.maxInt(u16), }; } pub fn newHuffmanEncoder(allocator: Allocator, size: u32) !HuffmanEncoder { return HuffmanEncoder{ .codes = try allocator.alloc(HuffCode, size), // Allocate a reusable buffer with the longest possible frequency table. // (deflate_const.max_num_frequencies). .freq_cache = try allocator.alloc(LiteralNode, deflate_const.max_num_frequencies + 1), .allocator = allocator, }; } // Generates a HuffmanCode corresponding to the fixed literal table pub fn generateFixedLiteralEncoding(allocator: Allocator) !HuffmanEncoder { var h = try newHuffmanEncoder(allocator, deflate_const.max_num_frequencies); var codes = h.codes; var ch: u16 = 0; while (ch < deflate_const.max_num_frequencies) : (ch += 1) { var bits: u16 = undefined; var size: u16 = undefined; switch (ch) { 0...143 => { // size 8, 000110000 .. 10111111 bits = ch + 48; size = 8; }, 144...255 => { // size 9, 110010000 .. 111111111 bits = ch + 400 - 144; size = 9; }, 256...279 => { // size 7, 0000000 .. 0010111 bits = ch - 256; size = 7; }, else => { // size 8, 11000000 .. 11000111 bits = ch + 192 - 280; size = 8; }, } codes[ch] = HuffCode{ .code = bu.bitReverse(u16, bits, @intCast(u5, size)), .len = size }; } return h; } pub fn generateFixedOffsetEncoding(allocator: Allocator) !HuffmanEncoder { var h = try newHuffmanEncoder(allocator, 30); var codes = h.codes; for (codes) |_, ch| { codes[ch] = HuffCode{ .code = bu.bitReverse(u16, @intCast(u16, ch), 5), .len = 5 }; } return h; } fn byLiteral(context: void, a: LiteralNode, b: LiteralNode) bool { _ = context; return a.literal < b.literal; } fn byFreq(context: void, a: LiteralNode, b: LiteralNode) bool { _ = context; if (a.freq == b.freq) { return a.literal < b.literal; } return a.freq < b.freq; } test "generate a Huffman code from an array of frequencies" { var freqs: [19]u16 = [_]u16{ 8, // 0 1, // 1 1, // 2 2, // 3 5, // 4 10, // 5 9, // 6 1, // 7 0, // 8 0, // 9 0, // 10 0, // 11 0, // 12 0, // 13 0, // 14 0, // 15 1, // 16 3, // 17 5, // 18 }; var enc = try newHuffmanEncoder(testing.allocator, freqs.len); defer enc.deinit(); enc.generate(freqs[0..], 7); try testing.expect(enc.bitLength(freqs[0..]) == 141); try testing.expect(enc.codes[0].len == 3); try testing.expect(enc.codes[1].len == 6); try testing.expect(enc.codes[2].len == 6); try testing.expect(enc.codes[3].len == 5); try testing.expect(enc.codes[4].len == 3); try testing.expect(enc.codes[5].len == 2); try testing.expect(enc.codes[6].len == 2); try testing.expect(enc.codes[7].len == 6); try testing.expect(enc.codes[8].len == 0); try testing.expect(enc.codes[9].len == 0); try testing.expect(enc.codes[10].len == 0); try testing.expect(enc.codes[11].len == 0); try testing.expect(enc.codes[12].len == 0); try testing.expect(enc.codes[13].len == 0); try testing.expect(enc.codes[14].len == 0); try testing.expect(enc.codes[15].len == 0); try testing.expect(enc.codes[16].len == 6); try testing.expect(enc.codes[17].len == 5); try testing.expect(enc.codes[18].len == 3); try testing.expect(enc.codes[5].code == 0x0); try testing.expect(enc.codes[6].code == 0x2); try testing.expect(enc.codes[0].code == 0x1); try testing.expect(enc.codes[4].code == 0x5); try testing.expect(enc.codes[18].code == 0x3); try testing.expect(enc.codes[3].code == 0x7); try testing.expect(enc.codes[17].code == 0x17); try testing.expect(enc.codes[1].code == 0x0f); try testing.expect(enc.codes[2].code == 0x2f); try testing.expect(enc.codes[7].code == 0x1f); try testing.expect(enc.codes[16].code == 0x3f); } test "generate a Huffman code for the fixed litteral table specific to Deflate" { var enc = try generateFixedLiteralEncoding(testing.allocator); defer enc.deinit(); } test "generate a Huffman code for the 30 possible relative offsets (LZ77 distances) of Deflate" { var enc = try generateFixedOffsetEncoding(testing.allocator); defer enc.deinit(); }
lib/std/compress/deflate/huffman_code.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const data = @embedFile("data/day24.txt"); const EntriesList = std.ArrayList(Record); const Map = std.AutoHashMap(Record, void); const Record = extern struct { x: i32 = 0, y: i32 = 0, fn min(a: Record, b: Record) Record { return .{ .x = if (a.x < b.x) a.x else b.x, .y = if (a.y < b.y) a.y else b.y, }; } fn max(a: Record, b: Record) Record { return .{ .x = if (a.x > b.x) a.x else b.x, .y = if (a.y > b.y) a.y else b.y, }; } fn add(a: Record, b: Record) Record { return .{ .x = a.x + b.x, .y = a.y + b.y, }; } }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const ally = &arena.allocator; var lines = std.mem.tokenize(data, "\r\n"); var entries = EntriesList.init(ally); try entries.ensureCapacity(400); var map = Map.init(ally); var result: usize = 0; var min = Record{}; var max = Record{}; while (lines.next()) |line| { if (line.len == 0) continue; var pos = Record{}; var rest = line; while (rest.len > 0) { switch (rest[0]) { 's' => { pos.y -= 1; pos.x -= @intCast(i32, @boolToInt(rest[1] == 'w')); rest = rest[2..]; }, 'n' => { pos.y += 1; pos.x += @intCast(i32, @boolToInt(rest[1] == 'e')); rest = rest[2..]; }, 'e' => { pos.x += 1; rest = rest[1..]; }, 'w' => { pos.x -= 1; rest = rest[1..]; }, else => unreachable, } } if (map.remove(pos)) |_| { } else { try map.put(pos, {}); min = min.min(pos); max = max.max(pos); } } var next_map = Map.init(ally); const neighbors = [_]Record{ .{ .x = 0, .y = 1 }, .{ .x = 1, .y = 1 }, .{ .x = -1, .y = 0 }, .{ .x = 1, .y = 0 }, .{ .x = -1, .y = -1 }, .{ .x = 0, .y = -1 }, }; print("initial: {}\n", .{map.count()}); dump_map(map, min, max); var iteration: usize = 0; while (iteration < 100) : (iteration += 1) { var next_min = Record{}; var next_max = Record{}; var y = min.y-1; while (y <= max.y+1) : (y += 1) { var x = min.x-1; while (x <= max.x+1) : (x += 1) { const self = Record{ .x = x, .y = y }; var num_neigh: usize = 0; for (neighbors) |offset| { var pos = offset.add(self); if (map.contains(pos)) { num_neigh += 1; } } if (map.contains(self)) { if (num_neigh == 1 or num_neigh == 2) { try next_map.put(self, {}); next_max = next_max.max(self); next_min = next_min.min(self); } } else { if (num_neigh == 2) { try next_map.put(self, {}); next_max = next_max.max(self); next_min = next_min.min(self); } } } } min = next_min; max = next_max; const tmp = next_map; next_map = map; map = tmp; next_map.clearRetainingCapacity(); const day = iteration + 1; if (day <= 10 or day % 10 == 0) { print("day {: >2}: {}\n", .{day, map.count()}); //dump_map(map, min, max); } } print("Result: {}\n", .{map.count()}); } fn dump_map(map: Map, min: Record, max: Record) void { print("map @ ({}, {})\n", .{min.x-1, max.x-1}); var y = min.y-1; while (y <= max.y+1) : (y += 1) { var offset = (max.y+1) - y; var i: i32 = 0; while (i < offset) : (i += 1) { print(" ", .{}); } var x = min.x-1; while (x <= max.x+1) : (x += 1) { if (map.contains(.{.x = x, .y = y})) { print("# ", .{}); } else { print(". ", .{}); } } print("\n", .{}); } print("\n", .{}); }
src/day24.zig
const std = @import("std"); const smithy = @import("smithy"); const snake = @import("snake.zig"); const json_zig = @embedFile("json.zig"); pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); const stdout = std.io.getStdOut().writer(); const json_file = try std.fs.cwd().createFile("json.zig", .{}); defer json_file.close(); try json_file.writer().writeAll(json_zig); const manifest_file = try std.fs.cwd().createFile("service_manifest.zig", .{}); defer manifest_file.close(); const manifest = manifest_file.writer(); var inx: u32 = 0; for (args) |arg| { if (inx == 0) { inx = inx + 1; continue; } try processFile(arg, stdout, manifest); inx = inx + 1; } if (args.len == 0) _ = try generateServices(allocator, ";", std.io.getStdIn(), stdout); } fn processFile(arg: []const u8, stdout: anytype, manifest: anytype) !void { // It's probably best to create our own allocator here so we can deint at the end and // toss all allocations related to the services in this file // I can't guarantee we're not leaking something, and at the end of the // day I'm not sure we want to track down leaks var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var writer = &stdout; var file: std.fs.File = undefined; const filename = try std.fmt.allocPrint(allocator, "{s}.zig", .{arg}); defer allocator.free(filename); file = try std.fs.cwd().createFile(filename, .{ .truncate = true }); errdefer file.close(); writer = &file.writer(); _ = try writer.write("const std = @import(\"std\");\n"); _ = try writer.write("const serializeMap = @import(\"json.zig\").serializeMap;\n"); _ = try writer.write("const smithy = @import(\"smithy\");\n\n"); std.log.info("Processing file: {s}", .{arg}); const service_names = generateServicesForFilePath(allocator, ";", arg, writer) catch |err| { std.log.err("Error processing file: {s}", .{arg}); return err; }; defer { for (service_names) |name| allocator.free(name); allocator.free(service_names); } file.close(); for (service_names) |name| { try manifest.print("pub const {s} = @import(\"{s}\");\n", .{ name, std.fs.path.basename(filename) }); } } fn generateServicesForFilePath(allocator: std.mem.Allocator, comptime terminator: []const u8, path: []const u8, writer: anytype) ![][]const u8 { const file = try std.fs.cwd().openFile(path, .{ .read = true, .write = false }); defer file.close(); return try generateServices(allocator, terminator, file, writer); } fn addReference(id: []const u8, map: *std.StringHashMap(u64)) !void { const res = try map.getOrPut(id); if (res.found_existing) { res.value_ptr.* += 1; } else { res.value_ptr.* = 1; } } fn countAllReferences(shape_ids: [][]const u8, shapes: std.StringHashMap(smithy.ShapeInfo), shape_references: *std.StringHashMap(u64), stack: *std.ArrayList([]const u8)) anyerror!void { for (shape_ids) |id| { try countReferences(shapes.get(id).?, shapes, shape_references, stack); } } fn countTypeMembersReferences(type_members: []smithy.TypeMember, shapes: std.StringHashMap(smithy.ShapeInfo), shape_references: *std.StringHashMap(u64), stack: *std.ArrayList([]const u8)) anyerror!void { for (type_members) |m| { try countReferences(shapes.get(m.target).?, shapes, shape_references, stack); } } fn countReferences(shape: smithy.ShapeInfo, shapes: std.StringHashMap(smithy.ShapeInfo), shape_references: *std.StringHashMap(u64), stack: *std.ArrayList([]const u8)) anyerror!void { // Add ourselves as a reference, then we will continue down the tree try addReference(shape.id, shape_references); // Put ourselves on the stack. If we come back to ourselves, we want to end. for (stack.items) |i| { if (std.mem.eql(u8, shape.id, i)) return; } try stack.append(shape.id); defer _ = stack.pop(); // Well, this is a fun read: https://awslabs.github.io/smithy/1.0/spec/core/model.html#recursive-shape-definitions // Looks like recursion has special rules in the spec to accomodate Java. // This is silly and we will ignore switch (shape.shape) { // We don't care about these primitives - they don't have children .blob, .boolean, .string, .byte, .short, .integer, .long, .float, .double, .bigInteger, .bigDecimal, .timestamp, => {}, .document, .member, .resource => {}, // less sure about these? .list => |i| try countReferences(shapes.get(i.member_target).?, shapes, shape_references, stack), .set => |i| try countReferences(shapes.get(i.member_target).?, shapes, shape_references, stack), .map => |i| { try countReferences(shapes.get(i.key).?, shapes, shape_references, stack); try countReferences(shapes.get(i.value).?, shapes, shape_references, stack); }, .structure => |m| try countTypeMembersReferences(m.members, shapes, shape_references, stack), .uniontype => |m| try countTypeMembersReferences(m.members, shapes, shape_references, stack), .service => |i| try countAllReferences(i.operations, shapes, shape_references, stack), .operation => |op| { if (op.input) |i| try countReferences(shapes.get(i).?, shapes, shape_references, stack); if (op.output) |i| try countReferences(shapes.get(i).?, shapes, shape_references, stack); if (op.errors) |i| try countAllReferences(i, shapes, shape_references, stack); }, } } fn generateServices(allocator: std.mem.Allocator, comptime _: []const u8, file: std.fs.File, writer: anytype) ![][]const u8 { const json = try file.readToEndAlloc(allocator, 1024 * 1024 * 1024); defer allocator.free(json); const model = try smithy.parse(allocator, json); defer model.deinit(); var shapes = std.StringHashMap(smithy.ShapeInfo).init(allocator); defer shapes.deinit(); var services = std.ArrayList(smithy.ShapeInfo).init(allocator); defer services.deinit(); for (model.shapes) |shape| { try shapes.put(shape.id, shape); switch (shape.shape) { .service => try services.append(shape), else => {}, } } // At this point we want to generate a graph of shapes, starting // services -> operations -> other shapes. This will allow us to get // a reference count in case there are recursive data structures var shape_references = std.StringHashMap(u64).init(allocator); defer shape_references.deinit(); var stack = std.ArrayList([]const u8).init(allocator); defer stack.deinit(); for (services.items) |service| try countReferences(service, shapes, &shape_references, &stack); var constant_names = std.ArrayList([]const u8).init(allocator); defer constant_names.deinit(); var unresolved = std.ArrayList(smithy.ShapeInfo).init(allocator); defer unresolved.deinit(); var generated = std.StringHashMap(void).init(allocator); defer generated.deinit(); var state = FileGenerationState{ .shape_references = shape_references, .additional_types_to_generate = &unresolved, .additional_types_generated = &generated, .shapes = shapes, }; for (services.items) |service| { var sdk_id: []const u8 = undefined; var version: []const u8 = service.shape.service.version; var name: []const u8 = service.name; var arn_namespace: []const u8 = undefined; var sigv4_name: []const u8 = undefined; var endpoint_prefix: []const u8 = undefined; var aws_protocol: smithy.AwsProtocol = undefined; for (service.shape.service.traits) |trait| { // need the info/get the info switch (trait) { .aws_api_service => { arn_namespace = trait.aws_api_service.arn_namespace; sdk_id = trait.aws_api_service.sdk_id; endpoint_prefix = trait.aws_api_service.endpoint_prefix; }, .aws_auth_sigv4 => sigv4_name = trait.aws_auth_sigv4.name, .aws_protocol => aws_protocol = trait.aws_protocol, else => {}, } } // Service struct // name of the field will be snake_case of whatever comes in from // sdk_id. Not sure this will simple... const constant_name = try constantName(allocator, sdk_id); try constant_names.append(constant_name); try writer.print("const Self = @This();\n", .{}); try writer.print("pub const version: []const u8 = \"{s}\";\n", .{version}); try writer.print("pub const sdk_id: []const u8 = \"{s}\";\n", .{sdk_id}); try writer.print("pub const arn_namespace: []const u8 = \"{s}\";\n", .{arn_namespace}); try writer.print("pub const endpoint_prefix: []const u8 = \"{s}\";\n", .{endpoint_prefix}); try writer.print("pub const sigv4_name: []const u8 = \"{s}\";\n", .{sigv4_name}); try writer.print("pub const name: []const u8 = \"{s}\";\n", .{name}); // TODO: This really should just be ".whatevs". We're fully qualifying here, which isn't typical try writer.print("pub const aws_protocol: smithy.AwsProtocol = smithy.{s};\n\n", .{aws_protocol}); _ = try writer.write("pub const service_metadata: struct {\n"); try writer.print(" version: []const u8 = \"{s}\",\n", .{version}); try writer.print(" sdk_id: []const u8 = \"{s}\",\n", .{sdk_id}); try writer.print(" arn_namespace: []const u8 = \"{s}\",\n", .{arn_namespace}); try writer.print(" endpoint_prefix: []const u8 = \"{s}\",\n", .{endpoint_prefix}); try writer.print(" sigv4_name: []const u8 = \"{s}\",\n", .{sigv4_name}); try writer.print(" name: []const u8 = \"{s}\",\n", .{name}); // TODO: This really should just be ".whatevs". We're fully qualifying here, which isn't typical try writer.print(" aws_protocol: smithy.AwsProtocol = smithy.{s},\n", .{aws_protocol}); _ = try writer.write("} = .{};\n"); // Operations for (service.shape.service.operations) |op| try generateOperation(allocator, shapes.get(op).?, state, writer); } try generateAdditionalTypes(allocator, state, writer); return constant_names.toOwnedSlice(); } fn generateAdditionalTypes(allocator: std.mem.Allocator, file_state: FileGenerationState, writer: anytype) !void { // More types may be added during processing while (file_state.additional_types_to_generate.popOrNull()) |t| { if (file_state.additional_types_generated.getEntry(t.name) != null) continue; // std.log.info("\t\t{s}", .{t.name}); var type_stack = std.ArrayList(*const smithy.ShapeInfo).init(allocator); defer type_stack.deinit(); const state = GenerationState{ .type_stack = &type_stack, .file_state = file_state, .allocator = allocator, .indent_level = 0, }; const type_name = avoidReserved(t.name); try writer.print("\npub const {s} = ", .{type_name}); try file_state.additional_types_generated.putNoClobber(t.name, {}); _ = try generateTypeFor(t.id, writer, state, true); _ = try writer.write(";\n"); } } fn constantName(allocator: std.mem.Allocator, id: []const u8) ![]const u8 { // There are some ids that don't follow consistent rules, so we'll // look for the exceptions and, if not found, revert to the snake case // algorithm // This one might be a bug in snake, but it's the only example so HPDL if (std.mem.eql(u8, id, "SESv2")) return try std.fmt.allocPrint(allocator, "ses_v2", .{}); // IoT is an acryonym, but snake wouldn't know that. Interestingly not all // iot services are capitalizing that way. if (std.mem.eql(u8, id, "IoTSiteWise")) return try std.fmt.allocPrint(allocator, "iot_site_wise", .{}); //sitewise? if (std.mem.eql(u8, id, "IoTFleetHub")) return try std.fmt.allocPrint(allocator, "iot_fleet_hub", .{}); if (std.mem.eql(u8, id, "IoTSecureTunneling")) return try std.fmt.allocPrint(allocator, "iot_secure_tunneling", .{}); if (std.mem.eql(u8, id, "IoTThingsGraph")) return try std.fmt.allocPrint(allocator, "iot_things_graph", .{}); // snake turns this into dev_ops, which is a little weird if (std.mem.eql(u8, id, "DevOps Guru")) return try std.fmt.allocPrint(allocator, "devops_guru", .{}); if (std.mem.eql(u8, id, "FSx")) return try std.fmt.allocPrint(allocator, "fsx", .{}); // Not a special case - just snake it return try snake.fromPascalCase(allocator, id); } const FileGenerationState = struct { shapes: std.StringHashMap(smithy.ShapeInfo), shape_references: std.StringHashMap(u64), additional_types_to_generate: *std.ArrayList(smithy.ShapeInfo), additional_types_generated: *std.StringHashMap(void), }; const GenerationState = struct { type_stack: *std.ArrayList(*const smithy.ShapeInfo), file_state: FileGenerationState, // we will need some sort of "type decls needed" for recursive structures allocator: std.mem.Allocator, indent_level: u64, }; fn outputIndent(state: GenerationState, writer: anytype) !void { const n_chars = 4 * state.indent_level; try writer.writeByteNTimes(' ', n_chars); } fn generateOperation(allocator: std.mem.Allocator, operation: smithy.ShapeInfo, file_state: FileGenerationState, writer: anytype) !void { const snake_case_name = try snake.fromPascalCase(allocator, operation.name); defer allocator.free(snake_case_name); var type_stack = std.ArrayList(*const smithy.ShapeInfo).init(allocator); defer type_stack.deinit(); const state = GenerationState{ .type_stack = &type_stack, .file_state = file_state, .allocator = allocator, .indent_level = 1, }; var child_state = state; child_state.indent_level += 1; // indent should start at 4 spaces here const operation_name = avoidReserved(snake_case_name); try writer.print("pub const {s}: struct ", .{operation_name}); _ = try writer.write("{\n"); for (operation.shape.operation.traits) |trait| { if (trait == .http) { try outputIndent(state, writer); _ = try writer.write("pub const http_config = .{\n"); try outputIndent(child_state, writer); try writer.print(".method = \"{s}\",\n", .{trait.http.method}); try outputIndent(child_state, writer); try writer.print(".uri = \"{s}\",\n", .{trait.http.uri}); try outputIndent(child_state, writer); try writer.print(".success_code = {d},\n", .{trait.http.code}); try outputIndent(state, writer); _ = try writer.write("};\n\n"); } } try outputIndent(state, writer); try writer.print("action_name: []const u8 = \"{s}\",\n", .{operation.name}); try outputIndent(state, writer); _ = try writer.write("Request: type = "); if (operation.shape.operation.input) |member| { if (try generateTypeFor(member, writer, state, false)) unreachable; // we expect only structs here _ = try writer.write("\n"); try generateMetadataFunction(operation_name, state, writer); } else { _ = try writer.write("struct {\n"); try generateMetadataFunction(operation_name, state, writer); } _ = try writer.write(",\n"); try outputIndent(state, writer); _ = try writer.write("Response: type = "); if (operation.shape.operation.output) |member| { if (try generateTypeFor(member, writer, state, true)) unreachable; // we expect only structs here } else _ = try writer.write("struct {}"); // we want to maintain consistency with other ops _ = try writer.write(",\n"); if (operation.shape.operation.errors) |errors| { try outputIndent(state, writer); _ = try writer.write("ServiceError: type = error{\n"); for (errors) |err| { const err_name = getErrorName(file_state.shapes.get(err).?.name); // need to remove "exception" try outputIndent(child_state, writer); try writer.print("{s},\n", .{err_name}); } try outputIndent(state, writer); _ = try writer.write("},\n"); } _ = try writer.write("} = .{};\n"); } fn generateMetadataFunction(operation_name: []const u8, state: GenerationState, writer: anytype) !void { // TODO: Shove these lines in here, and also the else portion // pub fn metaInfo(self: @This()) struct { service: @TypeOf(sts), action: @TypeOf(sts.get_caller_identity) } { // return .{ .service = sts, .action = sts.get_caller_identity }; // } // We want to add a short "get my parents" function into the response var child_state = state; child_state.indent_level += 1; try outputIndent(child_state, writer); _ = try writer.write("pub fn metaInfo() struct { "); try writer.print("service_metadata: @TypeOf(service_metadata), action: @TypeOf({s})", .{operation_name}); _ = try writer.write(" } {\n"); child_state.indent_level += 1; try outputIndent(child_state, writer); _ = try writer.write("return .{ .service_metadata = service_metadata, "); try writer.print(".action = {s}", .{operation_name}); _ = try writer.write(" };\n"); child_state.indent_level -= 1; try outputIndent(child_state, writer); _ = try writer.write("}\n"); try outputIndent(state, writer); try writer.writeByte('}'); } fn getErrorName(err_name: []const u8) []const u8 { if (endsWith("Exception", err_name)) return err_name[0 .. err_name.len - "Exception".len]; if (endsWith("Fault", err_name)) return err_name[0 .. err_name.len - "Fault".len]; return err_name; } fn endsWith(item: []const u8, str: []const u8) bool { if (str.len < item.len) return false; return std.mem.eql(u8, item, str[str.len - item.len ..]); } fn reuseCommonType(shape: smithy.ShapeInfo, writer: anytype, state: GenerationState) !bool { // We want to return if we're at the top level of the stack. There are three // reasons for this: // 1. For operations, we have a request that includes a metadata function // to enable aws.zig eventually to find the action based on a request. // This could be considered a hack and maybe we should remove that // caller convenience ability. // 2. Given the state of zig compiler tooling, "intellisense" or whatever // we're calling it these days, isn't real mature, so we end up looking // at the models quite a bit. Leaving the top level alone here reduces // the need for users to hop around too much looking at types as they // can at least see the top level. // 3. When we come through at the end, we want to make sure we're writing // something or we'll have an infinite loop! if (state.type_stack.items.len == 1) return false; var rc = false; if (state.file_state.shape_references.get(shape.id)) |r| { if (r > 1 and (shape.shape == .structure or shape.shape == .uniontype)) { rc = true; _ = try writer.write(avoidReserved(shape.name)); // This can't possibly be this easy... if (state.file_state.additional_types_generated.getEntry(shape.name) == null) try state.file_state.additional_types_to_generate.append(shape); } } return rc; } /// return type is anyerror!void as this is a recursive function, so the compiler cannot properly infer error types fn generateTypeFor(shape_id: []const u8, writer: anytype, state: GenerationState, end_structure: bool) anyerror!bool { var rc = false; // We assume it must exist const shape_info = state.file_state.shapes.get(shape_id) orelse { std.debug.print("Shape ID not found. This is most likely a bug. Shape ID: {s}\n", .{shape_id}); return error.InvalidType; }; const shape = shape_info.shape; // Check for ourselves up the stack var self_occurences: u8 = 0; for (state.type_stack.items) |i| { // NOTE: shapes.get isn't providing a consistent pointer - is it allocating each time? // we will therefore need to compare ids if (std.mem.eql(u8, i.*.id, shape_info.id)) self_occurences = self_occurences + 1; } // Debugging // if (std.mem.eql(u8, shape_info.name, "Expression")) { // std.log.info(" Type stack len: {d}, occurences: {d}\n", .{ type_stack.items.len, self_occurences }); // if (type_stack.items.len > 15) { // std.log.info(" Type stack:\n", .{}); // for (type_stack.items) |i| // std.log.info(" {s}: {*}", .{ i.*.id, i }); // return error.BugDetected; // } // } // End Debugging if (self_occurences > 2) { // TODO: What's the appropriate number here? // TODO: Determine if this warrants the creation of another public // type to properly reference. Realistically, AWS or the service // must be blocking deep recursion somewhere or this would be a great // DOS attack try generateSimpleTypeFor("nothing", "[]const u8", writer); std.log.warn("Type cycle detected, limiting depth. Type: {s}", .{shape_id}); // if (std.mem.eql(u8, "com.amazonaws.workmail#Timestamp", shape_id)) { // std.log.info(" Type stack:\n", .{}); // for (state.type_stack.items) |i| // std.log.info(" {s}", .{i.*.id}); // } return false; // not a map } try state.type_stack.append(&shape_info); defer _ = state.type_stack.pop(); switch (shape) { .structure => { if (!try reuseCommonType(shape_info, writer, state)) { try generateComplexTypeFor(shape_id, shape.structure.members, "struct", writer, state); if (end_structure) { // epilog try outputIndent(state, writer); _ = try writer.write("}"); } } }, .uniontype => { if (!try reuseCommonType(shape_info, writer, state)) { try generateComplexTypeFor(shape_id, shape.uniontype.members, "union", writer, state); // epilog try outputIndent(state, writer); _ = try writer.write("}"); } }, .string => |s| try generateSimpleTypeFor(s, "[]const u8", writer), .integer => |s| try generateSimpleTypeFor(s, "i64", writer), .list => { _ = try writer.write("[]"); // The serializer will have to deal with the idea we might be an array return try generateTypeFor(shape.list.member_target, writer, state, true); }, .set => { _ = try writer.write("[]"); // The serializer will have to deal with the idea we might be an array return try generateTypeFor(shape.set.member_target, writer, state, true); }, .timestamp => |s| try generateSimpleTypeFor(s, "i64", writer), .blob => |s| try generateSimpleTypeFor(s, "[]const u8", writer), .boolean => |s| try generateSimpleTypeFor(s, "bool", writer), .double => |s| try generateSimpleTypeFor(s, "f64", writer), .float => |s| try generateSimpleTypeFor(s, "f32", writer), .long => |s| try generateSimpleTypeFor(s, "i64", writer), .map => { _ = try writer.write("[]struct {\n"); var child_state = state; child_state.indent_level += 1; try outputIndent(child_state, writer); _ = try writer.write("key: "); try writeOptional(shape.map.traits, writer, null); var sub_maps = std.ArrayList([]const u8).init(state.allocator); defer sub_maps.deinit(); if (try generateTypeFor(shape.map.key, writer, child_state, true)) try sub_maps.append("key"); try writeOptional(shape.map.traits, writer, " = null"); _ = try writer.write(",\n"); try outputIndent(child_state, writer); _ = try writer.write("value: "); try writeOptional(shape.map.traits, writer, null); if (try generateTypeFor(shape.map.value, writer, child_state, true)) try sub_maps.append("value"); try writeOptional(shape.map.traits, writer, " = null"); _ = try writer.write(",\n"); if (sub_maps.items.len > 0) { _ = try writer.write("\n"); try writeStringify(state, sub_maps.items, writer); } try outputIndent(state, writer); _ = try writer.write("}"); rc = true; }, else => { std.log.err("encountered unimplemented shape type {s} for shape_id {s}. Generated code will not compile", .{ @tagName(shape), shape_id }); // Not sure we want to return here - I think we want an exhaustive list // return error{UnimplementedShapeType}.UnimplementedShapeType; }, } return rc; } fn generateSimpleTypeFor(_: anytype, type_name: []const u8, writer: anytype) !void { _ = try writer.write(type_name); // This had required stuff but the problem was elsewhere. Better to leave as function just in case } fn generateComplexTypeFor(shape_id: []const u8, members: []smithy.TypeMember, type_type_name: []const u8, writer: anytype, state: GenerationState) anyerror!void { _ = shape_id; const Mapping = struct { snake: []const u8, json: []const u8 }; var json_field_name_mappings = try std.ArrayList(Mapping).initCapacity(state.allocator, members.len); defer { for (json_field_name_mappings.items) |mapping| state.allocator.free(mapping.snake); json_field_name_mappings.deinit(); } // There is an httpQueryParams trait as well, but nobody is using it. API GW // pretends to, but it's an empty map // // Same with httpPayload // // httpLabel is interesting - right now we just assume anything can be used - do we need to track this? var http_query_mappings = try std.ArrayList(Mapping).initCapacity(state.allocator, members.len); defer { for (http_query_mappings.items) |mapping| state.allocator.free(mapping.snake); http_query_mappings.deinit(); } var http_header_mappings = try std.ArrayList(Mapping).initCapacity(state.allocator, members.len); defer { for (http_header_mappings.items) |mapping| state.allocator.free(mapping.snake); http_header_mappings.deinit(); } var map_fields = std.ArrayList([]const u8).init(state.allocator); defer { for (map_fields.items) |f| state.allocator.free(f); map_fields.deinit(); } // prolog. We'll rely on caller to get the spacing correct here _ = try writer.write(type_type_name); _ = try writer.write(" {\n"); var child_state = state; child_state.indent_level += 1; for (members) |member| { // This is our mapping const snake_case_member = try snake.fromPascalCase(state.allocator, member.name); // So it looks like some services have duplicate names?! Check out "httpMethod" // in API Gateway. Not sure what we're supposed to do there. Checking the go // sdk, they move this particular duplicate to 'http_method' - not sure yet // if this is a hard-coded exception` var found_name_trait = false; for (member.traits) |trait| { switch (trait) { .json_name => { found_name_trait = true; json_field_name_mappings.appendAssumeCapacity(.{ .snake = try state.allocator.dupe(u8, snake_case_member), .json = trait.json_name }); }, .http_query => http_query_mappings.appendAssumeCapacity(.{ .snake = try state.allocator.dupe(u8, snake_case_member), .json = trait.http_query }), .http_header => http_header_mappings.appendAssumeCapacity(.{ .snake = try state.allocator.dupe(u8, snake_case_member), .json = trait.http_header }), else => {}, } } if (!found_name_trait) json_field_name_mappings.appendAssumeCapacity(.{ .snake = try state.allocator.dupe(u8, snake_case_member), .json = member.name }); defer state.allocator.free(snake_case_member); try outputIndent(child_state, writer); const member_name = avoidReserved(snake_case_member); try writer.print("{s}: ", .{member_name}); try writeOptional(member.traits, writer, null); if (try generateTypeFor(member.target, writer, child_state, true)) try map_fields.append(try std.fmt.allocPrint(state.allocator, "{s}", .{member_name})); if (!std.mem.eql(u8, "union", type_type_name)) try writeOptional(member.traits, writer, " = null"); _ = try writer.write(",\n"); } // Add in http query metadata (only relevant to REST JSON APIs - do we care? // pub const http_query = .{ // .master_region = "MasterRegion", // .function_version = "FunctionVersion", // .marker = "Marker", // .max_items = "MaxItems", // }; if (http_query_mappings.items.len > 0) _ = try writer.write("\n"); try writeMappings(child_state, "pub ", "http_query", http_query_mappings, false, writer); if (http_query_mappings.items.len > 0 and http_header_mappings.items.len > 0) _ = try writer.write("\n"); try writeMappings(child_state, "pub ", "http_header", http_header_mappings, false, writer); // Add in json mappings. The function looks like this: // // pub fn jsonFieldNameFor(_: @This(), comptime field_name: []const u8) []const u8 { // const mappings = .{ // .exclusive_start_table_name = "ExclusiveStartTableName", // .limit = "Limit", // }; // return @field(mappings, field_name); // } // try writer.writeByte('\n'); try outputIndent(child_state, writer); _ = try writer.write("pub fn jsonFieldNameFor(_: @This(), comptime field_name: []const u8) []const u8 {\n"); var grandchild_state = child_state; grandchild_state.indent_level += 1; // We need to force output here becaseu we're referencing the field in the return statement below try writeMappings(grandchild_state, "", "mappings", json_field_name_mappings, true, writer); try outputIndent(grandchild_state, writer); _ = try writer.write("return @field(mappings, field_name);\n"); try outputIndent(child_state, writer); _ = try writer.write("}\n"); try writeStringify(child_state, map_fields.items, writer); } fn writeStringify(state: GenerationState, fields: [][]const u8, writer: anytype) !void { if (fields.len > 0) { // pub fn jsonStringifyField(self: @This(), comptime field_name: []const u8, options: anytype, out_stream: anytype) !bool { // if (std.mem.eql(u8, "tags", field_name)) // return try serializeMap(self.tags, self.jsonFieldNameFor("tags"), options, out_stream); // return false; // } var child_state = state; child_state.indent_level += 1; try writer.writeByte('\n'); try outputIndent(state, writer); _ = try writer.write("pub fn jsonStringifyField(self: @This(), comptime field_name: []const u8, options: anytype, out_stream: anytype) !bool {\n"); var return_state = child_state; return_state.indent_level += 1; for (fields) |field| { try outputIndent(child_state, writer); try writer.print("if (std.mem.eql(u8, \"{s}\", field_name))\n", .{field}); try outputIndent(return_state, writer); try writer.print("return try serializeMap(self.{s}, self.jsonFieldNameFor(\"{s}\"), options, out_stream);\n", .{ field, field }); } try outputIndent(child_state, writer); _ = try writer.write("return false;\n"); try outputIndent(state, writer); _ = try writer.write("}\n"); } } fn writeMappings(state: GenerationState, @"pub": []const u8, mapping_name: []const u8, mappings: anytype, force_output: bool, writer: anytype) !void { if (mappings.items.len == 0 and !force_output) return; try outputIndent(state, writer); if (mappings.items.len == 0) { try writer.print("{s}const {s} = ", .{ @"pub", mapping_name }); _ = try writer.write(".{};\n"); return; } try writer.print("{s}const {s} = .", .{ @"pub", mapping_name }); _ = try writer.write("{\n"); var child_state = state; child_state.indent_level += 1; for (mappings.items) |mapping| { try outputIndent(child_state, writer); try writer.print(".{s} = \"{s}\",\n", .{ avoidReserved(mapping.snake), mapping.json }); } try outputIndent(state, writer); _ = try writer.write("};\n"); } fn writeOptional(traits: ?[]smithy.Trait, writer: anytype, value: ?[]const u8) !void { if (traits) |ts| { for (ts) |t| if (t == .required) return; } // not required if (value) |v| { _ = try writer.write(v); } else _ = try writer.write("?"); } fn camelCase(allocator: std.mem.Allocator, name: []const u8) ![]const u8 { const first_letter = name[0] + ('a' - 'A'); return try std.fmt.allocPrint(allocator, "{c}{s}", .{ first_letter, name[1..] }); } fn avoidReserved(snake_name: []const u8) []const u8 { if (std.mem.eql(u8, snake_name, "error")) return "@\"error\""; if (std.mem.eql(u8, snake_name, "return")) return "@\"return\""; if (std.mem.eql(u8, snake_name, "not")) return "@\"not\""; if (std.mem.eql(u8, snake_name, "and")) return "@\"and\""; if (std.mem.eql(u8, snake_name, "or")) return "@\"or\""; if (std.mem.eql(u8, snake_name, "test")) return "@\"test\""; if (std.mem.eql(u8, snake_name, "null")) return "@\"null\""; return snake_name; }
codegen/src/main.zig
const assert = @import("std").debug.assert; const Memory = @This(); /// the CPU visible memory pages resolved from the optionally mapped memory banks pages: [num_pages]Page = [_]Page{.{}} ** num_pages, /// optionally mapped memory bank mapping to host memory banks: [num_banks][num_pages]BankPage = [_][num_pages]BankPage{[_]BankPage{.{}} ** num_pages} ** num_banks, /// map a range of host memory to a 16-bit address as RAM pub fn mapRAM(self: *Memory, bank_index: usize, addr: u16, ram: []u8) void { // map both the read- and write-slice to host memory assert(ram.len <= addr_range); self.map(bank_index, addr, ram.len, ram, ram); } /// map a range of host memory to a 16-bit address as ROM pub fn mapROM(self: *Memory, bank_index: usize, addr: u16, rom: []const u8) void { assert(rom.len <= addr_range); self.map(bank_index, addr, rom.len, rom, null); } /// read an 8-bit value from mapped memory pub fn r8(self: *Memory, addr: u16) u8 { return self.pages[addr >> page_shift].read[addr & page_mask]; } /// write an 8-bit value to mapped memory pub fn w8(self: *Memory, addr: u16, val: u8) void { self.pages[addr >> page_shift].write[addr & page_mask] = val; } /// read a 16-bit value from mapped memory pub fn r16(self: *Memory, addr: u16) u16 { const l: u16 = self.r8(addr); const h: u16 = self.r8(addr +% 1); return (h << 8) | l; } /// write a 16-bit value to mapped memory pub fn w16(self: *Memory, addr: u16, val: u16) void { self.w8(addr, @truncate(u8, val)); self.w8(addr +% 1, @truncate(u8, val >> 8)); } /// write a whole range of bytes to mapped memory pub fn writeBytes(self: *Memory, addr: u16, bytes: []const u8) void { var a = addr; for (bytes) |byte| { self.w8(a, byte); a +%= 1; } } /// unmap one memory bank pub fn unmapBank(self: *Memory, bank_index: usize) void { for (self.banks[bank_index]) |*page, page_index| { page.read = null; page.write = null; self.updatePage(page_index); } } /// unmap all memory banks pub fn unmapAll(self: *Memory) void { for (self.banks) |*bank| { for (bank) |*page| { page.read = null; page.write = null; } } for (self.pages) |_, page_index| { self.updatePage(page_index); } } // a memory bank page with optional mappings to host memory const BankPage = struct { read: ?[]const u8 = null, write: ?[] u8 = null, }; // a CPU visible memory page with guaranteed mappings const Page = struct { read: []const u8 = &unmapped_page, write: []u8 = &junk_page, }; const page_shift = 10; // page size is 1 KB const page_size = 1<<page_shift; const page_mask = page_size - 1; const addr_range = 1<<16; const addr_mask = addr_range - 1; const num_pages = addr_range / page_size; const num_banks = 4; // max number of memory bank layers // dummy pages for unmapped reads and writes const unmapped_page: [page_size]u8 = [_]u8{0xFF} ** page_size; var junk_page: [page_size]u8 = [_]u8{0} ** page_size; // internal memory mapping function for RAM, ROM and separate RW areas fn map(self: *Memory, bank_index: usize, addr: u16, size: usize, read: ?[]const u8, write: ?[]u8) void { assert((addr & page_mask) == 0); // start address must be at page boundary assert((size & page_mask) == 0); // size must be multiple of page size assert((read != null) or (write != null)); var offset: usize = 0; while (offset < size): (offset += page_size) { const page_index = ((addr + offset) & addr_mask) >> page_shift; const bank = &self.banks[bank_index][page_index]; if (read) |r| { bank.read = r[offset .. (offset + page_size)]; } else { bank.read = null; } if (write) |w| { bank.write = w[offset .. (offset + page_size)]; } else { bank.write = null; } self.updatePage(page_index); } } // helper function to update the CPU-visible page table for one memory page fn updatePage(self: *Memory, page_index: usize) void { // find highest priority bank page with valid mapping for (self.banks) |*bank| { if (bank[page_index].read) |_| { // highest priority mapped bank page found self.pages[page_index] = .{ .read = bank[page_index].read.?, .write = bank[page_index].write orelse &junk_page, }; break; } } else { // fallthrough: no mapped bank page found self.pages[page_index] = .{ .read = &unmapped_page, .write = &junk_page, }; } } //=== TESTS ==================================================================== const expect = @import("std").testing.expect; test "initial state" { try expect(unmapped_page[0] == 0xFF); try expect(unmapped_page[1023] == 0xFF); try expect(junk_page[0] == 0); try expect(junk_page[1023] == 0); var mem = Memory{}; try expect(mem.pages[0].read[0] == 0xFF); try expect(mem.pages[63].read[1023] == 0xFF); mem.pages[0].write[0] = 23; try expect(mem.pages[0].read[0] == 0xFF); try expect(junk_page[0] == 23); } test "RAM mapping" { var ram = [_]u8{23} ** 0x10000; var mem = Memory{}; // map the first 32 KB of the address range as RAM mem.mapRAM(0, 0x0000, ram[0..0x8000]); for (mem.pages) |page, i| { if (i < 32) { try expect(&page.read[0] == &ram[i * page_size]); try expect(&page.write[0] == &ram[i * page_size]); try expect(&page.read[0] == &page.write[0]); try expect(page.read[0] == 23); try expect(page.read[1023] == 23); try expect(page.write[0] == 23); try expect(page.write[1023] == 23); } else { try expect(&page.read[0] == &unmapped_page[0]); try expect(&page.write[0] == &junk_page[0]); try expect(page.read[0] == 0xFF); try expect(page.read[1023] == 0xFF); } } ram[1024] = 42; try expect(mem.pages[1].read[0] == 42); mem.pages[1].write[0] = 46; try expect(ram[1024] == 46); } test "ROM mapping" { var rom = [_]u8{23} ** 0x10000; var mem = Memory{}; // map the first 32 KB of the address range as ROM mem.mapROM(0, 0x0000, rom[0..0x8000]); try expect(mem.pages[0].read[0] == 23); // writing to ROM has no effect mem.pages[0].write[0] = 42; try expect(mem.pages[0].read[0] == 23); // but the write should go to the hidden junk page try expect(junk_page[0] == 42); } test "read/write bytes" { var ram = [_]u8{0} ** 0x10000; var mem = Memory{}; mem.mapRAM(0, 0x0000, &ram); mem.w8(0x0000, 23); try expect(mem.r8(0x0000) == 23); mem.w8(0x8000, 42); try expect(mem.r8(0x8000) == 42); } test "read/write words" { var ram = [_]u8{0} ** 0x10000; var mem = Memory{}; mem.mapRAM(0, 0x0000, &ram); mem.w16(0x0000, 0x1234); try expect(mem.r16(0x0000) == 0x1234); try expect(mem.r8(0x0000) == 0x34); try expect(mem.r8(0x0001) == 0x12); mem.w16(0x8000, 0x5678); try expect(mem.r16(0x8000) == 0x5678); try expect(mem.r8(0x8000) == 0x78); try expect(mem.r8(0x8001) == 0x56); // test with wraparound mem.w16(0xFFFF, 0x2345); try expect(mem.r16(0xFFFF) == 0x2345); try expect(mem.r8(0xFFFF) == 0x45); try expect(mem.r8(0x0000) == 0x23); } test "bank visibility" { var bank0 = [_]u8{0} ** 0x10000; var bank1 = [_]u8{1} ** 0x10000; var bank2 = [_]u8{2} ** 0x10000; var mem = Memory{}; mem.mapRAM(0, 0x0000, bank0[0..0x4000]); mem.mapRAM(1, 0x0000, bank1[0..0x8000]); mem.mapRAM(2, 0x0000, bank2[0..0xC000]); try expect(mem.r8(0x0000) == 0); try expect(mem.r8(0x3FFF) == 0); try expect(mem.r8(0x4000) == 1); try expect(mem.r8(0x7FFF) == 1); try expect(mem.r8(0x8000) == 2); try expect(mem.r8(0xBFFF) == 2); try expect(mem.r8(0xC000) == 0xFF); try expect(mem.r8(0xFFFF) == 0xFF); mem.w8(0x0000, 55); mem.w8(0x4000, 55); mem.w8(0x8000, 55); try expect(bank0[0x0000] == 55); try expect(bank1[0x0000] == 1); try expect(bank2[0x0000] == 2); try expect(bank0[0x4000] == 0); try expect(bank1[0x4000] == 55); try expect(bank2[0x4000] == 2); try expect(bank0[0x8000] == 0); try expect(bank1[0x8000] == 1); try expect(bank2[0x8000] == 55); } test "unmap bank" { var bank0 = [_]u8{1} ** 0x10000; var bank1 = [_]u8{2} ** 0x10000; var mem = Memory{}; mem.mapRAM(0, 0x0000, &bank0); mem.mapRAM(1, 0x0000, &bank1); try expect(mem.r8(0x0000) == 1); try expect(mem.r8(0x8000) == 1); try expect(mem.r8(0xFFFF) == 1); mem.w8(0x0000, 42); mem.w8(0x8000, 42); mem.w8(0xFFFF, 42); try expect(mem.r8(0x0000) == 42); try expect(mem.r8(0x8000) == 42); try expect(mem.r8(0xFFFF) == 42); mem.unmapBank(0); try expect(mem.r8(0x0000) == 2); try expect(mem.r8(0x8000) == 2); try expect(mem.r8(0xFFFF) == 2); mem.w8(0x0000, 42); mem.w8(0x8000, 42); mem.w8(0xFFFF, 42); try expect(mem.r8(0x0000) == 42); try expect(mem.r8(0x8000) == 42); try expect(mem.r8(0xFFFF) == 42); mem.unmapBank(1); try expect(mem.r8(0x0000) == 0xFF); try expect(mem.r8(0x8000) == 0xFF); try expect(mem.r8(0xFFFF) == 0xFF); mem.w8(0x0000, 42); mem.w8(0x8000, 42); mem.w8(0xFFFF, 42); try expect(mem.r8(0x0000) == 0xFF); try expect(mem.r8(0x8000) == 0xFF); try expect(mem.r8(0xFFFF) == 0xFF); } test "unmap all" { var bank0 = [_]u8{0} ** 0x10000; var bank1 = [_]u8{1} ** 0x10000; var bank2 = [_]u8{2} ** 0x10000; var bank3 = [_]u8{3} ** 0x10000; var mem = Memory{}; mem.mapRAM(0, 0x0000, &bank0); mem.mapRAM(1, 0x0000, &bank1); mem.mapRAM(2, 0x0000, &bank2); mem.mapRAM(3, 0x0000, &bank3); try expect(mem.r8(0x0000) == 0); try expect(mem.r8(0xFFFF) == 0); mem.w8(0x0000, 23); mem.w8(0xFFFF, 23); try expect(mem.r8(0x0000) == 23); try expect(mem.r8(0xFFFF) == 23); mem.unmapAll(); try expect(mem.r8(0x0000) == 0xFF); try expect(mem.r8(0xFFFF) == 0xFF); mem.w8(0x0000, 23); mem.w8(0xFFFF, 23); try expect(mem.r8(0x0000) == 0xFF); try expect(mem.r8(0xFFFF) == 0xFF); } test "write bytes" { var ram = [_]u8{0} ** 0x10000; var mem = Memory{}; mem.mapRAM(0, 0x0000, &ram); const bytes = [_]u8{23} ** 0x1000; mem.writeBytes(0x4000, &bytes); try expect(mem.r8(0x3FFF) == 0); try expect(mem.r8(0x4000) == 23); try expect(mem.r8(0x4FFF) == 23); try expect(mem.r8(0x5000) == 0); } test "write bytes wraparound" { var ram = [_]u8{0} ** 0x10000; var mem = Memory{}; mem.mapRAM(0, 0x0000, &ram); const bytes = [_]u8{23} ** 0x1000; mem.writeBytes(0xF800, &bytes); try expect(mem.r8(0xF7FF) == 0); try expect(mem.r8(0xF800) == 23); try expect(mem.r8(0x07FF) == 23); try expect(mem.r8(0x0800) == 0); }
src/emu/Memory.zig
const VTE = @import("vte"); const c = VTE.c; const gtk = VTE.gtk; const vte = VTE.vte; const std = @import("std"); const config = @import("config.zig"); const prefs = @import("prefs.zig"); const version = @import("version.zig").version; const menus = @import("menus.zig"); const Menu = menus.Menu; const Nav = menus.Nav; const allocator = std.heap.page_allocator; const known_folders = @import("known-folders"); const nt = @import("nestedtext"); const fs = std.fs; const math = std.math; const mem = std.mem; const os = std.os; const path = std.fs.path; pub fn getKeyFile(alloc: mem.Allocator) ?[]const u8 { const dir = known_folders.getPath(alloc, .local_configuration) catch return null; if (dir) |d| { return path.join(alloc, &[_][]const u8{ d, "zterm/keys.nt" }) catch return null; } else { return if (os.getenv("HOME")) |h| path.join(alloc, &[_][]const u8{ h, ".config/zterm/keys.nt" }) catch return null else null; } } pub const Actions = struct { copy: []const u8, paste: []const u8, quit: []const u8, const Self = @This(); fn default() Self { return Self{ .copy = "<Primary><Shift>c", .paste = "<Primary><Shift>v", .quit = "<Primary><Shift>q", }; } }; pub const Tabs = struct { new_tab: []const u8, prev_tab: []const u8, next_tab: []const u8, tab1: []const u8, tab2: []const u8, tab3: []const u8, tab4: []const u8, tab5: []const u8, tab6: []const u8, tab7: []const u8, tab8: []const u8, tab9: []const u8, const Self = @This(); fn default() Self { return Self{ .new_tab = "<Primary><Shift>t", .prev_tab = "<Alt>Up", .next_tab = "<Alt>Down", .tab1 = "<Alt>1", .tab2 = "<Alt>2", .tab3 = "<Alt>3", .tab4 = "<Alt>4", .tab5 = "<Alt>5", .tab6 = "<Alt>6", .tab7 = "<Alt>7", .tab8 = "<Alt>8", .tab9 = "<Alt>9", }; } }; pub const Views = struct { split_view: []const u8, rotate_view: []const u8, prev_view: []const u8, next_view: []const u8, const Self = @This(); fn default() Self { return Self{ .split_view = "<Primary><Shift>Return", .rotate_view = "<Alt>r", .prev_view = "<Alt>Left", .next_view = "<Alt>Right", }; } }; pub const Accel = struct { key: c_uint, mods: c.GdkModifierType, const Self = @This(); pub fn parse(accel: []const u8) Self { var key: c_uint = undefined; var mods: c.GdkModifierType = undefined; c.gtk_accelerator_parse(@ptrCast([*c]const u8, accel.ptr), &key, &mods); return Self{ .key = key, .mods = mods, }; } }; pub const Keys = struct { actions: Actions, tabs: Tabs, views: Views, const Self = @This(); pub fn default() Self { return Self{ .actions = Actions.default(), .tabs = Tabs.default(), .views = Views.default(), }; } pub fn fromFile(fd: fs.File) ?Self { const text = fd.reader().readAllAlloc(allocator, math.maxInt(usize)) catch return null; defer allocator.free(text); var parser = nt.Parser.init(allocator, .{}); @setEvalBranchQuota(4000); const keys = parser.parseTyped(Keys, text) catch return null; return keys; } pub fn load(self: Self) void { var accel = Accel.parse(self.actions.copy); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Copy", accel.key, accel.mods); accel = Accel.parse(self.actions.paste); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Paste", accel.key, accel.mods); accel = Accel.parse(self.actions.quit); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Quit", accel.key, accel.mods); accel = Accel.parse(self.tabs.new_tab); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/NewTab", accel.key, accel.mods); accel = Accel.parse(self.tabs.prev_tab); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/PrevTab", accel.key, accel.mods); accel = Accel.parse(self.tabs.next_tab); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/NextTab", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab1); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab1", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab2); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab2", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab3); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab3", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab4); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab4", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab5); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab5", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab6); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab6", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab7); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab7", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab8); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab8", accel.key, accel.mods); accel = Accel.parse(self.tabs.tab9); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/Tab9", accel.key, accel.mods); accel = Accel.parse(self.views.split_view); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/SplitView", accel.key, accel.mods); accel = Accel.parse(self.views.rotate_view); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/RotateView", accel.key, accel.mods); accel = Accel.parse(self.views.prev_view); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/PrevPane", accel.key, accel.mods); accel = Accel.parse(self.views.next_view); c.gtk_accel_map_add_entry("<Zterm>/AppMenu/Nav/NextPane", accel.key, accel.mods); } pub fn save(self: Self) void { if (config.getConfigDir(allocator)) |dir| { const tree = nt.fromArbitraryType(allocator, self) catch return; defer tree.deinit(); if (config.getConfigDirHandle(dir)) |h| { var handle = h; defer handle.close(); if (handle.createFile("keys.nt", .{ .truncate = true })) |file| { tree.stringify(.{}, file.writer()) catch return; } else |write_err| { std.debug.print("Write Error: {s}\n", .{write_err}); return; } } } } };
src/keys.zig
const std = @import("std"); const FormatOptions = std.fmt.FormatOptions; const value = @import("value.zig"); const Value = value.Value; const Lexer = struct { offset: ?usize = null, src: []const u8, fn advance(self: *Lexer) ?u8 { if (self.offset) |*offset| { offset.* += 1; if (offset.* >= self.src.len) return null; } else { self.offset = 0; } return self.src[self.offset.?]; } fn peekN(self: Lexer, n: usize) ?u8 { if (self.offset) |offset| { return if (offset + n < self.src.len) self.src[offset + n] else null; } else { return if (n - 1 < self.src.len) self.src[n - 1] else null; } } fn peekNIs(self: Lexer, n: usize, byte: u8) bool { return if (self.peekN(n)) |peek_byte| peek_byte == byte else false; } fn peek(self: Lexer) ?u8 { return self.peekN(1); } fn peekIs(self: Lexer, byte: u8) bool { return self.peekNIs(1, byte); } fn skip(self: *Lexer, byte: u8) bool { if (self.peekIs(byte)) { _ = self.advance(); return true; } return false; } fn until(self: *Lexer, byte: u8) void { while (self.peek() != null and !self.peekIs(byte)) _ = self.advance(); } }; pub const FormatSpec = struct { options: FormatOptions = .{}, spec: u8 = 'd', pub fn format(self: FormatSpec, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; const f = \\Fortmat{{ \\ .spec = '{u}', \\ .fill = '{u}', \\ .alignment = {}, \\ .width = {}, \\ .precision = {}, \\}} ; _ = try writer.print(f, .{ self.spec, self.options.fill, self.options.alignment, self.options.width, self.options.precision, }); } }; fn isValidSpec(byte: u8) bool { return switch (byte) { 'd', 'e', 's', => true, else => false, }; } pub fn parseFormat(fmt: []const u8) anyerror!FormatSpec { var format = FormatSpec{}; var lxr = Lexer{ .src = fmt }; if (!lxr.peekIs(':')) { // We have specifier. format.spec = lxr.advance().?; if (!isValidSpec(format.spec)) return error.InvalidSpec; } if (lxr.skip(':')) { if (lxr.peekN(2)) |peek_byte| { if (std.mem.indexOfScalar(u8, "<^>", peek_byte) != null) { // We have alignment, so we must have fill too. format.options.fill = lxr.advance().?; format.options.alignment = switch (lxr.advance().?) { '<' => .Left, '^' => .Center, '>' => .Right, else => unreachable, }; } } // Next maybe be width. if (lxr.peek()) |peek_byte| { if ('.' != peek_byte) { const w_start = lxr.offset.? + 1; lxr.until('.'); const end = lxr.offset.? + 1; format.options.width = try std.fmt.parseInt(usize, fmt[w_start..end], 10); } } if (lxr.peek()) |peek_byte| { if ('.' == peek_byte) { // We have precision. format.options.precision = try std.fmt.parseInt(usize, fmt[lxr.offset.? + 2 ..], 10); } } } return format; } pub fn runtimePrint( allocator: std.mem.Allocator, fmt: []const u8, v: Value, writer: anytype, ) anyerror!void { const format = try parseFormat(fmt); switch (format.spec) { 'd' => { if (!value.isFloat(v) and !value.isInt(v) and !value.isUint(v)) return error.InvalidFormatD; if (value.asFloat(v)) |f| { var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); var buf_writer = buf.writer(); try std.fmt.formatFloatDecimal( f, format.options, buf_writer, ); try std.fmt.formatBuf( buf.items, format.options, writer, ); } if (value.asInt(v)) |i| { try std.fmt.formatInt( i, 10, .lower, format.options, writer, ); } if (value.asUint(v)) |u| { try std.fmt.formatInt( u, 10, .lower, format.options, writer, ); } }, 'e' => { if (!value.isFloat(v)) return error.InvalidFormatE; var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); var buf_writer = buf.writer(); try std.fmt.formatFloatScientific( value.asFloat(v).?, format.options, buf_writer, ); try std.fmt.formatBuf( buf.items, format.options, writer, ); }, 's' => { if (!value.isAnyStr(v)) return error.InvalidFormatS; const s = if (value.unboxStr(v)) |u| std.mem.sliceTo(std.mem.asBytes(&u), 0) else value.asString(v).?.string; try std.fmt.formatBuf( s, format.options, writer, ); }, else => return error.UnknownFormatSpec, } }
src/fmt.zig
const std = @import("std"); const log = std.log.scoped(.uv); const c = @cImport({ // Make sure to pull the repo's uv.h. On macos, /usr/local/include/uv.h has precedence. @cInclude("vendor/include/uv.h"); }); pub const sockaddr = c.sockaddr; pub const sockaddr_in = c.sockaddr_in; pub const uv_loop_t = c.uv_loop_t; pub const uv_tcp_t = c.uv_tcp_t; pub const uv_stream_t = c.uv_stream_t; pub const uv_pipe_t = c.uv_pipe_t; pub const uv_handle_t = c.uv_handle_t; pub const uv_close_cb = c.uv_close_cb; pub const uv_async_t = c.uv_async_t; pub const uv_timer_t = c.uv_timer_t; pub const uv_poll_t = c.uv_poll_t; pub const uv_timer_cb = c.uv_timer_cb; pub const uv_fs_event_t = c.uv_fs_event_t; pub const uv_process_options_t = c.uv_process_options_t; pub const uv_process_t = c.uv_process_t; pub const uv_buf_t = c.uv_buf_t; pub const uv_stdio_container_t = c.uv_stdio_container_t; // Errors. pub const UV_EBUSY = c.UV_EBUSY; pub const UV_ENOENT = c.UV_ENOENT; pub const UV_EOF = c.UV_EOF; pub const UV_RUN_DEFAULT = c.UV_RUN_DEFAULT; pub const UV_RUN_ONCE = c.UV_RUN_ONCE; pub const UV_RUN_NOWAIT = c.UV_RUN_NOWAIT; pub const UV_READABLE = c.UV_READABLE; pub const UV_WRITABLE = c.UV_WRITABLE; pub const UV_IGNORE = c.UV_IGNORE; pub const UV_CREATE_PIPE = c.UV_CREATE_PIPE; pub const UV_READABLE_PIPE = c.UV_READABLE_PIPE; pub const UV_WRITABLE_PIPE = c.UV_WRITABLE_PIPE; // Handle types pub const UV_TCP = c.UV_TCP; pub const UV_TIMER = c.UV_TIMER; // uv_fs_event enum pub const UV_RENAME = c.UV_RENAME; pub const UV_CHANGE = c.UV_CHANGE; pub const uv_fs_event_cb = ?fn (*uv_fs_event_t, [*c]const u8, c_int, c_int) callconv(.C) void; pub const uv_connection_cb = ?fn (*uv_stream_t, c_int) callconv(.C) void; pub extern fn uv_loop_init(loop: *uv_loop_t) c_int; pub extern fn uv_listen(stream: *uv_stream_t, backlog: c_int, cb: uv_connection_cb) c_int; pub extern fn uv_tcp_init(*uv_loop_t, handle: *uv_tcp_t) c_int; pub extern fn uv_ip4_addr(ip: [*c]const u8, port: c_int, addr: *c.struct_sockaddr_in) c_int; pub extern fn uv_tcp_bind(handle: *uv_tcp_t, addr: *const c.struct_sockaddr, flags: c_uint) c_int; pub extern fn uv_strerror(err: c_int) [*c]const u8; /// [uv] Gets the platform dependent file descriptor equivalent. /// following handles are supported: TCP, pipes, TTY, UDP and poll. Passing any other handle type will fail with UV_EINVAL. /// If a handle doesn’t have an attached file descriptor yet or the handle itself has been closed, this function will return UV_EBADF. pub extern fn uv_fileno(handle: *const uv_handle_t, fd: *c.uv_os_fd_t) c_int; /// [uv] Request handle to be closed. close_cb will be called asynchronously after this call. /// This MUST be called on each handle before memory is released. /// Moreover, the memory can only be released in close_cb or after it has returned. /// Handles that wrap file descriptors are closed immediately but close_cb will still be deferred to the next iteration of the event loop. /// It gives you a chance to free up any resources associated with the handle. /// In-progress requests, like uv_connect_t or uv_write_t, are cancelled and have their callbacks called asynchronously with status=UV_ECANCELED. pub extern fn uv_close(handle: *uv_handle_t, close_cb: uv_close_cb) void; pub extern fn uv_run(*uv_loop_t, mode: c.uv_run_mode) c_int; pub extern fn uv_accept(server: *uv_stream_t, client: *uv_stream_t) c_int; pub extern fn uv_backend_fd(*const uv_loop_t) c_int; pub extern fn uv_backend_timeout(*const uv_loop_t) c_int; pub extern fn uv_loop_size() usize; pub extern fn uv_loop_alive(loop: *const uv_loop_t) c_int; pub extern fn uv_loop_close(loop: *const uv_loop_t) c_int; pub extern fn uv_stop(loop: *const uv_loop_t) void; pub extern fn uv_walk(loop: *const uv_loop_t, cb: c.uv_walk_cb, ctx: ?*anyopaque) void; pub extern fn uv_async_init(*uv_loop_t, @"async": *uv_async_t, async_cb: c.uv_async_cb) c_int; pub extern fn uv_async_send(@"async": *uv_async_t) c_int; pub extern fn uv_handle_get_type(handle: *const uv_handle_t) c.uv_handle_type; pub extern fn uv_timer_init(*uv_loop_t, handle: *uv_timer_t) c_int; pub extern fn uv_timer_start(handle: *uv_timer_t, cb: c.uv_timer_cb, timeout: u64, repeat: u64) c_int; pub extern fn uv_timer_stop(handle: *uv_timer_t) c_int; pub extern fn uv_poll_init_socket(loop: *uv_loop_t, handle: *uv_poll_t, socket: c.uv_os_sock_t) c_int; pub extern fn uv_poll_start(handle: *uv_poll_t, events: c_int, cb: c.uv_poll_cb) c_int; pub extern fn uv_poll_stop(handle: *uv_poll_t) c_int; pub extern fn uv_is_closing(handle: *const uv_handle_t) c_int; pub extern fn uv_update_time(*uv_loop_t) void; pub extern fn uv_fs_event_init(loop: *uv_loop_t, handle: *uv_fs_event_t) c_int; pub extern fn uv_fs_event_start(handle: *uv_fs_event_t, cb: uv_fs_event_cb, path: [*c]const u8, flags: c_uint) c_int; pub extern fn uv_fs_event_stop(handle: *uv_fs_event_t) c_int; pub extern fn uv_tcp_getsockname(handle: *const uv_tcp_t, name: *c.struct_sockaddr, namelen: *c_int) c_int; pub extern fn uv_spawn(loop: *uv_loop_t, handle: *uv_process_t, options: *const uv_process_options_t) c_int; pub extern fn uv_pipe_init(loop: *uv_loop_t, handle: *uv_pipe_t, ipc: c_int) c_int; pub extern fn uv_read_start(stream: *uv_stream_t, alloc_cb: c.uv_alloc_cb, read_cb: c.uv_read_cb) c_int; pub fn assertNoError(code: c_int) void { if (code != 0) { log.debug("uv error: [{}] {s}", .{code, uv_strerror(code)}); unreachable; } }
lib/uv/uv.zig
const std = @import("std"); const assert = std.debug.assert; const math = std.math; const mem = std.mem; const testing = std.testing; const log = std.log.scoped(.tapi); const Allocator = mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; pub const Tokenizer = @import("Tokenizer.zig"); pub const parse = @import("parse.zig"); const Node = parse.Node; const Tree = parse.Tree; const ParseError = parse.ParseError; pub const YamlError = error{ UnexpectedNodeType, OutOfMemory, } || ParseError || std.fmt.ParseIntError; pub const ValueType = enum { empty, int, float, string, list, map, }; pub const List = []Value; pub const Map = std.StringArrayHashMap(Value); pub const Value = union(ValueType) { empty, int: i64, float: f64, string: []const u8, list: List, map: Map, pub fn asInt(self: Value) !i64 { if (self != .int) return error.TypeMismatch; return self.int; } pub fn asFloat(self: Value) !f64 { if (self != .float) return error.TypeMismatch; return self.float; } pub fn asString(self: Value) ![]const u8 { if (self != .string) return error.TypeMismatch; return self.string; } pub fn asList(self: Value) !List { if (self != .list) return error.TypeMismatch; return self.list; } pub fn asMap(self: Value) !Map { if (self != .map) return error.TypeMismatch; return self.map; } const StringifyArgs = struct { indentation: usize = 0, should_inline_first_key: bool = false, }; pub const StringifyError = std.os.WriteError; pub fn stringify(self: Value, writer: anytype, args: StringifyArgs) StringifyError!void { switch (self) { .empty => return, .int => |int| return writer.print("{}", .{int}), .float => |float| return writer.print("{d}", .{float}), .string => |string| return writer.print("{s}", .{string}), .list => |list| { const len = list.len; if (len == 0) return; const first = list[0]; if (first.is_compound()) { for (list) |elem, i| { try writer.writeByteNTimes(' ', args.indentation); try writer.writeAll("- "); try elem.stringify(writer, .{ .indentation = args.indentation + 2, .should_inline_first_key = true, }); if (i < len - 1) { try writer.writeByte('\n'); } } return; } try writer.writeAll("[ "); for (list) |elem, i| { try elem.stringify(writer, args); if (i < len - 1) { try writer.writeAll(", "); } } try writer.writeAll(" ]"); }, .map => |map| { const keys = map.keys(); const len = keys.len; if (len == 0) return; for (keys) |key, i| { if (!args.should_inline_first_key or i != 0) { try writer.writeByteNTimes(' ', args.indentation); } try writer.print("{s}: ", .{key}); const value = map.get(key) orelse unreachable; const should_inline = blk: { if (!value.is_compound()) break :blk true; if (value == .list and value.list.len > 0 and !value.list[0].is_compound()) break :blk true; break :blk false; }; if (should_inline) { try value.stringify(writer, args); } else { try writer.writeByte('\n'); try value.stringify(writer, .{ .indentation = args.indentation + 4, }); } if (i < len - 1) { try writer.writeByte('\n'); } } }, } } fn is_compound(self: Value) bool { return switch (self) { .list, .map => true, else => false, }; } fn fromNode(arena: Allocator, tree: *const Tree, node: *const Node, type_hint: ?ValueType) YamlError!Value { if (node.cast(Node.Doc)) |doc| { const inner = doc.value orelse { // empty doc return Value{ .empty = {} }; }; return Value.fromNode(arena, tree, inner, null); } else if (node.cast(Node.Map)) |map| { var out_map = std.StringArrayHashMap(Value).init(arena); try out_map.ensureUnusedCapacity(map.values.items.len); for (map.values.items) |entry| { const key_tok = tree.tokens[entry.key]; const key = try arena.dupe(u8, tree.source[key_tok.start..key_tok.end]); const value = try Value.fromNode(arena, tree, entry.value, null); out_map.putAssumeCapacityNoClobber(key, value); } return Value{ .map = out_map }; } else if (node.cast(Node.List)) |list| { var out_list = std.ArrayList(Value).init(arena); try out_list.ensureUnusedCapacity(list.values.items.len); if (list.values.items.len > 0) { const hint = if (list.values.items[0].cast(Node.Value)) |value| hint: { const start = tree.tokens[value.start.?]; const end = tree.tokens[value.end.?]; const raw = tree.source[start.start..end.end]; _ = std.fmt.parseInt(i64, raw, 10) catch { _ = std.fmt.parseFloat(f64, raw) catch { break :hint ValueType.string; }; break :hint ValueType.float; }; break :hint ValueType.int; } else null; for (list.values.items) |elem| { const value = try Value.fromNode(arena, tree, elem, hint); out_list.appendAssumeCapacity(value); } } return Value{ .list = out_list.toOwnedSlice() }; } else if (node.cast(Node.Value)) |value| { const start = tree.tokens[value.start.?]; const end = tree.tokens[value.end.?]; const raw = tree.source[start.start..end.end]; if (type_hint) |hint| { return switch (hint) { .int => Value{ .int = try std.fmt.parseInt(i64, raw, 10) }, .float => Value{ .float = try std.fmt.parseFloat(f64, raw) }, .string => Value{ .string = try arena.dupe(u8, raw) }, else => unreachable, }; } try_int: { // TODO infer base for int const int = std.fmt.parseInt(i64, raw, 10) catch break :try_int; return Value{ .int = int }; } try_float: { const float = std.fmt.parseFloat(f64, raw) catch break :try_float; return Value{ .float = float }; } return Value{ .string = try arena.dupe(u8, raw) }; } else { log.err("Unexpected node type: {}", .{node.tag}); return error.UnexpectedNodeType; } } }; pub const Yaml = struct { arena: ArenaAllocator, tree: ?Tree = null, docs: std.ArrayList(Value), pub fn deinit(self: *Yaml) void { self.arena.deinit(); } pub fn stringify(self: Yaml, writer: anytype) !void { for (self.docs.items) |doc| { // if (doc.directive) |directive| { // try writer.print("--- !{s}\n", .{directive}); // } try doc.stringify(writer, .{}); // if (doc.directive != null) { // try writer.writeAll("...\n"); // } } } pub fn load(allocator: Allocator, source: []const u8) !Yaml { var arena = ArenaAllocator.init(allocator); const arena_allocator = arena.allocator(); var tree = Tree.init(arena_allocator); try tree.parse(source); var docs = std.ArrayList(Value).init(arena_allocator); try docs.ensureUnusedCapacity(tree.docs.items.len); for (tree.docs.items) |node| { const value = try Value.fromNode(arena_allocator, &tree, node, null); docs.appendAssumeCapacity(value); } return Yaml{ .arena = arena, .tree = tree, .docs = docs, }; } pub const Error = error{ Unimplemented, TypeMismatch, StructFieldMissing, ArraySizeMismatch, UntaggedUnion, UnionTagMissing, Overflow, OutOfMemory, }; pub fn parse(self: *Yaml, comptime T: type) Error!T { if (self.docs.items.len == 0) { if (@typeInfo(T) == .Void) return {}; return error.TypeMismatch; } if (self.docs.items.len == 1) { return self.parseValue(T, self.docs.items[0]); } switch (@typeInfo(T)) { .Array => |info| { var parsed: T = undefined; for (self.docs.items) |doc, i| { parsed[i] = try self.parseValue(info.child, doc); } return parsed; }, .Pointer => |info| { switch (info.size) { .Slice => { var parsed = try self.arena.allocator().alloc(info.child, self.docs.items.len); for (self.docs.items) |doc, i| { parsed[i] = try self.parseValue(info.child, doc); } return parsed; }, else => return error.TypeMismatch, } }, .Union => return error.Unimplemented, else => return error.TypeMismatch, } } fn parseValue(self: *Yaml, comptime T: type, value: Value) Error!T { return switch (@typeInfo(T)) { .Int => math.cast(T, try value.asInt()), .Float => math.lossyCast(T, try value.asFloat()), .Struct => self.parseStruct(T, try value.asMap()), .Union => self.parseUnion(T, value), .Array => self.parseArray(T, try value.asList()), .Pointer => { if (value.asList()) |list| { return self.parsePointer(T, .{ .list = list }); } else |_| { return self.parsePointer(T, .{ .string = try value.asString() }); } }, .Void => error.TypeMismatch, .Optional => unreachable, else => error.Unimplemented, }; } fn parseUnion(self: *Yaml, comptime T: type, value: Value) Error!T { const union_info = @typeInfo(T).Union; if (union_info.tag_type) |_| { inline for (union_info.fields) |field| { if (self.parseValue(field.field_type, value)) |u_value| { return @unionInit(T, field.name, u_value); } else |err| { if (@as(@TypeOf(err) || error{TypeMismatch}, err) != error.TypeMismatch) return err; } } } else return error.UntaggedUnion; return error.UnionTagMissing; } fn parseOptional(self: *Yaml, comptime T: type, value: ?Value) Error!T { const unwrapped = value orelse return null; const opt_info = @typeInfo(T).Optional; return @as(T, try self.parseValue(opt_info.child, unwrapped)); } fn parseStruct(self: *Yaml, comptime T: type, map: Map) Error!T { const struct_info = @typeInfo(T).Struct; var parsed: T = undefined; inline for (struct_info.fields) |field| { const value: ?Value = map.get(field.name) orelse blk: { const field_name = try mem.replaceOwned(u8, self.arena.allocator(), field.name, "_", "-"); break :blk map.get(field_name); }; if (@typeInfo(field.field_type) == .Optional) { @field(parsed, field.name) = try self.parseOptional(field.field_type, value); continue; } const unwrapped = value orelse { log.debug("missing struct field: {s}: {s}", .{ field.name, @typeName(field.field_type) }); return error.StructFieldMissing; }; @field(parsed, field.name) = try self.parseValue(field.field_type, unwrapped); } return parsed; } fn parsePointer(self: *Yaml, comptime T: type, value: Value) Error!T { const ptr_info = @typeInfo(T).Pointer; const arena = self.arena.allocator(); switch (ptr_info.size) { .Slice => { const child_info = @typeInfo(ptr_info.child); if (child_info == .Int and child_info.Int.bits == 8) { return value.asString(); } var parsed = try arena.alloc(ptr_info.child, value.list.len); for (value.list) |elem, i| { parsed[i] = try self.parseValue(ptr_info.child, elem); } return parsed; }, else => return error.Unimplemented, } } fn parseArray(self: *Yaml, comptime T: type, list: List) Error!T { const array_info = @typeInfo(T).Array; if (array_info.len != list.len) return error.ArraySizeMismatch; var parsed: T = undefined; for (list) |elem, i| { parsed[i] = try self.parseValue(array_info.child, elem); } return parsed; } }; test { testing.refAllDecls(@This()); } test "simple list" { const source = \\- a \\- b \\- c ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const list = yaml.docs.items[0].list; try testing.expectEqual(list.len, 3); try testing.expect(mem.eql(u8, list[0].string, "a")); try testing.expect(mem.eql(u8, list[1].string, "b")); try testing.expect(mem.eql(u8, list[2].string, "c")); } test "simple list typed as array of strings" { const source = \\- a \\- b \\- c ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const arr = try yaml.parse([3][]const u8); try testing.expectEqual(arr.len, 3); try testing.expect(mem.eql(u8, arr[0], "a")); try testing.expect(mem.eql(u8, arr[1], "b")); try testing.expect(mem.eql(u8, arr[2], "c")); } test "simple list typed as array of ints" { const source = \\- 0 \\- 1 \\- 2 ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const arr = try yaml.parse([3]u8); try testing.expectEqual(arr.len, 3); try testing.expectEqual(arr[0], 0); try testing.expectEqual(arr[1], 1); try testing.expectEqual(arr[2], 2); } test "list of mixed sign integer" { const source = \\- 0 \\- -1 \\- 2 ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const arr = try yaml.parse([3]i8); try testing.expectEqual(arr.len, 3); try testing.expectEqual(arr[0], 0); try testing.expectEqual(arr[1], -1); try testing.expectEqual(arr[2], 2); } test "simple map untyped" { const source = \\a: 0 ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectEqual(yaml.docs.items.len, 1); const map = yaml.docs.items[0].map; try testing.expect(map.contains("a")); try testing.expectEqual(map.get("a").?.int, 0); } test "simple map typed" { const source = \\a: 0 \\b: hello there \\c: 'wait, what?' ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); const simple = try yaml.parse(struct { a: usize, b: []const u8, c: []const u8 }); try testing.expectEqual(simple.a, 0); try testing.expect(mem.eql(u8, simple.b, "hello there")); try testing.expect(mem.eql(u8, simple.c, "wait, what?")); } test "typed nested structs" { const source = \\a: \\ b: hello there \\ c: 'wait, what?' ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); const simple = try yaml.parse(struct { a: struct { b: []const u8, c: []const u8, }, }); try testing.expect(mem.eql(u8, simple.a.b, "hello there")); try testing.expect(mem.eql(u8, simple.a.c, "wait, what?")); } test "multidoc typed as a slice of structs" { const source = \\--- \\a: 0 \\--- \\a: 1 \\... ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); { const result = try yaml.parse([2]struct { a: usize }); try testing.expectEqual(result.len, 2); try testing.expectEqual(result[0].a, 0); try testing.expectEqual(result[1].a, 1); } { const result = try yaml.parse([]struct { a: usize }); try testing.expectEqual(result.len, 2); try testing.expectEqual(result[0].a, 0); try testing.expectEqual(result[1].a, 1); } } test "multidoc typed as a struct is an error" { const source = \\--- \\a: 0 \\--- \\b: 1 \\... ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectError(Yaml.Error.TypeMismatch, yaml.parse(struct { a: usize })); try testing.expectError(Yaml.Error.TypeMismatch, yaml.parse(struct { b: usize })); try testing.expectError(Yaml.Error.TypeMismatch, yaml.parse(struct { a: usize, b: usize })); } test "multidoc typed as a slice of structs with optionals" { const source = \\--- \\a: 0 \\c: 1.0 \\--- \\a: 1 \\b: different field \\... ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); const result = try yaml.parse([]struct { a: usize, b: ?[]const u8, c: ?f16 }); try testing.expectEqual(result.len, 2); try testing.expectEqual(result[0].a, 0); try testing.expect(result[0].b == null); try testing.expect(result[0].c != null); try testing.expectEqual(result[0].c.?, 1.0); try testing.expectEqual(result[1].a, 1); try testing.expect(result[1].b != null); try testing.expect(mem.eql(u8, result[1].b.?, "different field")); try testing.expect(result[1].c == null); } test "empty yaml can be represented as void" { const source = ""; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); const result = try yaml.parse(void); try testing.expect(@TypeOf(result) == void); } test "nonempty yaml cannot be represented as void" { const source = \\a: b ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectError(Yaml.Error.TypeMismatch, yaml.parse(void)); } test "typed array size mismatch" { const source = \\- 0 \\- 0 ; var yaml = try Yaml.load(testing.allocator, source); defer yaml.deinit(); try testing.expectError(Yaml.Error.ArraySizeMismatch, yaml.parse([1]usize)); try testing.expectError(Yaml.Error.ArraySizeMismatch, yaml.parse([5]usize)); }
src/link/tapi/yaml.zig
const std = @import("std"); const link = @import("../link.zig"); const Module = @import("../Module.zig"); const Compilation = @import("../Compilation.zig"); const Inst = @import("../ir.zig").Inst; const Value = @import("../value.zig").Value; const Type = @import("../type.zig").Type; const C = link.File.C; const Decl = Module.Decl; const mem = std.mem; const indentation = " "; /// Maps a name from Zig source to C. Currently, this will always give the same /// output for any given input, sometimes resulting in broken identifiers. fn map(allocator: *std.mem.Allocator, name: []const u8) ![]const u8 { return allocator.dupe(u8, name); } fn renderType(ctx: *Context, header: *C.Header, writer: std.ArrayList(u8).Writer, T: Type) !void { switch (T.zigTypeTag()) { .NoReturn => { try writer.writeAll("zig_noreturn void"); }, .Void => try writer.writeAll("void"), .Bool => try writer.writeAll("bool"), .Int => { if (T.tag() == .u8) { header.need_stdint = true; try writer.writeAll("uint8_t"); } else if (T.tag() == .u32) { header.need_stdint = true; try writer.writeAll("uint32_t"); } else if (T.tag() == .usize) { header.need_stddef = true; try writer.writeAll("size_t"); } else { return ctx.fail(ctx.decl.src(), "TODO implement int type {}", .{T}); } }, else => |e| return ctx.fail(ctx.decl.src(), "TODO implement type {}", .{e}), } } fn renderValue(ctx: *Context, writer: std.ArrayList(u8).Writer, T: Type, val: Value) !void { switch (T.zigTypeTag()) { .Int => { if (T.isSignedInt()) return writer.print("{}", .{val.toSignedInt()}); return writer.print("{}", .{val.toUnsignedInt()}); }, else => |e| return ctx.fail(ctx.decl.src(), "TODO implement value {}", .{e}), } } fn renderFunctionSignature(ctx: *Context, header: *C.Header, writer: std.ArrayList(u8).Writer, decl: *Decl) !void { const tv = decl.typed_value.most_recent.typed_value; try renderType(ctx, header, writer, tv.ty.fnReturnType()); // Use the child allocator directly, as we know the name can be freed before // the rest of the arena. const name = try map(ctx.arena.child_allocator, mem.spanZ(decl.name)); defer ctx.arena.child_allocator.free(name); try writer.print(" {}(", .{name}); var param_len = tv.ty.fnParamLen(); if (param_len == 0) try writer.writeAll("void") else { var index: usize = 0; while (index < param_len) : (index += 1) { if (index > 0) { try writer.writeAll(", "); } try renderType(ctx, header, writer, tv.ty.fnParamType(index)); try writer.print(" arg{}", .{index}); } } try writer.writeByte(')'); } pub fn generate(file: *C, decl: *Decl) !void { switch (decl.typed_value.most_recent.typed_value.ty.zigTypeTag()) { .Fn => try genFn(file, decl), .Array => try genArray(file, decl), else => |e| return file.fail(decl.src(), "TODO {}", .{e}), } } pub fn generateHeader( arena: *std.heap.ArenaAllocator, module: *Module, header: *C.Header, decl: *Decl, ) error{ AnalysisFail, OutOfMemory }!void { switch (decl.typed_value.most_recent.typed_value.ty.zigTypeTag()) { .Fn => { var inst_map = std.AutoHashMap(*Inst, []u8).init(&arena.allocator); defer inst_map.deinit(); var ctx = Context{ .decl = decl, .arena = arena, .inst_map = &inst_map, }; const writer = header.buf.writer(); renderFunctionSignature(&ctx, header, writer, decl) catch |err| { if (err == error.AnalysisFail) { try module.failed_decls.put(module.gpa, decl, ctx.error_msg); } return err; }; try writer.writeAll(";\n"); }, else => {}, } } fn genArray(file: *C, decl: *Decl) !void { const tv = decl.typed_value.most_recent.typed_value; // TODO: prevent inline asm constants from being emitted const name = try map(file.base.allocator, mem.span(decl.name)); defer file.base.allocator.free(name); if (tv.val.cast(Value.Payload.Bytes)) |payload| if (tv.ty.sentinel()) |sentinel| if (sentinel.toUnsignedInt() == 0) // TODO: static by default try file.constants.writer().print("const char *const {} = \"{}\";\n", .{ name, payload.data }) else return file.fail(decl.src(), "TODO byte arrays with non-zero sentinels", .{}) else return file.fail(decl.src(), "TODO byte arrays without sentinels", .{}) else return file.fail(decl.src(), "TODO non-byte arrays", .{}); } const Context = struct { decl: *Decl, inst_map: *std.AutoHashMap(*Inst, []u8), arena: *std.heap.ArenaAllocator, argdex: usize = 0, unnamed_index: usize = 0, error_msg: *Compilation.ErrorMsg = undefined, fn resolveInst(self: *Context, inst: *Inst) ![]u8 { if (inst.cast(Inst.Constant)) |const_inst| { var out = std.ArrayList(u8).init(&self.arena.allocator); try renderValue(self, out.writer(), inst.ty, const_inst.val); return out.toOwnedSlice(); } if (self.inst_map.get(inst)) |val| { return val; } unreachable; } fn name(self: *Context) ![]u8 { const val = try std.fmt.allocPrint(&self.arena.allocator, "__temp_{}", .{self.unnamed_index}); self.unnamed_index += 1; return val; } fn fail(self: *Context, src: usize, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } { self.error_msg = try Compilation.ErrorMsg.create(self.arena.child_allocator, src, format, args); return error.AnalysisFail; } fn deinit(self: *Context) void { self.* = undefined; } }; fn genFn(file: *C, decl: *Decl) !void { const writer = file.main.writer(); const tv = decl.typed_value.most_recent.typed_value; var arena = std.heap.ArenaAllocator.init(file.base.allocator); defer arena.deinit(); var inst_map = std.AutoHashMap(*Inst, []u8).init(&arena.allocator); defer inst_map.deinit(); var ctx = Context{ .decl = decl, .arena = &arena, .inst_map = &inst_map, }; defer { file.error_msg = ctx.error_msg; ctx.deinit(); } try renderFunctionSignature(&ctx, &file.header, writer, decl); try writer.writeAll(" {"); const func: *Module.Fn = tv.val.cast(Value.Payload.Function).?.func; const instructions = func.analysis.success.instructions; if (instructions.len > 0) { try writer.writeAll("\n"); for (instructions) |inst| { if (switch (inst.tag) { .assembly => try genAsm(&ctx, file, inst.castTag(.assembly).?), .call => try genCall(&ctx, file, inst.castTag(.call).?), .add => try genBinOp(&ctx, file, inst.cast(Inst.BinOp).?, "+"), .sub => try genBinOp(&ctx, file, inst.cast(Inst.BinOp).?, "-"), .ret => try genRet(&ctx, inst.castTag(.ret).?), .retvoid => try genRetVoid(file), .arg => try genArg(&ctx), .dbg_stmt => try genDbgStmt(&ctx, inst.castTag(.dbg_stmt).?), .breakpoint => try genBreak(&ctx, inst.castTag(.breakpoint).?), .unreach => try genUnreach(file, inst.castTag(.unreach).?), .intcast => try genIntCast(&ctx, file, inst.castTag(.intcast).?), else => |e| return ctx.fail(decl.src(), "TODO implement C codegen for {}", .{e}), }) |name| { try ctx.inst_map.putNoClobber(inst, name); } } } try writer.writeAll("}\n\n"); } fn genArg(ctx: *Context) !?[]u8 { const name = try std.fmt.allocPrint(&ctx.arena.allocator, "arg{}", .{ctx.argdex}); ctx.argdex += 1; return name; } fn genRetVoid(file: *C) !?[]u8 { try file.main.writer().print(indentation ++ "return;\n", .{}); return null; } fn genRet(ctx: *Context, inst: *Inst.UnOp) !?[]u8 { return ctx.fail(ctx.decl.src(), "TODO return", .{}); } fn genIntCast(ctx: *Context, file: *C, inst: *Inst.UnOp) !?[]u8 { if (inst.base.isUnused()) return null; const op = inst.operand; const writer = file.main.writer(); const name = try ctx.name(); const from = try ctx.resolveInst(inst.operand); try writer.writeAll(indentation ++ "const "); try renderType(ctx, &file.header, writer, inst.base.ty); try writer.print(" {} = (", .{name}); try renderType(ctx, &file.header, writer, inst.base.ty); try writer.print("){};\n", .{from}); return name; } fn genBinOp(ctx: *Context, file: *C, inst: *Inst.BinOp, comptime operator: []const u8) !?[]u8 { if (inst.base.isUnused()) return null; const lhs = ctx.resolveInst(inst.lhs); const rhs = ctx.resolveInst(inst.rhs); const writer = file.main.writer(); const name = try ctx.name(); try writer.writeAll(indentation ++ "const "); try renderType(ctx, &file.header, writer, inst.base.ty); try writer.print(" {} = {} " ++ operator ++ " {};\n", .{ name, lhs, rhs }); return name; } fn genCall(ctx: *Context, file: *C, inst: *Inst.Call) !?[]u8 { const writer = file.main.writer(); const header = file.header.buf.writer(); try writer.writeAll(indentation); if (inst.func.castTag(.constant)) |func_inst| { if (func_inst.val.cast(Value.Payload.Function)) |func_val| { const target = func_val.func.owner_decl; const target_ty = target.typed_value.most_recent.typed_value.ty; const ret_ty = target_ty.fnReturnType().tag(); if (target_ty.fnReturnType().hasCodeGenBits() and inst.base.isUnused()) { try writer.print("(void)", .{}); } const tname = mem.spanZ(target.name); if (file.called.get(tname) == null) { try file.called.put(tname, void{}); try renderFunctionSignature(ctx, &file.header, header, target); try header.writeAll(";\n"); } try writer.print("{}(", .{tname}); if (inst.args.len != 0) { for (inst.args) |arg, i| { if (i > 0) { try writer.writeAll(", "); } if (arg.cast(Inst.Constant)) |con| { try renderValue(ctx, writer, arg.ty, con.val); } else { const val = try ctx.resolveInst(arg); try writer.print("{}", .{val}); } } } try writer.writeAll(");\n"); } else { return ctx.fail(ctx.decl.src(), "TODO non-function call target?", .{}); } } else { return ctx.fail(ctx.decl.src(), "TODO non-constant call inst?", .{}); } return null; } fn genDbgStmt(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { // TODO emit #line directive here with line number and filename return null; } fn genBreak(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { // TODO ?? return null; } fn genUnreach(file: *C, inst: *Inst.NoOp) !?[]u8 { try file.main.writer().writeAll(indentation ++ "zig_unreachable();\n"); return null; } fn genAsm(ctx: *Context, file: *C, as: *Inst.Assembly) !?[]u8 { const writer = file.main.writer(); try writer.writeAll(indentation); for (as.inputs) |i, index| { if (i[0] == '{' and i[i.len - 1] == '}') { const reg = i[1 .. i.len - 1]; const arg = as.args[index]; try writer.writeAll("register "); try renderType(ctx, &file.header, writer, arg.ty); try writer.print(" {}_constant __asm__(\"{}\") = ", .{ reg, reg }); // TODO merge constant handling into inst_map as well if (arg.castTag(.constant)) |c| { try renderValue(ctx, writer, arg.ty, c.val); try writer.writeAll(";\n "); } else { const gop = try ctx.inst_map.getOrPut(arg); if (!gop.found_existing) { return ctx.fail(ctx.decl.src(), "Internal error in C backend: asm argument not found in inst_map", .{}); } try writer.print("{};\n ", .{gop.entry.value}); } } else { return ctx.fail(ctx.decl.src(), "TODO non-explicit inline asm regs", .{}); } } try writer.print("__asm {} (\"{}\"", .{ if (as.is_volatile) @as([]const u8, "volatile") else "", as.asm_source }); if (as.output) |o| { return ctx.fail(ctx.decl.src(), "TODO inline asm output", .{}); } if (as.inputs.len > 0) { if (as.output == null) { try writer.writeAll(" :"); } try writer.writeAll(": "); for (as.inputs) |i, index| { if (i[0] == '{' and i[i.len - 1] == '}') { const reg = i[1 .. i.len - 1]; const arg = as.args[index]; if (index > 0) { try writer.writeAll(", "); } try writer.print("\"\"({}_constant)", .{reg}); } else { // This is blocked by the earlier test unreachable; } } } try writer.writeAll(");\n"); return null; }
src/codegen/c.zig
const std = @import("../std.zig"); const __rem_pio2_large = @import("__rem_pio2_large.zig").__rem_pio2_large; const math = std.math; const toint = 1.5 / math.floatEps(f64); // pi/4 const pio4 = 0x1.921fb54442d18p-1; // invpio2: 53 bits of 2/pi const invpio2 = 6.36619772367581382433e-01; // 0x3FE45F30, 0x6DC9C883 // pio2_1: first 33 bit of pi/2 const pio2_1 = 1.57079632673412561417e+00; // 0x3FF921FB, 0x54400000 // pio2_1t: pi/2 - pio2_1 const pio2_1t = 6.07710050650619224932e-11; // 0x3DD0B461, 0x1A626331 // pio2_2: second 33 bit of pi/2 const pio2_2 = 6.07710050630396597660e-11; // 0x3DD0B461, 0x1A600000 // pio2_2t: pi/2 - (pio2_1+pio2_2) const pio2_2t = 2.02226624879595063154e-21; // 0x3BA3198A, 0x2E037073 // pio2_3: third 33 bit of pi/2 const pio2_3 = 2.02226624871116645580e-21; // 0x3BA3198A, 0x2E000000 // pio2_3t: pi/2 - (pio2_1+pio2_2+pio2_3) const pio2_3t = 8.47842766036889956997e-32; // 0x397B839A, 0x252049C1 fn U(x: anytype) usize { return @intCast(usize, x); } fn medium(ix: u32, x: f64, y: *[2]f64) i32 { var w: f64 = undefined; var t: f64 = undefined; var r: f64 = undefined; var @"fn": f64 = undefined; var n: i32 = undefined; var ex: i32 = undefined; var ey: i32 = undefined; var ui: u64 = undefined; // rint(x/(pi/2)) @"fn" = x * invpio2 + toint - toint; n = @floatToInt(i32, @"fn"); r = x - @"fn" * pio2_1; w = @"fn" * pio2_1t; // 1st round, good to 85 bits // Matters with directed rounding. if (r - w < -pio4) { n -= 1; @"fn" -= 1; r = x - @"fn" * pio2_1; w = @"fn" * pio2_1t; } else if (r - w > pio4) { n += 1; @"fn" += 1; r = x - @"fn" * pio2_1; w = @"fn" * pio2_1t; } y[0] = r - w; ui = @bitCast(u64, y[0]); ey = @intCast(i32, (ui >> 52) & 0x7ff); ex = @intCast(i32, ix >> 20); if (ex - ey > 16) { // 2nd round, good to 118 bits t = r; w = @"fn" * pio2_2; r = t - w; w = @"fn" * pio2_2t - ((t - r) - w); y[0] = r - w; ui = @bitCast(u64, y[0]); ey = @intCast(i32, (ui >> 52) & 0x7ff); if (ex - ey > 49) { // 3rd round, good to 151 bits, covers all cases t = r; w = @"fn" * pio2_3; r = t - w; w = @"fn" * pio2_3t - ((t - r) - w); y[0] = r - w; } } y[1] = (r - y[0]) - w; return n; } // Returns the remainder of x rem pi/2 in y[0]+y[1] // // use __rem_pio2_large() for large x // // caller must handle the case when reduction is not needed: |x| ~<= pi/4 */ pub fn __rem_pio2(x: f64, y: *[2]f64) i32 { var z: f64 = undefined; var tx: [3]f64 = undefined; var ty: [2]f64 = undefined; var n: i32 = undefined; var ix: u32 = undefined; var sign: bool = undefined; var i: i32 = undefined; var ui: u64 = undefined; ui = @bitCast(u64, x); sign = ui >> 63 != 0; ix = @truncate(u32, (ui >> 32) & 0x7fffffff); if (ix <= 0x400f6a7a) { // |x| ~<= 5pi/4 if ((ix & 0xfffff) == 0x921fb) { // |x| ~= pi/2 or 2pi/2 return medium(ix, x, y); } if (ix <= 0x4002d97c) { // |x| ~<= 3pi/4 if (!sign) { z = x - pio2_1; // one round good to 85 bits y[0] = z - pio2_1t; y[1] = (z - y[0]) - pio2_1t; return 1; } else { z = x + pio2_1; y[0] = z + pio2_1t; y[1] = (z - y[0]) + pio2_1t; return -1; } } else { if (!sign) { z = x - 2 * pio2_1; y[0] = z - 2 * pio2_1t; y[1] = (z - y[0]) - 2 * pio2_1t; return 2; } else { z = x + 2 * pio2_1; y[0] = z + 2 * pio2_1t; y[1] = (z - y[0]) + 2 * pio2_1t; return -2; } } } if (ix <= 0x401c463b) { // |x| ~<= 9pi/4 if (ix <= 0x4015fdbc) { // |x| ~<= 7pi/4 if (ix == 0x4012d97c) { // |x| ~= 3pi/2 return medium(ix, x, y); } if (!sign) { z = x - 3 * pio2_1; y[0] = z - 3 * pio2_1t; y[1] = (z - y[0]) - 3 * pio2_1t; return 3; } else { z = x + 3 * pio2_1; y[0] = z + 3 * pio2_1t; y[1] = (z - y[0]) + 3 * pio2_1t; return -3; } } else { if (ix == 0x401921fb) { // |x| ~= 4pi/2 */ return medium(ix, x, y); } if (!sign) { z = x - 4 * pio2_1; y[0] = z - 4 * pio2_1t; y[1] = (z - y[0]) - 4 * pio2_1t; return 4; } else { z = x + 4 * pio2_1; y[0] = z + 4 * pio2_1t; y[1] = (z - y[0]) + 4 * pio2_1t; return -4; } } } if (ix < 0x413921fb) { // |x| ~< 2^20*(pi/2), medium size return medium(ix, x, y); } // all other (large) arguments if (ix >= 0x7ff00000) { // x is inf or NaN y[0] = x - x; y[1] = y[0]; return 0; } // set z = scalbn(|x|,-ilogb(x)+23) ui = @bitCast(u64, x); ui &= std.math.maxInt(u64) >> 12; ui |= @as(u64, 0x3ff + 23) << 52; z = @bitCast(f64, ui); i = 0; while (i < 2) : (i += 1) { tx[U(i)] = @intToFloat(f64, @floatToInt(i32, z)); z = (z - tx[U(i)]) * 0x1p24; } tx[U(i)] = z; // skip zero terms, first term is non-zero while (tx[U(i)] == 0.0) { i -= 1; } n = __rem_pio2_large(tx[0..], ty[0..], @intCast(i32, (ix >> 20)) - (0x3ff + 23), i + 1, 1); if (sign) { y[0] = -ty[0]; y[1] = -ty[1]; return -n; } y[0] = ty[0]; y[1] = ty[1]; return n; }
lib/std/math/__rem_pio2.zig
const std = @import("std"); const BigInt = std.math.big.int.Const; const mem = std.mem; const Allocator = mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; // zig fmt: off pub const Tag = enum(u8) { bool = 0x01, int = 0x02, bit_string = 0x03, octet_string = 0x04, @"null" = 0x05, object_identifier = 0x06, utf8_string = 0x0c, printable_string = 0x13, ia5_string = 0x16, utc_time = 0x17, bmp_string = 0x1e, sequence = 0x30, set = 0x31, // Bogus value context_specific = 0xff, }; // zig fmt: on pub const ObjectIdentifier = struct { data: [16]u32, len: u8, }; pub const BitString = struct { data: []const u8, bit_len: usize, }; pub const Value = union(Tag) { bool: bool, int: BigInt, bit_string: BitString, octet_string: []const u8, @"null", // @TODO Make this []u32, owned? object_identifier: ObjectIdentifier, utf8_string: []const u8, printable_string: []const u8, ia5_string: []const u8, utc_time: []const u8, bmp_string: []const u16, sequence: []const @This(), set: []const @This(), context_specific: struct { child: *const Value, number: u8, }, pub fn deinit(self: @This(), alloc: *Allocator) void { switch (self) { .int => |i| alloc.free(i.limbs), .bit_string => |bs| alloc.free(bs.data), .octet_string, .utf8_string, .printable_string, .ia5_string, .utc_time, => |s| alloc.free(s), .bmp_string => |s| alloc.free(s), .sequence, .set => |s| { for (s) |c| { c.deinit(alloc); } alloc.free(s); }, .context_specific => |cs| { cs.child.deinit(alloc); alloc.destroy(cs.child); }, else => {}, } } fn formatInternal( self: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, indents: usize, writer: anytype, ) @TypeOf(writer).Error!void { try writer.writeByteNTimes(' ', indents); switch (self) { .bool => |b| try writer.print("BOOLEAN {}\n", .{b}), .int => |i| { try writer.writeAll("INTEGER "); try i.format(fmt, options, writer); try writer.writeByte('\n'); }, .bit_string => |bs| { try writer.print("BIT STRING ({} bits) ", .{bs.bit_len}); const bits_to_show = std.math.min(8 * 3, bs.bit_len); const bytes = std.math.divCeil(usize, bits_to_show, 8) catch unreachable; var bit_idx: usize = 0; var byte_idx: usize = 0; while (byte_idx < bytes) : (byte_idx += 1) { const byte = bs.data[byte_idx]; var cur_bit_idx: u3 = 0; while (bit_idx < bits_to_show) { const mask = @as(u8, 0x80) >> cur_bit_idx; try writer.print("{}", .{@boolToInt(byte & mask == mask)}); cur_bit_idx += 1; bit_idx += 1; if (cur_bit_idx == 7) break; } } if (bits_to_show != bs.bit_len) try writer.writeAll("..."); try writer.writeByte('\n'); }, .octet_string => |s| try writer.print("OCTET STRING ({} bytes) {X}\n", .{ s.len, s }), .@"null" => try writer.writeAll("NULL\n"), .object_identifier => |oid| { try writer.writeAll("OBJECT IDENTIFIER "); var i: u8 = 0; while (i < oid.len) : (i += 1) { if (i != 0) try writer.writeByte('.'); try writer.print("{}", .{oid.data[i]}); } try writer.writeByte('\n'); }, .utf8_string => |s| try writer.print("UTF8 STRING ({} bytes) {}\n", .{ s.len, s }), .printable_string => |s| try writer.print("PRINTABLE STRING ({} bytes) {}\n", .{ s.len, s }), .ia5_string => |s| try writer.print("IA5 STRING ({} bytes) {}\n", .{ s.len, s }), .utc_time => |s| try writer.print("UTC TIME {}\n", .{s}), .bmp_string => |s| try writer.print("BMP STRING ({} words) {}\n", .{ s.len, @ptrCast([*]const u16, s.ptr)[0 .. s.len * 2], }), .sequence => |children| { try writer.print("SEQUENCE ({} elems)\n", .{children.len}); for (children) |child| try child.formatInternal(fmt, options, indents + 2, writer); }, .set => |children| { try writer.print("SET ({} elems)\n", .{children.len}); for (children) |child| try child.formatInternal(fmt, options, indents + 2, writer); }, .context_specific => |cs| { try writer.print("[{}]\n", .{cs.number}); try cs.child.formatInternal(fmt, options, indents + 2, writer); }, } } pub fn format(self: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try self.formatInternal(fmt, options, 0, writer); } }; /// Distinguished encoding rules pub const der = struct { pub fn DecodeError(comptime Reader: type) type { return Reader.Error || error{ OutOfMemory, EndOfStream, InvalidLength, InvalidTag, InvalidContainerLength, DoesNotMatchSchema, }; } fn DERReaderState(comptime Reader: type) type { return struct { der_reader: Reader, length: usize, idx: usize = 0, }; } fn DERReader(comptime Reader: type) type { const S = struct { pub fn read(state: *DERReaderState(Reader), buffer: []u8) DecodeError(Reader)!usize { const out_bytes = std.math.min(buffer.len, state.length - state.idx); const res = try state.der_reader.readAll(buffer[0..out_bytes]); state.idx += res; return res; } }; return std.io.Reader(*DERReaderState(Reader), DecodeError(Reader), S.read); } pub fn parse_schema( schema: anytype, captures: anytype, der_reader: anytype, ) !void { const res = try parse_schema_tag_len_internal(null, null, schema, captures, der_reader); if (res != null) return error.DoesNotMatchSchema; } pub fn parse_schema_tag_len( existing_tag_byte: ?u8, existing_length: ?usize, schema: anytype, captures: anytype, der_reader: anytype, ) !void { const res = try parse_schema_tag_len_internal( existing_tag_byte, existing_length, schema, captures, der_reader, ); if (res != null) return error.DoesNotMatchSchema; } const TagLength = struct { tag: u8, length: usize, }; pub fn parse_schema_tag_len_internal( existing_tag_byte: ?u8, existing_length: ?usize, schema: anytype, captures: anytype, der_reader: anytype, ) !?TagLength { const Reader = @TypeOf(der_reader); const isEnumLit = comptime std.meta.trait.is(.EnumLiteral); comptime var tag_idx = 0; const has_capture = comptime isEnumLit(@TypeOf(schema[tag_idx])) and schema[tag_idx] == .capture; if (has_capture) tag_idx += 2; const is_optional = comptime isEnumLit(@TypeOf(schema[tag_idx])) and schema[tag_idx] == .optional; if (is_optional) tag_idx += 1; const tag_literal = schema[tag_idx]; comptime std.debug.assert(isEnumLit(@TypeOf(tag_literal))); const tag_byte = existing_tag_byte orelse (der_reader.readByte() catch |err| switch (err) { error.EndOfStream => |e| return if (is_optional) null else error.EndOfStream, else => |e| return e, }); const length = existing_length orelse try parse_length(der_reader); if (tag_literal == .sequence_of) { if (tag_byte != @enumToInt(Tag.sequence)) { if (is_optional) return TagLength{ .tag = tag_byte, .length = length }; return error.InvalidTag; } var curr_tag_length: ?TagLength = null; const sub_schema = schema[tag_idx + 1]; while (true) { if (curr_tag_length == null) { curr_tag_length = .{ .tag = der_reader.readByte() catch |err| switch (err) { error.EndOfStream => { curr_tag_length = null; break; }, else => |e| return e, }, .length = try parse_length(der_reader), }; } curr_tag_length = parse_schema_tag_len_internal( curr_tag_length.?.tag, curr_tag_length.?.length, sub_schema, captures, der_reader, ) catch |err| switch (err) { error.DoesNotMatchSchema => break, else => |e| return e, }; } return curr_tag_length; } else if (tag_literal == .any) { if (!has_capture) { try der_reader.skipBytes(length, .{}); return null; } var reader_state = DERReaderState(Reader){ .der_reader = der_reader, .idx = 0, .length = length, }; var reader = DERReader(@TypeOf(der_reader)){ .context = &reader_state }; const capture_context = captures[schema[1] * 2]; const capture_action = captures[schema[1] * 2 + 1]; try capture_action(capture_context, tag_byte, length, reader); // Skip remaining bytes try der_reader.skipBytes(reader_state.length - reader_state.idx, .{}); return null; } else if (tag_literal == .context_specific) { const cs_number = schema[tag_idx + 1]; if (tag_byte & 0xC0 == 0x80 and tag_byte - 0xa0 == cs_number) { if (!has_capture) { if (schema.len > tag_idx + 2) { return try parse_schema_tag_len_internal(null, null, schema[tag_idx + 2], captures, der_reader); } try der_reader.skipBytes(length, .{}); return null; } var reader_state = DERReaderState(Reader){ .der_reader = der_reader, .idx = 0, .length = length, }; var reader = DERReader(Reader){ .context = &reader_state }; const capture_context = captures[schema[1] * 2]; const capture_action = captures[schema[1] * 2 + 1]; try capture_action(capture_context, tag_byte, length, reader); // Skip remaining bytes try der_reader.skipBytes(reader_state.length - reader_state.idx, .{}); return null; } else if (is_optional) return TagLength{ .tag = tag_byte, .length = length } else return error.DoesNotMatchSchema; } const schema_tag: Tag = tag_literal; const actual_tag = std.meta.intToEnum(Tag, tag_byte) catch return error.InvalidTag; if (actual_tag != schema_tag) { if (is_optional) return TagLength{ .tag = tag_byte, .length = length }; return error.DoesNotMatchSchema; } const single_seq = schema_tag == .sequence and schema.len == 1; if ((!has_capture and schema_tag != .sequence) or (!has_capture and single_seq)) { try der_reader.skipBytes(length, .{}); return null; } if (has_capture) { var reader_state = DERReaderState(Reader){ .der_reader = der_reader, .idx = 0, .length = length, }; var reader = DERReader(Reader){ .context = &reader_state }; const capture_context = captures[schema[1] * 2]; const capture_action = captures[schema[1] * 2 + 1]; try capture_action(capture_context, tag_byte, length, reader); // Skip remaining bytes try der_reader.skipBytes(reader_state.length - reader_state.idx, .{}); return null; } var cur_tag_length: ?TagLength = null; const sub_schemas = schema[tag_idx + 1]; comptime var i = 0; inline while (i < sub_schemas.len) : (i += 1) { const curr_tag = if (cur_tag_length) |tl| tl.tag else null; const curr_length = if (cur_tag_length) |tl| tl.length else null; cur_tag_length = try parse_schema_tag_len_internal(curr_tag, curr_length, sub_schemas[i], captures, der_reader); } return cur_tag_length; } pub const EncodedLength = struct { data: [@sizeOf(usize) + 1]u8, len: usize, pub fn slice(self: @This()) []const u8 { if (self.len == 1) return self.data[0..1]; return self.data[0 .. 1 + self.len]; } }; pub fn encode_length(length: usize) EncodedLength { var enc = EncodedLength{ .data = undefined, .len = 0 }; if (length < 128) { enc.data[0] = @truncate(u8, length); enc.len = 1; } else { const bytes_needed = @intCast(u8, std.math.divCeil( usize, std.math.log2_int_ceil(usize, length), 8, ) catch unreachable); enc.data[0] = bytes_needed | 0x80; mem.copy( u8, enc.data[1 .. bytes_needed + 1], mem.asBytes(&length)[0..bytes_needed], ); if (std.builtin.endian != .Big) { mem.reverse(u8, enc.data[1 .. bytes_needed + 1]); } enc.len = bytes_needed; } return enc; } fn parse_int_internal(alloc: *Allocator, bytes_read: *usize, der_reader: anytype) !BigInt { const length = try parse_length_internal(bytes_read, der_reader); return try parse_int_with_length_internal(alloc, bytes_read, length, der_reader); } pub fn parse_int(alloc: *Allocator, der_reader: anytype) !BigInt { var bytes: usize = undefined; return try parse_int_internal(alloc, &bytes, der_reader); } pub fn parse_int_with_length(alloc: *Allocator, length: usize, der_reader: anytype) !BigInt { var read: usize = 0; return try parse_int_with_length_internal(alloc, &read, length, der_reader); } fn parse_int_with_length_internal(alloc: *Allocator, bytes_read: *usize, length: usize, der_reader: anytype) !BigInt { const first_byte = try der_reader.readByte(); if (first_byte == 0x0 and length > 1) { // Positive number with highest bit set to 1 in the rest. const limb_count = std.math.divCeil(usize, length - 1, @sizeOf(usize)) catch unreachable; const limbs = try alloc.alloc(usize, limb_count); std.mem.set(usize, limbs, 0); errdefer alloc.free(limbs); var limb_ptr = @ptrCast([*]u8, limbs.ptr); try der_reader.readNoEof(limb_ptr[0 .. length - 1]); // We always reverse because the standard library big int expects little endian. mem.reverse(u8, limb_ptr[0 .. length - 1]); bytes_read.* += length; return BigInt{ .limbs = limbs, .positive = true }; } std.debug.assert(length != 0); // Write first_byte // Twos complement const limb_count = std.math.divCeil(usize, length, @sizeOf(usize)) catch unreachable; const limbs = try alloc.alloc(usize, limb_count); std.mem.set(usize, limbs, 0); errdefer alloc.free(limbs); var limb_ptr = @ptrCast([*]u8, limbs.ptr); limb_ptr[0] = first_byte & ~@as(u8, 0x80); try der_reader.readNoEof(limb_ptr[1..length]); // We always reverse because the standard library big int expects little endian. mem.reverse(u8, limb_ptr[0..length]); bytes_read.* += length; return BigInt{ .limbs = limbs, .positive = (first_byte & 0x80) == 0x00 }; } pub fn parse_length(der_reader: anytype) !usize { var bytes: usize = 0; return try parse_length_internal(&bytes, der_reader); } fn parse_length_internal(bytes_read: *usize, der_reader: anytype) !usize { const first_byte = try der_reader.readByte(); bytes_read.* += 1; if (first_byte & 0x80 == 0x00) { // 1 byte value return first_byte; } const length = @truncate(u7, first_byte); if (length > @sizeOf(usize)) @panic("DER length does not fit in usize"); var res_buf = std.mem.zeroes([@sizeOf(usize)]u8); try der_reader.readNoEof(res_buf[0..length]); bytes_read.* += length; if (std.builtin.endian != .Big) { mem.reverse(u8, res_buf[0..length]); } return mem.bytesToValue(usize, &res_buf); } fn parse_value_with_tag_byte( tag_byte: u8, alloc: *Allocator, bytes_read: *usize, der_reader: anytype, ) DecodeError(@TypeOf(der_reader))!Value { const tag = std.meta.intToEnum(Tag, tag_byte) catch { // tag starts with '0b10...', this is the context specific class. if (tag_byte & 0xC0 == 0x80) { const length = try parse_length_internal(bytes_read, der_reader); var cur_read_bytes: usize = 0; var child = try alloc.create(Value); errdefer alloc.destroy(child); child.* = try parse_value_internal(alloc, &cur_read_bytes, der_reader); if (cur_read_bytes != length) return error.InvalidContainerLength; bytes_read.* += length; return Value{ .context_specific = .{ .child = child, .number = tag_byte - 0xa0 } }; } return error.InvalidTag; }; switch (tag) { .bool => { if ((try der_reader.readByte()) != 0x1) return error.InvalidLength; defer bytes_read.* += 2; return Value{ .bool = (try der_reader.readByte()) != 0x0 }; }, .int => return Value{ .int = try parse_int_internal(alloc, bytes_read, der_reader) }, .bit_string => { const length = try parse_length_internal(bytes_read, der_reader); const unused_bits = try der_reader.readByte(); std.debug.assert(unused_bits < 8); const bit_count = (length - 1) * 8 - unused_bits; const bit_memory = try alloc.alloc(u8, std.math.divCeil(usize, bit_count, 8) catch unreachable); errdefer alloc.free(bit_memory); try der_reader.readNoEof(bit_memory[0 .. length - 1]); bytes_read.* += length; return Value{ .bit_string = .{ .data = bit_memory, .bit_len = bit_count } }; }, .octet_string, .utf8_string, .printable_string, .utc_time, .ia5_string => { const length = try parse_length_internal(bytes_read, der_reader); const str_mem = try alloc.alloc(u8, length); try der_reader.readNoEof(str_mem); bytes_read.* += length; return @as(Value, switch (tag) { .octet_string => .{ .octet_string = str_mem }, .utf8_string => .{ .utf8_string = str_mem }, .printable_string => .{ .printable_string = str_mem }, .utc_time => .{ .utc_time = str_mem }, .ia5_string => .{ .ia5_string = str_mem }, else => unreachable, }); }, .@"null" => { std.debug.assert((try parse_length_internal(bytes_read, der_reader)) == 0x00); return .@"null"; }, .object_identifier => { const length = try parse_length_internal(bytes_read, der_reader); const first_byte = try der_reader.readByte(); var ret = Value{ .object_identifier = .{ .data = undefined, .len = 0 } }; ret.object_identifier.data[0] = first_byte / 40; ret.object_identifier.data[1] = first_byte % 40; var out_idx: u8 = 2; var i: usize = 0; while (i < length - 1) { var current_value: u32 = 0; var current_byte = try der_reader.readByte(); i += 1; while (current_byte & 0x80 == 0x80) : (i += 1) { // Increase the base of the previous bytes current_value *= 128; // Add the current byte in base 128 current_value += @as(u32, current_byte & ~@as(u8, 0x80)) * 128; current_byte = try der_reader.readByte(); } else { current_value += current_byte; } ret.object_identifier.data[out_idx] = current_value; out_idx += 1; } ret.object_identifier.len = out_idx; std.debug.assert(out_idx <= 16); bytes_read.* += length; return ret; }, .bmp_string => { const length = try parse_length_internal(bytes_read, der_reader); const str_mem = try alloc.alloc(u16, @divExact(length, 2)); errdefer alloc.free(str_mem); for (str_mem) |*wide_char| { wide_char.* = try der_reader.readIntBig(u16); } bytes_read.* += length; return Value{ .bmp_string = str_mem }; }, .sequence, .set => { const length = try parse_length_internal(bytes_read, der_reader); var cur_read_bytes: usize = 0; var arr = std.ArrayList(Value).init(alloc); errdefer arr.deinit(); while (cur_read_bytes < length) { (try arr.addOne()).* = try parse_value_internal(alloc, &cur_read_bytes, der_reader); } if (cur_read_bytes != length) return error.InvalidContainerLength; bytes_read.* += length; return @as(Value, switch (tag) { .sequence => .{ .sequence = arr.toOwnedSlice() }, .set => .{ .set = arr.toOwnedSlice() }, else => unreachable, }); }, .context_specific => unreachable, } } fn parse_value_internal(alloc: *Allocator, bytes_read: *usize, der_reader: anytype) DecodeError(@TypeOf(der_reader))!Value { const tag_byte = try der_reader.readByte(); bytes_read.* += 1; return try parse_value_with_tag_byte(tag_byte, alloc, bytes_read, der_reader); } pub fn parse_value(alloc: *Allocator, der_reader: anytype) DecodeError(@TypeOf(der_reader))!Value { var read: usize = 0; return try parse_value_internal(alloc, &read, der_reader); } }; test "der.parse_value" { const github_der = @embedFile("../test/github.der"); var fbs = std.io.fixedBufferStream(github_der); var arena = ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); _ = try der.parse_value(&arena.allocator, fbs.reader()); }
src/asn1.zig
const std = @import("std"); usingnamespace @import("imgui"); const colors = @import("../colors.zig"); const Tilemap = @import("tilemap.zig").Tilemap; const Tileset = @import("tileset.zig").Tileset; pub const TilemapEditor = struct { map: Tilemap, tileset: Tileset, shift_dragged: bool = false, dragged: bool = false, prev_mouse_pos: ImVec2 = .{}, pub fn init(map: Tilemap, tileset: Tileset) TilemapEditor { return .{ .map = map, .tileset = tileset }; } pub fn deinit(self: @This()) void {_ = self;} pub fn mapSize(self: @This()) ImVec2 { return .{ .x = @intToFloat(f32, self.map.w * self.tileset.tile_size), .y = @intToFloat(f32, self.map.h * self.tileset.tile_size) }; } pub fn draw(self: *@This(), name: [*c]const u8) void { // if the alt key is down dont allow scrolling with the mouse wheel since we will be zooming with it var window_flags = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysHorizontalScrollbar; if (igGetIO().KeyAlt) window_flags |= ImGuiWindowFlags_NoScrollWithMouse; defer igEnd(); if (!igBegin(name, null, window_flags)) return; var pos = ogGetCursorScreenPos(); var map_size = self.mapSize(); ogAddRectFilled(igGetWindowDrawList(), pos, map_size, colors.rgbToU32(0, 0, 0)); self.drawPostProcessedMap(pos); _ = ogInvisibleButton("##input_map_button", map_size, ImGuiButtonFlags_None); const is_hovered = igIsItemHovered(ImGuiHoveredFlags_None); if (is_hovered) self.handleInput(pos); // draw a rect over the current tile if (is_hovered and !self.shift_dragged) { var tile = tileIndexUnderPos(igGetIO().MousePos, self.tileset.tile_size, pos); const tl = ImVec2{ .x = pos.x + @intToFloat(f32, tile.x * self.tileset.tile_size), .y = pos.y + @intToFloat(f32, tile.y * self.tileset.tile_size) }; ogAddQuad(igGetWindowDrawList(), tl, @intToFloat(f32, self.tileset.tile_size), colors.rgbToU32(116, 252, 253), 1); } } pub fn drawTileset(self: *@This(), name: [*c]const u8) void { self.tileset.drawTileset(name); } pub fn drawLayers(self: *@This(), name: [*c]const u8) void { defer igEnd(); if (!igBegin(name, null, ImGuiWindowFlags_None)) return; for (self.map.layers) |layer, i| { igPushIDInt(@intCast(c_int, i)); defer igPopID(); if (ogSelectableBool(layer.name.ptr, i == self.map.current_layer, ImGuiSelectableFlags_None, .{})) { self.map.current_layer = i; } } if (ogButton("Add Layer")) self.map.addLayer(); } fn handleInput(self: *@This(), origin: ImVec2) void { // scrolling via drag with alt or super key down if (igIsMouseDragging(ImGuiMouseButton_Left, 0) and (igGetIO().KeyAlt or igGetIO().KeySuper)) { var scroll_delta = ogGetMouseDragDelta(ImGuiMouseButton_Left, 0); igSetScrollXFloat(igGetScrollX() - scroll_delta.x); igSetScrollYFloat(igGetScrollY() - scroll_delta.y); igResetMouseDragDelta(ImGuiMouseButton_Left); return; } // box selection with left/right mouse + shift if (ogIsAnyMouseDragging() and igGetIO().KeyShift) { var drag_delta = ogGetAnyMouseDragDelta(); var tile1 = tileIndexUnderPos(igGetIO().MousePos, self.tileset.tile_size, origin); drag_delta = drag_delta.add(origin); var tile2 = tileIndexUnderPos(igGetIO().MousePos, self.tileset.tile_size, drag_delta); const tile_size = @intToFloat(f32, self.tileset.tile_size); const min_x = @intToFloat(f32, std.math.min(tile1.x, tile2.x)) * tile_size + origin.x; const min_y = @intToFloat(f32, std.math.max(tile1.y, tile2.y)) * tile_size + tile_size + origin.y; const max_x = @intToFloat(f32, std.math.max(tile1.x, tile2.x)) * tile_size + tile_size + origin.x; const max_y = @intToFloat(f32, std.math.min(tile1.y, tile2.y)) * tile_size + origin.y; const color = if (igIsMouseDragging(ImGuiMouseButton_Left, 0)) colors.rgbToU32(255, 255, 255) else colors.rgbToU32(220, 0, 0); ogImDrawList_AddQuad(igGetWindowDrawList(), &ImVec2{ .x = min_x, .y = max_y }, &ImVec2{ .x = max_x, .y = max_y }, &ImVec2{ .x = max_x, .y = min_y }, &ImVec2{ .x = min_x, .y = min_y }, color, 2); self.shift_dragged = true; } else if ((igIsMouseReleased(ImGuiMouseButton_Left) or igIsMouseReleased(ImGuiMouseButton_Right)) and self.shift_dragged) { self.shift_dragged = false; var drag_delta = if (igIsMouseReleased(ImGuiMouseButton_Left)) ogGetMouseDragDelta(ImGuiMouseButton_Left, 0) else ogGetMouseDragDelta(ImGuiMouseButton_Right, 0); var tile1 = tileIndexUnderPos(igGetIO().MousePos, self.tileset.tile_size, origin); drag_delta = drag_delta.add(origin); var tile2 = tileIndexUnderPos(igGetIO().MousePos, self.tileset.tile_size, drag_delta); const min_x = std.math.min(tile1.x, tile2.x); var min_y = std.math.min(tile1.y, tile2.y); const max_x = std.math.max(tile1.x, tile2.x); const max_y = std.math.max(tile1.y, tile2.y); // either set the tile to a brush or 0 depending on mouse button const selected_brush_index: usize = self.tileset.selected; // TODO: brushes const tile_value = if (igIsMouseReleased(ImGuiMouseButton_Left)) selected_brush_index + 1 else 0; while (min_y <= max_y) : (min_y += 1) { var x = min_x; while (x <= max_x) : (x += 1) { self.map.setTile(x, min_y, @intCast(u8, tile_value)); } } } else if (ogIsAnyMouseDown() and !igGetIO().KeyShift) { var tile = tileIndexUnderPos(igGetIO().MousePos, self.tileset.tile_size, origin); const brush_index: u8 = if (igIsMouseDown(ImGuiMouseButton_Left)) self.tileset.selected + 1 else 0; // if the mouse down last frame, get last mouse pos and ensure we dont skip tiles when drawing if (self.dragged) { self.commitInBetweenTiles(tile.x, tile.y, origin, brush_index); } self.dragged = true; self.prev_mouse_pos = igGetIO().MousePos; self.map.setTile(tile.x, tile.y, brush_index); } else if (igIsMouseReleased(ImGuiMouseButton_Left) or igIsMouseReleased(ImGuiMouseButton_Right)) { self.dragged = false; } } fn drawPostProcessedMap(self: @This(), origin: ImVec2) void { for (self.map.layers) |layer| { var y: usize = 0; while (y < self.map.h) : (y += 1) { var x: usize = 0; while (x < self.map.w) : (x += 1) { const tile = layer.data[x + y * self.map.w]; if (tile == 0) continue; const offset = ImVec2.init(@intToFloat(f32, x * self.tileset.tile_size), @intToFloat(f32, y * self.tileset.tile_size)); var tl = origin.add(offset); self.drawTile(tl, tile - 1, 1); } } } } fn commitInBetweenTiles(self: *@This(), tile_x: usize, tile_y: usize, origin: ImVec2, color: u8) void { var prev_tile = tileIndexUnderPos(self.prev_mouse_pos, self.tileset.tile_size, origin); const abs_x = std.math.absInt(@intCast(i32, tile_x) - @intCast(i32, prev_tile.x)) catch unreachable; const abs_y = std.math.absInt(@intCast(i32, tile_y) - @intCast(i32, prev_tile.y)) catch unreachable; if (abs_x <= 1 and abs_y <= 1) { return; } self.bresenham(@intToFloat(f32, prev_tile.x), @intToFloat(f32, prev_tile.y), @intToFloat(f32, tile_x), @intToFloat(f32, tile_y), color); } /// fill in all the tiles between the two mouse positions using bresenham's line algo fn bresenham(self: *@This(), in_x1: f32, in_y1: f32, in_x2: f32, in_y2: f32, color: u8) void { var x1 = in_x1; var y1 = in_y1; var x2 = in_x2; var y2 = in_y2; const steep = std.math.absFloat(y2 - y1) > std.math.absFloat(x2 - x1); if (steep) { std.mem.swap(f32, &x1, &y1); std.mem.swap(f32, &x2, &y2); } if (x1 > x2) { std.mem.swap(f32, &x1, &x2); std.mem.swap(f32, &y1, &y2); } const dx: f32 = x2 - x1; const dy: f32 = std.math.absFloat(y2 - y1); var err: f32 = dx / 2.0; var ystep: i32 = if (y1 < y2) 1 else -1; var y: i32 = @floatToInt(i32, y1); const maxX: i32 = @floatToInt(i32, x2); var x: i32 = @floatToInt(i32, x1); while (x <= maxX) : (x += 1) { if (steep) { self.map.setTile(@intCast(usize, y), @intCast(usize, x), color); } else { self.map.setTile(@intCast(usize, x), @intCast(usize, y), color); } err -= dy; if (err < 0) { y += ystep; err += dx; } } } fn drawTile(self: @This(), tl: ImVec2, tile: usize, zoom: usize) void { var br = tl; br.x += @intToFloat(f32, self.tileset.tile_size * zoom); br.y += @intToFloat(f32, self.tileset.tile_size * zoom); const rect = self.tileset.uvsForTile(tile); const uv0 = ImVec2{ .x = rect.x, .y = rect.y }; const uv1 = ImVec2{ .x = rect.x + rect.width, .y = rect.y + rect.height }; ogImDrawList_AddImage(igGetWindowDrawList(), self.tileset.tex.imTextureID(), tl, br, uv0, uv1, 0xffffffff); } }; /// helper to find the tile under the position given a top-left position of the grid (origin) and a grid size pub fn tileIndexUnderPos(pos: ImVec2, rect_size: usize, origin: ImVec2) struct { x: usize, y: usize } { const final_pos = pos.subtract(origin); return .{ .x = @divTrunc(@floatToInt(usize, final_pos.x), rect_size), .y = @divTrunc(@floatToInt(usize, final_pos.y), rect_size) }; }
src/tilemaps/editor.zig
const std = @import("std"); const assert = std.debug.assert; const testing = std.testing; const c = @cImport({ @cInclude("pcre.h"); }); pub const Options = struct { Anchored: bool = false, AutoCallout: bool = false, BsrAnycrlf: bool = false, BsrUnicode: bool = false, Caseless: bool = false, DollarEndonly: bool = false, Dotall: bool = false, Dupnames: bool = false, Extended: bool = false, Extra: bool = false, Firstline: bool = false, JavascriptCompat: bool = false, Multiline: bool = false, NeverUtf: bool = false, NewlineAny: bool = false, NewlineAnycrlf: bool = false, NewlineCr: bool = false, NewlineCrlf: bool = false, NewlineLf: bool = false, NoAutoCapture: bool = false, NoAutoPossess: bool = false, NoStartOptimize: bool = false, NoUtf16Check: bool = false, NoUtf32Check: bool = false, NoUtf8Check: bool = false, Ucp: bool = false, Ungreedy: bool = false, Utf16: bool = false, Utf32: bool = false, Utf8: bool = false, fn compile(options: Options) c_int { var r: c_int = 0; if (options.Anchored) r |= c.PCRE_ANCHORED; if (options.AutoCallout) r |= c.PCRE_AUTO_CALLOUT; if (options.BsrAnycrlf) r |= c.PCRE_BSR_ANYCRLF; if (options.BsrUnicode) r |= c.PCRE_BSR_UNICODE; if (options.Caseless) r |= c.PCRE_CASELESS; if (options.DollarEndonly) r |= c.PCRE_DOLLAR_ENDONLY; if (options.Dotall) r |= c.PCRE_DOTALL; if (options.Dupnames) r |= c.PCRE_DUPNAMES; if (options.Extended) r |= c.PCRE_EXTENDED; if (options.Extra) r |= c.PCRE_EXTRA; if (options.Firstline) r |= c.PCRE_FIRSTLINE; if (options.JavascriptCompat) r |= c.PCRE_JAVASCRIPT_COMPAT; if (options.Multiline) r |= c.PCRE_MULTILINE; if (options.NeverUtf) r |= c.PCRE_NEVER_UTF; if (options.NewlineAny) r |= c.PCRE_NEWLINE_ANY; if (options.NewlineAnycrlf) r |= c.PCRE_NEWLINE_ANYCRLF; if (options.NewlineCr) r |= c.PCRE_NEWLINE_CR; if (options.NewlineCrlf) r |= c.PCRE_NEWLINE_CRLF; if (options.NewlineLf) r |= c.PCRE_NEWLINE_LF; if (options.NoAutoCapture) r |= c.PCRE_NO_AUTO_CAPTURE; if (options.NoAutoPossess) r |= c.PCRE_NO_AUTO_POSSESS; if (options.NoStartOptimize) r |= c.PCRE_NO_START_OPTIMIZE; if (options.NoUtf16Check) r |= c.PCRE_NO_UTF16_CHECK; if (options.NoUtf32Check) r |= c.PCRE_NO_UTF32_CHECK; if (options.NoUtf8Check) r |= c.PCRE_NO_UTF8_CHECK; if (options.Ucp) r |= c.PCRE_UCP; if (options.Ungreedy) r |= c.PCRE_UNGREEDY; if (options.Utf16) r |= c.PCRE_UTF16; if (options.Utf32) r |= c.PCRE_UTF32; if (options.Utf8) r |= c.PCRE_UTF8; return r; } }; // pub const Compile2Error = enum(c_int) {}; pub const Regex = struct { pcre: *c.pcre, pcre_extra: ?*c.pcre_extra, capture_count: usize, pub const CompileError = error{CompileError} || std.mem.Allocator.Error; pub const ExecError = error{ExecError} || std.mem.Allocator.Error; pub fn compile( pattern: [:0]const u8, options: Options, ) CompileError!Regex { var err: [*c]const u8 = undefined; var err_offset: c_int = undefined; const pcre = c.pcre_compile(pattern, options.compile(), &err, &err_offset, 0) orelse { std.log.warn("pcre_compile (at {}): {s}\n", .{ err_offset, @ptrCast([*:0]const u8, err) }); return error.CompileError; }; errdefer c.pcre_free.?(pcre); const pcre_extra = c.pcre_study(pcre, 0, &err); if (err != 0) { std.log.warn("pcre_study: {s}\n", .{@ptrCast([*:0]const u8, err)}); return error.CompileError; } errdefer c.pcre_free_study(pcre_extra); var capture_count: c_int = undefined; var fullinfo_rc = c.pcre_fullinfo(pcre, pcre_extra, c.PCRE_INFO_CAPTURECOUNT, &capture_count); if (fullinfo_rc != 0) @panic("could not request PCRE_INFO_CAPTURECOUNT"); return Regex{ .pcre = pcre, .pcre_extra = pcre_extra, .capture_count = @intCast(usize, capture_count), }; } pub fn deinit(self: Regex) void { c.pcre_free_study(self.pcre_extra); c.pcre_free.?(self.pcre); } /// Returns the start and end index of the match if any, otherwise null. pub fn matches(self: Regex, s: []const u8, options: Options) ExecError!?Capture { var ovector: [3]c_int = undefined; var result = c.pcre_exec(self.pcre, self.pcre_extra, s.ptr, @intCast(c_int, s.len), 0, options.compile(), &ovector, 3); switch (result) { c.PCRE_ERROR_NOMATCH => return null, c.PCRE_ERROR_NOMEMORY => return error.OutOfMemory, else => {}, } // result == 0 implies there were capture groups that didn't fit into ovector. // We don't care. if (result < 0) { std.log.warn("pcre_exec: {}\n", .{result}); return error.ExecError; // TODO: should clarify } return Capture{ .start = @intCast(usize, ovector[0]), .end = @intCast(usize, ovector[1]) }; } /// Searches for capture groups in s. The 0th Capture of the result is the entire match. pub fn captures(self: Regex, allocator: std.mem.Allocator, s: []const u8, start_index: usize, options: Options) (ExecError || std.mem.Allocator.Error)!?[]?Capture { var ovecsize = (self.capture_count + 1) * 3; var ovector: []c_int = try allocator.alloc(c_int, ovecsize); defer allocator.free(ovector); var result = c.pcre_exec( self.pcre, self.pcre_extra, s.ptr, @intCast(c_int, s.len), @intCast(c_int, start_index), options.compile(), &ovector[0], @intCast(c_int, ovecsize), ); switch (result) { c.PCRE_ERROR_NOMATCH => return null, c.PCRE_ERROR_NOMEMORY => return error.OutOfMemory, else => {}, } // 0 implies we didn't allocate enough ovector, and should never happen. std.debug.assert(result != 0); if (result < 0) { std.log.warn("pcre_exec: {}\n", .{result}); return error.ExecError; // TODO: should clarify } var caps: []?Capture = try allocator.alloc(?Capture, @intCast(usize, self.capture_count + 1)); errdefer allocator.free(caps); for (caps) |*cap, i| { if (i >= result) { cap.* = null; } else if (ovector[i * 2] == -1) { assert(ovector[i * 2 + 1] == -1); cap.* = null; } else { cap.* = .{ .start = @intCast(usize, ovector[i * 2]), .end = @intCast(usize, ovector[i * 2 + 1]), }; } } return caps; } pub const MatchList = std.ArrayList([]?Capture); pub fn captureAll( self: Regex, allocator: std.mem.Allocator, s: []const u8, options: Options, ) (ExecError || std.mem.Allocator.Error)!Regex.MatchList { var offset: usize = 0; var match_list = Regex.MatchList.init(allocator); errdefer match_list.deinit(); while (true) { var maybe_single_capture = try self.captures(allocator, s, offset, options); if (maybe_single_capture) |single_capture| { try match_list.append(single_capture); offset = single_capture[0].?.end; } else { break; } } return match_list; } }; pub const Capture = struct { start: usize, end: usize, }; test "compiles" { const regex = Regex.compile("(", .{}); try testing.expectError(error.CompileError, regex); } test "matches" { const regex = try Regex.compile("hello", .{}); defer regex.deinit(); try testing.expect((try regex.matches("hello", .{})) != null); try testing.expect((try regex.matches("yes hello", .{})) != null); try testing.expect((try regex.matches("yes hello", .{ .Anchored = true })) == null); } test "captures" { const regex = try Regex.compile("(a+)b(c+)", .{}); defer regex.deinit(); try testing.expect((try regex.captures(std.testing.allocator, "a", 0, .{})) == null); const captures = (try regex.captures(std.testing.allocator, "aaaaabcc", 0, .{})).?; defer std.testing.allocator.free(captures); try testing.expectEqualSlices(?Capture, &[_]?Capture{ .{ .start = 0, .end = 8, }, .{ .start = 0, .end = 5, }, .{ .start = 6, .end = 8, }, }, captures); } test "missing capture group" { const regex = try Regex.compile("abc(def)(ghi)?(jkl)", .{}); defer regex.deinit(); const captures = (try regex.captures(std.testing.allocator, "abcdefjkl", 0, .{})).?; defer std.testing.allocator.free(captures); try testing.expectEqualSlices(?Capture, &[_]?Capture{ .{ .start = 0, .end = 9, }, .{ .start = 3, .end = 6, }, null, .{ .start = 6, .end = 9, }, }, captures); } test "missing capture group at end of capture list" { const regex = try Regex.compile("abc(def)(ghi)?jkl", .{}); defer regex.deinit(); const captures = (try regex.captures(std.testing.allocator, "abcdefjkl", 0, .{})).?; defer std.testing.allocator.free(captures); try testing.expectEqualSlices(?Capture, &[_]?Capture{ .{ .start = 0, .end = 9, }, .{ .start = 3, .end = 6, }, null, }, captures); } test "captureall" { const regex = try Regex.compile("\\[\\[.+\\]\\]", .{}); defer regex.deinit(); const matches = try regex.captureAll(std.testing.allocator, "[[x]]a[[b]]c[[asd]]", .{}); defer { for (matches.items) |match| std.testing.allocator.free(match); matches.deinit(); } try testing.expectEqualSlices(?Capture, &[_]?Capture{ .{ .start = 0, .end = 4, }, }, matches.items[0]); try testing.expectEqualSlices(?Capture, &[_]?Capture{ .{ .start = 6, .end = 10, }, }, matches.items[1]); try testing.expectEqualSlices(?Capture, &[_]?Capture{ .{ .start = 12, .end = 18, }, }, matches.items[2]); }
src/main.zig