forge
Explore
Log in

Don't you dare go Hollow

Releases split by side and guarded by protocol: Builder builds Server, Client or Both

Browse files at this commit

4b67e80f7edd3c93845d959f3a77a2dfde2907a4Ahmet Kaan GümüşParent: 27ceb05
  • feat
    • releases split by side and guarded by protocol: Builder builds Server, Client or Both
    • Windows builds in the Linux container with cargo-xwin (VM, ssh and install.bat gone
    • gpui-pre-windows vendored with the upstreamed GPUI_SHADERS_BYTES build.rs, shader bytes checked against shaders.hlsl's sha256)
    • every binary carries yumush-protocol:<ALPN>
    • the server refuses a release whose protocol differs from its own unless it holds the server and every released client target. ALPN yumush/6
Show full message
✨ feat: releases split by side and guarded by protocol: Builder builds Server, Client or Both; Windows builds in the Linux container with cargo-xwin (VM, ssh and install.bat gone; gpui-pre-windows vendored with the upstreamed GPUI_SHADERS_BYTES build.rs, shader bytes checked against shaders.hlsl's sha256); every binary carries yumush-protocol:<ALPN>; the server refuses a release whose protocol differs from its own unless it holds the server and every released client target. ALPN yumush/6

42 changed files +27354 -473

Cargo.lockmodified+0 -2
@@ -4207,8 +4207,6 @@ dependencies = [
4207 [[package]]4207 [[package]]
4208 name = "gpui-pre-windows"4208 name = "gpui-pre-windows"
4209 version = "0.3.14"4209 version = "0.3.14"
4210-source = "registry+https://github.com/rust-lang/crates.io-index"
4211-checksum = "8badbaa4129a88e4d2fdaa1615fc61b2a59d4ebb2ac36e5de51f75598f0dd992"
4212 dependencies = [4210 dependencies = [
4213 "accesskit",4211 "accesskit",
4214 "accesskit_windows",4212 "accesskit_windows",
Cargo.tomlmodified+4 -0
@@ -1,6 +1,7 @@
1 [workspace]1 [workspace]
2 resolver = "2"2 resolver = "2"
3 members = ["crates/client", "crates/common", "crates/pixel", "crates/spectrum", "crates/server", "crates/usage"]3 members = ["crates/client", "crates/common", "crates/pixel", "crates/spectrum", "crates/server", "crates/usage"]
4+exclude = ["vendor"]
4 5
5 [profile.dev]6 [profile.dev]
6 debug = "line-tables-only"7 debug = "line-tables-only"
@@ -49,3 +50,6 @@ quinn = { version = "0.11.12", default-features = false, features = [
49 "runtime-tokio",50 "runtime-tokio",
50 ] }51 ] }
51 rustls = "0.23.45"52 rustls = "0.23.45"
53+
54+[patch.crates-io]
55+gpui-pre-windows = { path = "vendor/gpui-pre-windows" }
crates/client/lang/en/builder_release.txtmodified+2 -3
@@ -6,7 +6,6 @@ required = Required
6 publish = Publish6 publish = Publish
7 confirm = Confirm7 confirm = Confirm
8 no_releases = No releases8 no_releases = No releases
9-build = Build
10 choose_source = Choose source9 choose_source = Choose source
11 no_source = No source folder10 no_source = No source folder
12 not_source = Not a release source11 not_source = Not a release source
@@ -17,8 +16,6 @@ skipped = Skipped
17 failed = Failed16 failed = Failed
18 linux_v1 = Linux v117 linux_v1 = Linux v1
19 linux_v3 = Linux v318 linux_v3 = Linux v3
20-windows_vm = Windows VM
21-this_machine = Linux container
22 prepare = Prepare19 prepare = Prepare
23 windows_v1 = Windows v120 windows_v1 = Windows v1
24 windows_v3 = Windows v321 windows_v3 = Windows v3
@@ -32,3 +29,5 @@ discard = Discard
32 server = Server29 server = Server
33 retry = Retry30 retry = Retry
34 stopping = Stopping31 stopping = Stopping
32+client = Client
33+both = Both
crates/client/lang/tr/builder_release.txtmodified+2 -3
@@ -6,7 +6,6 @@ required = Zorunlu
6 publish = Yayınla6 publish = Yayınla
7 confirm = Onayla7 confirm = Onayla
8 no_releases = Sürüm yok8 no_releases = Sürüm yok
9-build = Derle
10 choose_source = Kaynak seç9 choose_source = Kaynak seç
11 no_source = Kaynak klasörü yok10 no_source = Kaynak klasörü yok
12 not_source = Geçerli bir sürüm kaynağı değil11 not_source = Geçerli bir sürüm kaynağı değil
@@ -17,8 +16,6 @@ skipped = Atlandı
17 failed = Başarısız16 failed = Başarısız
18 linux_v1 = Linux v117 linux_v1 = Linux v1
19 linux_v3 = Linux v318 linux_v3 = Linux v3
20-windows_vm = Windows VM
21-this_machine = Linux kapsayıcı
22 prepare = Hazırlık19 prepare = Hazırlık
23 windows_v1 = Windows v120 windows_v1 = Windows v1
24 windows_v3 = Windows v321 windows_v3 = Windows v3
@@ -32,3 +29,5 @@ discard = Vazgeç
32 server = Sunucu29 server = Sunucu
33 retry = Tekrar dene30 retry = Tekrar dene
34 stopping = Durduruluyor31 stopping = Durduruluyor
32+client = İstemci
33+both = İkisi
crates/client/src/gui/builder/releases.rsmodified+34 -51
@@ -23,7 +23,7 @@ use crate::gui::{
23 text,23 text,
24 };24 };
25 use crate::lang::w;25 use crate::lang::w;
26-use crate::release::{Build, Event, Job, LANES, Lane, Level, is_source};26+use crate::release::{Build, Event, Job, Level, Side, is_source};
27 27
28 const METER: f32 = 140.;28 const METER: f32 = 140.;
29 const LOG_LINE: f32 = 18.;29 const LOG_LINE: f32 = 18.;
@@ -189,24 +189,15 @@ impl Desk {
189 fn job_label(job: Job) -> &'static str {189 fn job_label(job: Job) -> &'static str {
190 let w = &w().builder_release;190 let w = &w().builder_release;
191 match job {191 match job {
192- Job::LinuxStart => w.prepare,192+ Job::Prepare => w.prepare,
193 Job::Linux(Level::V1) => w.linux_v1,193 Job::Linux(Level::V1) => w.linux_v1,
194 Job::Linux(Level::V3) => w.linux_v3,194 Job::Linux(Level::V3) => w.linux_v3,
195 Job::Server => w.server,195 Job::Server => w.server,
196- Job::WindowsStart => w.prepare,
197 Job::Windows(Level::V1) => w.windows_v1,196 Job::Windows(Level::V1) => w.windows_v1,
198 Job::Windows(Level::V3) => w.windows_v3,197 Job::Windows(Level::V3) => w.windows_v3,
199 }198 }
200 }199 }
201 200
202-fn lane_label(lane: Lane) -> &'static str {
203- let w = &w().builder_release;
204- match lane {
205- Lane::Host => w.this_machine,
206- Lane::Vm => w.windows_vm,
207- }
208-}
209-
210 pub(super) fn caption_text(value: impl Into<String>, color: Hsla) -> Div {201 pub(super) fn caption_text(value: impl Into<String>, color: Hsla) -> Div {
211 div()202 div()
212 .text_size(text(text::CAPTION))203 .text_size(text(text::CAPTION))
@@ -497,18 +488,25 @@ impl Yumush {
497 yumush.pick_release_source(window, cx)488 yumush.pick_release_source(window, cx)
498 }),489 }),
499 );490 );
500- let build = parts::button(491+ let ready = self.settings.release_source.is_some() && !running;
501- "build_release",492+ let w = &w().builder_release;
502- w().builder_release.build,493+ let builds = [
503- Press::Primary,494+ ("build_server", w.server, Side::Server),
504- palette.tokens,495+ ("build_client", w.client, Side::Client),
505- entity_action(entity, |yumush, window, cx| yumush.start_build(window, cx)),496+ ("build_both", w.both, Side::Both),
506- );497+ ]
507- let build = if self.settings.release_source.is_some() && !running {498+ .map(|(id, label, side)| {
508- build499+ let button = parts::button(
509- } else {500+ id,
510- build.opacity(0.4)501+ label,
511- };502+ Press::Primary,
503+ palette.tokens,
504+ entity_action(entity, move |yumush, window, cx| {
505+ yumush.start_build(side, window, cx)
506+ }),
507+ );
508+ if ready { button } else { button.opacity(0.4) }
509+ });
512 510
513 card(palette)511 card(palette)
514 .child(512 .child(
@@ -523,7 +521,7 @@ impl Yumush {
523 .child(source),521 .child(source),
524 )522 )
525 .child(choose)523 .child(choose)
526- .child(build),524+ .children(builds),
527 )525 )
528 .children(526 .children(
529 self.desk527 self.desk
@@ -595,7 +593,7 @@ impl Yumush {
595 let Some(build) = &self.desk.build else {593 let Some(build) = &self.desk.build else {
596 return;594 return;
597 };595 };
598- build.retry(job);596+ build.retry();
599 if let Some(row) = self.desk.row(job) {597 if let Some(row) = self.desk.row(job) {
600 row.phase = Phase::Waiting;598 row.phase = Phase::Waiting;
601 row.line.clear();599 row.line.clear();
@@ -646,27 +644,12 @@ impl Yumush {
646 644
647 fn lanes(&self, entity: &Entity<Self>, fit: impl Fn(Div) -> Div, palette: Palette) -> Vec<Div> {645 fn lanes(&self, entity: &Entity<Self>, fit: impl Fn(Div) -> Div, palette: Palette) -> Vec<Div> {
648 let seconds = self.settings.clock_seconds;646 let seconds = self.settings.clock_seconds;
649- LANES647+ self.desk
648+ .jobs
650 .iter()649 .iter()
651- .filter(|(_, jobs)| self.desk.jobs.iter().any(|row| jobs.contains(&row.job)))650+ .map(|row| {
652- .map(|(lane, jobs)| {651+ let retry = self.retry_button(row, entity, palette);
653- div()652+ fit(job_row(row, seconds, retry, entity, palette))
654- .flex()
655- .flex_col()
656- .child(fit(list_row()
657- .text_size(text(text::LABEL))
658- .text_color(palette.muted)
659- .child(lane_label(*lane))))
660- .children(
661- self.desk
662- .jobs
663- .iter()
664- .filter(|row| jobs.contains(&row.job))
665- .map(|row| {
666- let retry = self.retry_button(row, entity, palette);
667- fit(job_row(row, seconds, retry, entity, palette).pl(px(space::XL)))
668- }),
669- )
670 })653 })
671 .collect()654 .collect()
672 }655 }
@@ -939,19 +922,19 @@ impl Yumush {
939 .detach();922 .detach();
940 }923 }
941 924
942- fn start_build(&mut self, window: &mut Window, cx: &mut Context<Self>) {925+ fn start_build(&mut self, side: Side, window: &mut Window, cx: &mut Context<Self>) {
943 let Some(source) = self.settings.release_source.clone() else {926 let Some(source) = self.settings.release_source.clone() else {
944 return;927 return;
945 };928 };
946 if self.desk.build.is_some() {929 if self.desk.build.is_some() {
947 return;930 return;
948 }931 }
949- let (build, mut events) = Build::start(source);932+ let (build, mut events) = Build::start(source, side);
950 self.desk.build = Some(build);933 self.desk.build = Some(build);
951- self.desk.jobs = LANES934+ self.desk.jobs = side
952- .iter()935+ .jobs()
953- .flat_map(|(_, jobs)| jobs.iter())936+ .into_iter()
954- .map(|&job| Row {937+ .map(|job| Row {
955 job,938 job,
956 phase: Phase::Waiting,939 phase: Phase::Waiting,
957 line: String::new(),940 line: String::new(),
crates/client/src/release.rsmodified+84 -390
@@ -5,7 +5,7 @@ use std::process::{Child, Command, ExitStatus, Stdio};
5 use std::sync::atomic::{AtomicBool, Ordering};5 use std::sync::atomic::{AtomicBool, Ordering};
6 use std::sync::{Arc, Mutex};6 use std::sync::{Arc, Mutex};
7 use std::thread;7 use std::thread;
8-use std::time::{Duration, Instant};8+use std::time::Duration;
9 9
10 use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};10 use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
11 11
@@ -17,38 +17,38 @@ pub enum Level {
17 17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19 pub enum Job {19 pub enum Job {
20- LinuxStart,20+ Prepare,
21- Linux(Level),
22 Server,21 Server,
23- WindowsStart,22+ Linux(Level),
24 Windows(Level),23 Windows(Level),
25 }24 }
26 25
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]26 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28-pub enum Lane {27+pub enum Side {
29- Host,28+ Server,
30- Vm,29+ Client,
31-}30+ Both,
32-31+}
33-pub const LANES: [(Lane, &[Job]); 2] = [32+
34- (33+impl Side {
35- Lane::Host,34+ pub fn jobs(self) -> Vec<Job> {
36- &[35+ let server = matches!(self, Side::Server | Side::Both);
37- Job::LinuxStart,36+ let client = matches!(self, Side::Client | Side::Both);
38- Job::Server,37+ let mut jobs = vec![Job::Prepare];
39- Job::Linux(Level::V1),38+ if server {
40- Job::Linux(Level::V3),39+ jobs.push(Job::Server);
41- ],40+ }
42- ),41+ if client {
43- (42+ jobs.extend([
44- Lane::Vm,43+ Job::Linux(Level::V1),
45- &[44+ Job::Linux(Level::V3),
46- Job::WindowsStart,45+ Job::Windows(Level::V1),
47- Job::Windows(Level::V1),46+ Job::Windows(Level::V3),
48- Job::Windows(Level::V3),47+ ]);
49- ],48+ }
50- ),49+ jobs
51-];50+ }
51+}
52 52
53 type Slot = Arc<Mutex<Option<Child>>>;53 type Slot = Arc<Mutex<Option<Child>>>;
54 54
@@ -67,17 +67,12 @@ pub enum Event {
67 const LINUX: &str = "yumush-linux";67 const LINUX: &str = "yumush-linux";
68 const LINUX_IMAGE: &str = "docker.io/library/ubuntu:24.04";68 const LINUX_IMAGE: &str = "docker.io/library/ubuntu:24.04";
69 const LINUX_CACHE: &str = ".cache/yumush-build";69 const LINUX_CACHE: &str = ".cache/yumush-build";
70-const LINUX_PACKAGES: &str = "ca-certificates curl git build-essential pkg-config clang cmake nasm libpipewire-0.3-dev libspa-0.2-dev libva-dev libdrm-dev libgbm-dev libxkbcommon-x11-dev libxkbcommon-dev libxcb1-dev libwayland-dev libvulkan-dev libfontconfig-dev libfreetype-dev libasound2-dev";70+const LINUX_READY: &str = "/etc/yumush-ready-2";
71+const LINUX_PACKAGES: &str = "ca-certificates curl git build-essential pkg-config clang lld llvm cmake nasm libpipewire-0.3-dev libspa-0.2-dev libva-dev libdrm-dev libgbm-dev libxkbcommon-x11-dev libxkbcommon-dev libxcb1-dev libwayland-dev libvulkan-dev libfontconfig-dev libfreetype-dev libasound2-dev";
72+const WINDOWS_TARGET: &str = "x86_64-pc-windows-msvc";
73+const SHADERS: &str = "crates/client/src/release/shaders_bytes.rs";
74+const SHADERS_SUM: &str = "crates/client/src/release/shaders.sha256";
71 const ARCHIVE: &str = "dist/source.tgz";75 const ARCHIVE: &str = "dist/source.tgz";
72-const VM: &str = "yumush-win";
73-const VM_DIR: &str = "vm/yumush-win";
74-const SSH_WAIT: Duration = Duration::from_secs(3 * 60 * 60);
75-const VM_IMAGE: &str = "docker.io/dockurr/windows";
76-const VM_AUDIO: &str = "ARGUMENTS=-audiodev none,id=snd0 -device ich9-intel-hda,id=hda1 -device hda-duplex,bus=hda1.0,audiodev=snd0 -device ich9-intel-hda,id=hda2 -device hda-duplex,bus=hda2.0,audiodev=snd0";
77-const INSTALL: &str = include_str!("release/install.bat");
78-const TARGET: &str = "yumush@127.0.0.1";
79-const PORT: &str = "2222";
80-const EXTRACT: &str = "Remove-Item -Recurse -Force release -ErrorAction SilentlyContinue; New-Item -ItemType Directory release | Out-Null; tar -xmzf release.tgz -C release";
81 76
82 static RUNNING: AtomicBool = AtomicBool::new(false);77 static RUNNING: AtomicBool = AtomicBool::new(false);
83 78
@@ -106,50 +101,41 @@ pub fn is_source(path: &Path) -> bool {
106 101
107 pub struct Build {102 pub struct Build {
108 cancel: Arc<AtomicBool>,103 cancel: Arc<AtomicBool>,
109- children: Vec<Slot>,104+ child: Slot,
110- retries: Vec<Arc<AtomicBool>>,105+ retry: Arc<AtomicBool>,
111 }106 }
112 107
113 impl Build {108 impl Build {
114- pub fn start(source: PathBuf) -> (Self, UnboundedReceiver<Event>) {109+ pub fn start(source: PathBuf, side: Side) -> (Self, UnboundedReceiver<Event>) {
115 let (tx, rx) = unbounded_channel();110 let (tx, rx) = unbounded_channel();
116 let build = Self {111 let build = Self {
117 cancel: Arc::default(),112 cancel: Arc::default(),
118- children: LANES.iter().map(|_| Slot::default()).collect(),113+ child: Slot::default(),
119- retries: LANES.iter().map(|_| Arc::default()).collect(),114+ retry: Arc::default(),
115+ };
116+ let cx = Cx {
117+ tx,
118+ cancel: build.cancel.clone(),
119+ child: build.child.clone(),
120+ retry: build.retry.clone(),
120 };121 };
121- let lanes: Vec<Cx> = build
122- .children
123- .iter()
124- .zip(&build.retries)
125- .map(|(child, retry)| Cx {
126- tx: tx.clone(),
127- cancel: build.cancel.clone(),
128- child: child.clone(),
129- retry: retry.clone(),
130- })
131- .collect();
132 let running = Running::new();122 let running = Running::new();
133 thread::spawn(move || {123 thread::spawn(move || {
134 let _running = running;124 let _running = running;
135- run(&source, &lanes);125+ run(&source, &side.jobs(), &cx);
136 });126 });
137 (build, rx)127 (build, rx)
138 }128 }
139 129
140- pub fn retry(&self, job: Job) {130+ pub fn retry(&self) {
141- if let Some(lane) = LANES.iter().position(|(_, jobs)| jobs.contains(&job)) {131+ self.retry.store(true, Ordering::SeqCst);
142- self.retries[lane].store(true, Ordering::SeqCst);
143- }
144 }132 }
145 133
146 pub fn cancel(&self) {134 pub fn cancel(&self) {
147 self.cancel.store(true, Ordering::SeqCst);135 self.cancel.store(true, Ordering::SeqCst);
148 podman_ok(&["stop", "-t", "2", LINUX]);136 podman_ok(&["stop", "-t", "2", LINUX]);
149- for slot in &self.children {137+ if let Some(child) = self.child.lock().unwrap().as_mut() {
150- if let Some(child) = slot.lock().unwrap().as_mut() {138+ let _ = child.kill();
151- let _ = child.kill();
152- }
153 }139 }
154 }140 }
155 }141 }
@@ -182,46 +168,26 @@ impl Cx {
182 }168 }
183 }169 }
184 170
185-fn run(source: &Path, lanes: &[Cx]) {171+fn run(source: &Path, jobs: &[Job], cx: &Cx) {
186- let key = vm_dir().join("id_ed25519");172+ let prepared = lock().and_then(|lock| preflight(source).map(|()| lock));
187- let first = &lanes[0];173+ match prepared {
188- let _lock = match lock() {174+ Ok(_lock) => {
189- Ok(lock) => lock,175+ run_jobs(jobs, source, cx);
190- Err(e) => {176+ podman_ok(&["stop", "-t", "2", LINUX]);
191- first.send(Event::Failed(LANES[0].1[0], e));
192- first.send(Event::Done);
193- return;
194 }177 }
195- };178+ Err(e) => cx.send(Event::Failed(jobs[0], e)),
196- let vm_was_running = match preflight(source) {
197- Ok(running) => running,
198- Err(e) => {
199- first.send(Event::Failed(LANES[0].1[0], e));
200- first.send(Event::Done);
201- return;
202- }
203- };
204- thread::scope(|scope| {
205- for ((_, jobs), cx) in LANES.iter().zip(lanes) {
206- let key = &key;
207- scope.spawn(move || run_lane(jobs, source, key, cx));
208- }
209- });
210- if !vm_was_running {
211- podman_ok(&["stop", VM]);
212 }179 }
213- podman_ok(&["stop", "-t", "2", LINUX]);180+ cx.send(Event::Done);
214- first.send(Event::Done);
215 }181 }
216 182
217-fn run_lane(jobs: &[Job], source: &Path, key: &Path, cx: &Cx) {183+fn run_jobs(jobs: &[Job], source: &Path, cx: &Cx) {
218 let mut next = 0;184 let mut next = 0;
219 while let Some(&job) = jobs.get(next) {185 while let Some(&job) = jobs.get(next) {
220 if cx.cancelled() {186 if cx.cancelled() {
221 cx.send(Event::Failed(job, "cancelled".into()));187 cx.send(Event::Failed(job, "cancelled".into()));
222 return;188 return;
223 }189 }
224- match run_job(job, source, key, cx) {190+ match run_job(job, source, cx) {
225 Ok(()) => next += 1,191 Ok(()) => next += 1,
226 Err(_) if cx.cancelled() => {192 Err(_) if cx.cancelled() => {
227 cx.send(Event::Failed(job, "cancelled".into()));193 cx.send(Event::Failed(job, "cancelled".into()));
@@ -246,7 +212,7 @@ fn lock() -> Result<fs::File, String> {
246 Ok(file)212 Ok(file)
247 }213 }
248 214
249-fn preflight(source: &Path) -> Result<bool, String> {215+fn preflight(source: &Path) -> Result<(), String> {
250 let dirty = Command::new("git")216 let dirty = Command::new("git")
251 .arg("-C")217 .arg("-C")
252 .arg(source)218 .arg(source)
@@ -256,51 +222,19 @@ fn preflight(source: &Path) -> Result<bool, String> {
256 if !dirty.stdout.is_empty() {222 if !dirty.stdout.is_empty() {
257 return Err("uncommitted changes".into());223 return Err("uncommitted changes".into());
258 }224 }
259- snapshot(source)?;225+ snapshot(source)
260- Ok(container_running(VM))
261 }226 }
262 227
263-fn container_running(container: &str) -> bool {228+fn run_job(job: Job, source: &Path, cx: &Cx) -> Result<(), String> {
264- podman()229+ if !cfg!(target_os = "linux") {
265- .args(["inspect", "-f", "{{.State.Running}}", container])230+ return skip(cx, job, "not linux");
266- .output()231+ }
267- .is_ok_and(|out| String::from_utf8_lossy(&out.stdout).trim() == "true")232+ cx.send(Event::Started(job));
268-}
269-
270-fn run_job(job: Job, source: &Path, key: &Path, cx: &Cx) -> Result<(), String> {
271 match job {233 match job {
272- Job::LinuxStart => {234+ Job::Prepare => prepare(job, source, cx),
273- if !cfg!(target_os = "linux") {235+ Job::Server => build_server(job, source, cx),
274- return skip(cx, job, "not linux");236+ Job::Linux(level) => build_linux(job, level, source, cx),
275- }237+ Job::Windows(level) => build_windows(job, level, source, cx),
276- cx.send(Event::Started(job));
277- start_linux(job, source, cx)
278- }
279- Job::Linux(level) => {
280- if !cfg!(target_os = "linux") {
281- return skip(cx, job, "not linux");
282- }
283- cx.send(Event::Started(job));
284- build_linux(job, level, source, cx)
285- }
286- Job::Server => {
287- if !cfg!(target_os = "linux") {
288- return skip(cx, job, "not linux");
289- }
290- cx.send(Event::Started(job));
291- build_server(job, source, cx)
292- }
293- Job::WindowsStart => {
294- if !cfg!(target_os = "linux") {
295- return skip(cx, job, "not linux");
296- }
297- cx.send(Event::Started(job));
298- start_windows(job, source, key, cx)
299- }
300- Job::Windows(level) => {
301- cx.send(Event::Started(job));
302- build_windows(job, level, source, key, cx)
303- }
304 }238 }
305 }239 }
306 240
@@ -316,12 +250,6 @@ fn flags(level: Level) -> (&'static str, &'static str) {
316 }250 }
317 }251 }
318 252
319-fn toml_text(cpu: &str) -> String {
320- format!(
321- "[target.'cfg(target_arch = \"x86_64\")']\nrustflags = [\"-C\", \"target-cpu={cpu}\"]\n"
322- )
323-}
324-
325 fn snapshot(source: &Path) -> Result<(), String> {253 fn snapshot(source: &Path) -> Result<(), String> {
326 fs::create_dir_all(source.join("dist")).map_err(|e| e.to_string())?;254 fs::create_dir_all(source.join("dist")).map_err(|e| e.to_string())?;
327 check(255 check(
@@ -363,7 +291,7 @@ fn in_linux(script: &str) -> Command {
363 cmd291 cmd
364 }292 }
365 293
366-fn start_linux(job: Job, source: &Path, cx: &Cx) -> Result<(), String> {294+fn prepare(job: Job, source: &Path, cx: &Cx) -> Result<(), String> {
367 let cache = linux_cache();295 let cache = linux_cache();
368 for dir in ["cargo", "rustup", "target"] {296 for dir in ["cargo", "rustup", "target"] {
369 fs::create_dir_all(cache.join(dir)).map_err(|e| e.to_string())?;297 fs::create_dir_all(cache.join(dir)).map_err(|e| e.to_string())?;
@@ -390,10 +318,11 @@ fn start_linux(job: Job, source: &Path, cx: &Cx) -> Result<(), String> {
390 )?;318 )?;
391 let rust = host_rust()?;319 let rust = host_rust()?;
392 let script = format!(320 let script = format!(
393- "[ -f /etc/yumush-ready ] || {{ apt-get update; apt-get install -y --no-install-recommends {LINUX_PACKAGES}; touch /etc/yumush-ready; }}321+ "[ -f {LINUX_READY} ] || {{ apt-get update; apt-get install -y --no-install-recommends {LINUX_PACKAGES}; touch {LINUX_READY}; }}
394 [ -x /root/.cargo/bin/rustup ] || curl -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path --default-toolchain none322 [ -x /root/.cargo/bin/rustup ] || curl -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path --default-toolchain none
395-rustup toolchain install {rust} --profile minimal323+rustup toolchain install {rust} --profile minimal --target {WINDOWS_TARGET}
396 rustup default {rust}324 rustup default {rust}
325+command -v cargo-xwin >/dev/null || cargo install cargo-xwin --locked
397 rm -rf src && mkdir src && tar -xmzf src.tgz -C src"326 rm -rf src && mkdir src && tar -xmzf src.tgz -C src"
398 );327 );
399 stream(&mut in_linux(&script), job, cx)?;328 stream(&mut in_linux(&script), job, cx)?;
@@ -447,241 +376,25 @@ fn build_server(job: Job, source: &Path, cx: &Cx) -> Result<(), String> {
447 )376 )
448 }377 }
449 378
450-fn vm_dir() -> PathBuf {379+fn build_windows(job: Job, level: Level, source: &Path, cx: &Cx) -> Result<(), String> {
451- dirs::home_dir().unwrap_or_default().join(VM_DIR)
452-}
453-
454-fn create_windows(job: Job, key: &Path, cx: &Cx) -> Result<(), String> {
455- if !Path::new("/dev/kvm").exists() {
456- return Err("no /dev/kvm".into());
457- }
458- let dir = vm_dir();
459- for sub in ["storage", "oem", "shared"] {
460- fs::create_dir_all(dir.join(sub)).map_err(|e| e.to_string())?;
461- }
462- if !key.exists() {
463- check(
464- Command::new("ssh-keygen")
465- .args(["-q", "-t", "ed25519", "-N", "", "-C", "yumush-vm", "-f"])
466- .arg(key),
467- )?;
468- }
469- let _ = Command::new("chattr")
470- .arg("+C")
471- .arg(dir.join("storage"))
472- .output();
473- let public = fs::read_to_string(key.with_extension("pub")).map_err(|e| e.to_string())?;
474- fs::write(
475- dir.join("oem/install.bat"),
476- INSTALL.replace("{key}", public.trim()),
477- )
478- .map_err(|e| e.to_string())?;
479- let cores = thread::available_parallelism().map_or(4, |n| n.get());
480- let mount = |sub: &str| format!("{}:/{sub}:Z", dir.join(sub).display());
481- cx.send(Event::Line(job, "creating Windows VM".into()));
482- check(
483- podman()
484- .args(["run", "-d", "--name", VM])
485- .args([
486- "-e",
487- "VERSION=11l",
488- "-e",
489- "RAM_SIZE=12G",
490- "-e",
491- "DISK_SIZE=96G",
492- ])
493- .args(["-e", &format!("CPU_CORES={cores}")])
494- .args([
495- "-e",
496- "USERNAME=yumush",
497- "-e",
498- "PASSWORD=yumush",
499- "-e",
500- "USER_PORTS=22",
501- ])
502- .args(["-e", VM_AUDIO])
503- .args([
504- "--device",
505- "/dev/kvm",
506- "--device",
507- "/dev/net/tun",
508- "--cap-add",
509- "NET_ADMIN",
510- ])
511- .args(["-p", "127.0.0.1:8006:8006", "-p", "127.0.0.1:3389:3389"])
512- .args(["-p", &format!("127.0.0.1:{PORT}:22")])
513- .args([
514- "-v",
515- &mount("storage"),
516- "-v",
517- &mount("oem"),
518- "-v",
519- &mount("shared"),
520- ])
521- .args(["--stop-timeout", "120", VM_IMAGE]),
522- )
523-}
524-
525-fn start_windows(job: Job, source: &Path, key: &Path, cx: &Cx) -> Result<(), String> {
526- if !podman_ok(&["container", "exists", VM]) {
527- create_windows(job, key, cx)?;
528- } else if !container_running(VM) {
529- check(podman().args(["start", VM]))?;
530- }
531- wait_ssh(job, key, cx)?;
532- while !ssh_ok_with(
533- key,
534- "if (Test-Path C:\\OEM\\finished.txt) { exit 0 } else { exit 1 }",
535- ) {
536- if cx.cancelled() {
537- return Err("cancelled".into());
538- }
539- cx.send(Event::Line(job, "installing build tools".into()));
540- thread::sleep(Duration::from_secs(15));
541- }
542- let rust = host_rust()?;
543- stream(
544- &mut ps(
545- key,
546- &format!(
547- "$env:Path += \";$env:USERPROFILE\\.cargo\\bin\"\nrustup toolchain install {rust} --profile minimal\nrustup default {rust}"
548- ),
549- ),
550- job,
551- cx,
552- )?;
553- check(
554- scp(key)
555- .arg(source.join(ARCHIVE))
556- .arg(format!("{TARGET}:release.tgz")),
557- )?;
558- stream(&mut ps(key, EXTRACT), job, cx)?;
559- cx.send(Event::Finished(job));
560- Ok(())
561-}
562-
563-fn build_windows(job: Job, level: Level, source: &Path, key: &Path, cx: &Cx) -> Result<(), String> {
564 let (name, cpu) = flags(level);380 let (name, cpu) = flags(level);
381+ let out = format!("release-{name}/{WINDOWS_TARGET}/release/client.exe");
565 let script = format!(382 let script = format!(
566- r#"$ErrorActionPreference = 'Continue'383+ "cd src
567-Set-Location release384+sha256sum -c --quiet {SHADERS_SUM}
568-$env:Path += ";$env:USERPROFILE\.cargo\bin"385+rm -f /build/target/{out}
569-$env:CARGO_TERM_PROGRESS_WHEN = 'always'; $env:CARGO_TERM_PROGRESS_WIDTH = '200'; $env:CARGO_TERM_COLOR = 'never'386+export XWIN_ACCEPT_LICENSE=1 XWIN_CACHE_DIR=/root/.cargo/xwin GPUI_SHADERS_BYTES=$PWD/{SHADERS}
570-@'387+export CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS='-C target-cpu={cpu}'
571-{toml}'@ | Set-Content -Encoding ascii level.toml388+cargo xwin build --release -p client --target {WINDOWS_TARGET} --target-dir /build/target/release-{name}"
572-Remove-Item -Force ..\target-release-{name}\release\client.exe -ErrorAction SilentlyContinue
573-cargo build --release -p client --target-dir ..\target-release-{name} --config level.toml
574-exit $LASTEXITCODE
575-"#,
576- toml = toml_text(cpu)
577 );389 );
578- stream(&mut ps(key, &script), job, cx)?;390+ stream(&mut in_linux(&script), job, cx)?;
579 let dest = source.join("dist").join(format!("x86_64_{name}-windows"));391 let dest = source.join("dist").join(format!("x86_64_{name}-windows"));
580- check(392+ fs::copy(linux_cache().join("target").join(&out), &dest).map_err(|e| e.to_string())?;
581- scp(key)
582- .arg(format!("{TARGET}:target-release-{name}/release/client.exe"))
583- .arg(&dest),
584- )?;
585 cx.send(Event::Built(job, dest));393 cx.send(Event::Built(job, dest));
586 cx.send(Event::Finished(job));394 cx.send(Event::Finished(job));
587 Ok(())395 Ok(())
588 }396 }
589 397
590-fn wait_ssh(job: Job, key: &Path, cx: &Cx) -> Result<(), String> {
591- let deadline = Instant::now() + SSH_WAIT;
592- while !ssh_ok(key) {
593- if cx.cancelled() {
594- return Err("cancelled".into());
595- }
596- if Instant::now() >= deadline {
597- return Err("ssh timeout".into());
598- }
599- cx.send(Event::Line(job, vm_status()));
600- thread::sleep(Duration::from_secs(5));
601- }
602- Ok(())
603-}
604-
605-fn vm_status() -> String {
606- let Ok(out) = podman().args(["logs", "--tail", "5", VM]).output() else {
607- return "waiting for ssh".into();
608- };
609- let text = String::from_utf8_lossy(&out.stdout) + String::from_utf8_lossy(&out.stderr);
610- text.lines()
611- .map(plain)
612- .rfind(|line| !line.is_empty() && !line.starts_with("Warning"))
613- .unwrap_or_else(|| "waiting for ssh".into())
614-}
615-
616-fn plain(line: &str) -> String {
617- let mut out = String::new();
618- let mut chars = line.chars();
619- while let Some(c) = chars.next() {
620- if c == '\u{1b}' {
621- chars.by_ref().find(|c| c.is_ascii_alphabetic());
622- } else if c != '❯' {
623- out.push(c);
624- }
625- }
626- out.trim().trim_end_matches("...").to_string()
627-}
628-
629-fn opts(key: &Path, port_flag: &str) -> Vec<String> {
630- let mut args = vec!["-i".to_string(), key.display().to_string()];
631- for option in [
632- "StrictHostKeyChecking=no",
633- "UserKnownHostsFile=/dev/null",
634- "ConnectTimeout=10",
635- "LogLevel=ERROR",
636- ] {
637- args.push("-o".into());
638- args.push(option.into());
639- }
640- args.push(port_flag.into());
641- args.push(PORT.into());
642- args
643-}
644-
645-fn ssh(key: &Path) -> Command {
646- let mut cmd = Command::new("ssh");
647- cmd.args(opts(key, "-p")).arg(TARGET);
648- cmd
649-}
650-
651-fn scp(key: &Path) -> Command {
652- let mut cmd = Command::new("scp");
653- cmd.arg("-q").args(opts(key, "-P"));
654- cmd
655-}
656-
657-fn ps(key: &Path, script: &str) -> Command {
658- let script = format!("$ProgressPreference = 'SilentlyContinue'\n{script}");
659- let bytes: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
660- let mut cmd = ssh(key);
661- cmd.args([
662- "powershell",
663- "-NoProfile",
664- "-NonInteractive",
665- "-EncodedCommand",
666- ])
667- .arg(base64(&bytes))
668- .stdout(Stdio::piped());
669- cmd
670-}
671-
672-fn ssh_ok(key: &Path) -> bool {
673- ssh_ok_with(key, "echo ok")
674-}
675-
676-fn ssh_ok_with(key: &Path, command: &str) -> bool {
677- ssh(key)
678- .arg(command)
679- .stdout(Stdio::null())
680- .stderr(Stdio::null())
681- .status()
682- .is_ok_and(|s| s.success())
683-}
684-
685 fn podman() -> Command {398 fn podman() -> Command {
686 let mut cmd = Command::new("podman");399 let mut cmd = Command::new("podman");
687 if let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR") {400 if let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR") {
@@ -796,22 +509,3 @@ fn progress(job: Job, text: &str) -> Option<Event> {
796 total: total.trim().parse().ok()?,509 total: total.trim().parse().ok()?,
797 })510 })
798 }511 }
799-
800-fn base64(bytes: &[u8]) -> String {
801- const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
802- let mut out = String::new();
803- for chunk in bytes.chunks(3) {
804- let n = chunk
805- .iter()
806- .enumerate()
807- .fold(0u32, |n, (i, &b)| n | (b as u32) << (16 - 8 * i));
808- for i in 0..4 {
809- if i <= chunk.len() {
810- out.push(TABLE[(n >> (18 - 6 * i)) as usize & 63] as char);
811- } else {
812- out.push('=');
813- }
814- }
815- }
816- out
817-}
crates/client/src/release/install.batdeleted+0 -10
@@ -1,10 +0,0 @@
1-@echo off
2-if exist C:\OEM\finished.txt exit /b
3-reg add HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce /v yumush /d C:\OEM\install.bat /f
4-powershell -NoProfile -ExecutionPolicy Bypass -Command "Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0; Set-Service sshd -StartupType Automatic; Start-Service sshd; New-NetFirewallRule -Name sshd -DisplayName sshd -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 -ErrorAction SilentlyContinue; Set-Content -Path C:\ProgramData\ssh\administrators_authorized_keys -Value '{key}'; icacls C:\ProgramData\ssh\administrators_authorized_keys /inheritance:r /grant 'Administrators:F' /grant 'SYSTEM:F'; New-ItemProperty -Path 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell -Value 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -PropertyType String -Force"
5-curl.exe -L -o C:\vs_BuildTools.exe https://aka.ms/vs/17/release/vs_BuildTools.exe
6-C:\vs_BuildTools.exe --quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended
7-curl.exe -L -o C:\rustup-init.exe https://win.rustup.rs/x86_64
8-C:\rustup-init.exe -y --default-toolchain none --profile minimal
9-reg delete HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce /v yumush /f
10-echo done > C:\OEM\finished.txt
crates/client/src/release/shaders.sha256added+1 -0
@@ -0,0 +1 @@
1+fbfce2de66d9f28316e0ee91ea4d7af73055540d242804bab613ef2daa8d1588 vendor/gpui-pre-windows/src/shaders.hlsl
crates/client/src/release/shaders_bytes.rsadded+11805 -0

Diff too large; view file

@@ -0,0 +1,11805 @@
1+const QUAD_VERTEX_BYTES: &[u8] = &[
2+ 68, 88, 66, 67, 190, 191,
3+ 107, 161, 88, 163, 204, 45,
4+ 179, 48, 133, 71, 171, 61,
5+ 215, 132, 1, 0, 0, 0,
6+ 204, 32, 0, 0, 6, 0,
7+ 0, 0, 56, 0, 0, 0,
8+ 88, 6, 0, 0, 180, 6,
9+ 0, 0, 112, 7, 0, 0,
10+ 64, 32, 0, 0, 80, 32,
11+ 0, 0, 82, 68, 69, 70,
12+ 24, 6, 0, 0, 3, 0,
13+ 0, 0, 156, 0, 0, 0,
14+ 3, 0, 0, 0, 28, 0,
15+ 0, 0, 1, 4, 254, 255,
16+ 0, 129, 0, 0, 240, 5,
17+ 0, 0, 124, 0, 0, 0,
18+ 5, 0, 0, 0, 6, 0,
19+ 0, 0, 1, 0, 0, 0,
20+ 160, 0, 0, 0, 1, 0,
21+ 0, 0, 1, 0, 0, 0,
22+ 1, 0, 0, 0, 130, 0,
23+ 0, 0, 0, 0, 0, 0,
24+ 0, 0, 0, 0, 0, 0,
25+ 0, 0, 0, 0, 0, 0,
26+ 0, 0, 0, 0, 1, 0,
27+ 0, 0, 1, 0, 0, 0,
28+ 143, 0, 0, 0, 0, 0,
29+ 0, 0, 0, 0, 0, 0,
30+ 0, 0, 0, 0, 0, 0,
31+ 0, 0, 1, 0, 0, 0,
32+ 1, 0, 0, 0, 1, 0,
33+ 0, 0, 113, 117, 97, 100,
34+ 115, 0, 71, 108, 111, 98,
35+ 97, 108, 80, 97, 114, 97,
36+ 109, 115, 0, 66, 97, 116,
37+ 99, 104, 80, 97, 114, 97,
38+ 109, 115, 0, 171, 130, 0,
39+ 0, 0, 7, 0, 0, 0,
40+ 228, 0, 0, 0, 48, 0,
41+ 0, 0, 0, 0, 0, 0,
42+ 0, 0, 0, 0, 143, 0,
43+ 0, 0, 2, 0, 0, 0,
44+ 92, 2, 0, 0, 16, 0,
45+ 0, 0, 0, 0, 0, 0,
46+ 0, 0, 0, 0, 124, 0,
47+ 0, 0, 1, 0, 0, 0,
48+ 184, 2, 0, 0, 160, 0,
49+ 0, 0, 0, 0, 0, 0,
50+ 3, 0, 0, 0, 140, 1,
51+ 0, 0, 0, 0, 0, 0,
52+ 16, 0, 0, 0, 0, 0,
53+ 0, 0, 156, 1, 0, 0,
54+ 0, 0, 0, 0, 172, 1,
55+ 0, 0, 16, 0, 0, 0,
56+ 8, 0, 0, 0, 2, 0,
57+ 0, 0, 196, 1, 0, 0,
58+ 0, 0, 0, 0, 212, 1,
59+ 0, 0, 24, 0, 0, 0,
60+ 4, 0, 0, 0, 0, 0,
61+ 0, 0, 240, 1, 0, 0,
62+ 0, 0, 0, 0, 0, 2,
63+ 0, 0, 28, 0, 0, 0,
64+ 4, 0, 0, 0, 0, 0,
65+ 0, 0, 240, 1, 0, 0,
66+ 0, 0, 0, 0, 27, 2,
67+ 0, 0, 32, 0, 0, 0,
68+ 4, 0, 0, 0, 0, 0,
69+ 0, 0, 36, 2, 0, 0,
70+ 0, 0, 0, 0, 52, 2,
71+ 0, 0, 36, 0, 0, 0,
72+ 4, 0, 0, 0, 2, 0,
73+ 0, 0, 240, 1, 0, 0,
74+ 0, 0, 0, 0, 64, 2,
75+ 0, 0, 40, 0, 0, 0,
76+ 8, 0, 0, 0, 0, 0,
77+ 0, 0, 76, 2, 0, 0,
78+ 0, 0, 0, 0, 103, 97,
79+ 109, 109, 97, 95, 114, 97,
80+ 116, 105, 111, 115, 0, 171,
81+ 171, 171, 1, 0, 3, 0,
82+ 1, 0, 4, 0, 0, 0,
83+ 0, 0, 0, 0, 0, 0,
84+ 103, 108, 111, 98, 97, 108,
85+ 95, 118, 105, 101, 119, 112,
86+ 111, 114, 116, 95, 115, 105,
87+ 122, 101, 0, 171, 171, 171,
88+ 1, 0, 3, 0, 1, 0,
89+ 2, 0, 0, 0, 0, 0,
90+ 0, 0, 0, 0, 103, 114,
91+ 97, 121, 115, 99, 97, 108,
92+ 101, 95, 101, 110, 104, 97,
93+ 110, 99, 101, 100, 95, 99,
94+ 111, 110, 116, 114, 97, 115,
95+ 116, 0, 0, 0, 3, 0,
96+ 1, 0, 1, 0, 0, 0,
97+ 0, 0, 0, 0, 0, 0,
98+ 115, 117, 98, 112, 105, 120,
99+ 101, 108, 95, 101, 110, 104,
100+ 97, 110, 99, 101, 100, 95,
101+ 99, 111, 110, 116, 114, 97,
102+ 115, 116, 0, 105, 115, 95,
103+ 98, 103, 114, 0, 171, 171,
104+ 0, 0, 19, 0, 1, 0,
105+ 1, 0, 0, 0, 0, 0,
106+ 0, 0, 0, 0, 100, 101,
107+ 112, 116, 104, 95, 115, 99,
108+ 97, 108, 101, 0, 103, 108,
109+ 111, 98, 97, 108, 95, 112,
110+ 97, 100, 0, 171, 1, 0,
111+ 19, 0, 1, 0, 2, 0,
112+ 0, 0, 0, 0, 0, 0,
113+ 0, 0, 140, 2, 0, 0,
114+ 0, 0, 0, 0, 4, 0,
115+ 0, 0, 2, 0, 0, 0,
116+ 36, 2, 0, 0, 0, 0,
117+ 0, 0, 158, 2, 0, 0,
118+ 4, 0, 0, 0, 12, 0,
119+ 0, 0, 0, 0, 0, 0,
120+ 168, 2, 0, 0, 0, 0,
121+ 0, 0, 98, 97, 116, 99,
122+ 104, 95, 115, 116, 97, 114,
123+ 116, 95, 105, 110, 100, 101,
124+ 120, 0, 98, 97, 116, 99,
125+ 104, 95, 112, 97, 100, 0,
126+ 1, 0, 19, 0, 1, 0,
127+ 3, 0, 0, 0, 0, 0,
128+ 0, 0, 0, 0, 208, 2,
129+ 0, 0, 0, 0, 0, 0,
130+ 160, 0, 0, 0, 2, 0,
131+ 0, 0, 224, 5, 0, 0,
132+ 0, 0, 0, 0, 36, 69,
133+ 108, 101, 109, 101, 110, 116,
134+ 0, 111, 114, 100, 101, 114,
135+ 0, 171, 0, 0, 19, 0,
136+ 1, 0, 1, 0, 0, 0,
137+ 0, 0, 0, 0, 0, 0,
138+ 98, 111, 114, 100, 101, 114,
139+ 95, 115, 116, 121, 108, 101,
140+ 0, 98, 111, 117, 110, 100,
141+ 115, 0, 111, 114, 105, 103,
142+ 105, 110, 0, 171, 1, 0,
143+ 3, 0, 1, 0, 2, 0,
144+ 0, 0, 0, 0, 0, 0,
145+ 0, 0, 115, 105, 122, 101,
146+ 0, 171, 171, 171, 4, 3,
147+ 0, 0, 12, 3, 0, 0,
148+ 0, 0, 0, 0, 28, 3,
149+ 0, 0, 12, 3, 0, 0,
150+ 8, 0, 0, 0, 5, 0,
151+ 0, 0, 1, 0, 4, 0,
152+ 0, 0, 2, 0, 36, 3,
153+ 0, 0, 99, 111, 110, 116,
154+ 101, 110, 116, 95, 109, 97,
155+ 115, 107, 0, 98, 97, 99,
156+ 107, 103, 114, 111, 117, 110,
157+ 100, 0, 116, 97, 103, 0,
158+ 99, 111, 108, 111, 114, 95,
159+ 115, 112, 97, 99, 101, 0,
160+ 115, 111, 108, 105, 100, 0,
161+ 104, 0, 0, 0, 3, 0,
162+ 1, 0, 1, 0, 0, 0,
163+ 0, 0, 0, 0, 0, 0,
164+ 115, 0, 108, 0, 97, 0,
165+ 171, 171, 122, 3, 0, 0,
166+ 124, 3, 0, 0, 0, 0,
167+ 0, 0, 140, 3, 0, 0,
168+ 124, 3, 0, 0, 4, 0,
169+ 0, 0, 142, 3, 0, 0,
170+ 124, 3, 0, 0, 8, 0,
171+ 0, 0, 144, 3, 0, 0,
172+ 124, 3, 0, 0, 12, 0,
173+ 0, 0, 5, 0, 0, 0,
174+ 1, 0, 4, 0, 0, 0,
175+ 4, 0, 148, 3, 0, 0,
176+ 103, 114, 97, 100, 105, 101,
177+ 110, 116, 95, 97, 110, 103,
178+ 108, 101, 95, 111, 114, 95,
179+ 112, 97, 116, 116, 101, 114,
180+ 110, 95, 104, 101, 105, 103,
181+ 104, 116, 0, 99, 111, 108,
182+ 111, 114, 115, 0, 99, 111,
183+ 108, 111, 114, 0, 112, 101,
184+ 114, 99, 101, 110, 116, 97,
185+ 103, 101, 0, 171, 171, 171,
186+ 252, 3, 0, 0, 196, 3,
187+ 0, 0, 0, 0, 0, 0,
188+ 2, 4, 0, 0, 124, 3,
189+ 0, 0, 16, 0, 0, 0,
190+ 5, 0, 0, 0, 1, 0,
191+ 5, 0, 2, 0, 2, 0,
192+ 16, 4, 0, 0, 112, 97,
193+ 100, 0, 100, 3, 0, 0,
194+ 224, 2, 0, 0, 0, 0,
195+ 0, 0, 104, 3, 0, 0,
196+ 224, 2, 0, 0, 4, 0,
197+ 0, 0, 116, 3, 0, 0,
198+ 196, 3, 0, 0, 8, 0,
199+ 0, 0, 212, 3, 0, 0,
200+ 124, 3, 0, 0, 24, 0,
201+ 0, 0, 245, 3, 0, 0,
202+ 40, 4, 0, 0, 28, 0,
203+ 0, 0, 56, 4, 0, 0,
204+ 224, 2, 0, 0, 68, 0,
205+ 0, 0, 5, 0, 0, 0,
206+ 1, 0, 18, 0, 0, 0,
207+ 6, 0, 60, 4, 0, 0,
208+ 98, 111, 114, 100, 101, 114,
209+ 95, 99, 111, 108, 111, 114,
210+ 0, 99, 111, 114, 110, 101,
211+ 114, 95, 114, 97, 100, 105,
212+ 105, 0, 116, 111, 112, 95,
213+ 108, 101, 102, 116, 0, 116,
214+ 111, 112, 95, 114, 105, 103,
215+ 104, 116, 0, 98, 111, 116,
216+ 116, 111, 109, 95, 114, 105,
217+ 103, 104, 116, 0, 98, 111,
218+ 116, 116, 111, 109, 95, 108,
219+ 101, 102, 116, 0, 171, 171,
220+ 174, 4, 0, 0, 124, 3,
221+ 0, 0, 0, 0, 0, 0,
222+ 183, 4, 0, 0, 124, 3,
223+ 0, 0, 4, 0, 0, 0,
224+ 193, 4, 0, 0, 124, 3,
225+ 0, 0, 8, 0, 0, 0,
226+ 206, 4, 0, 0, 124, 3,
227+ 0, 0, 12, 0, 0, 0,
228+ 5, 0, 0, 0, 1, 0,
229+ 4, 0, 0, 0, 4, 0,
230+ 220, 4, 0, 0, 98, 111,
231+ 114, 100, 101, 114, 95, 119,
232+ 105, 100, 116, 104, 115, 0,
233+ 116, 111, 112, 0, 114, 105,
234+ 103, 104, 116, 0, 98, 111,
235+ 116, 116, 111, 109, 0, 108,
236+ 101, 102, 116, 0, 42, 5,
237+ 0, 0, 124, 3, 0, 0,
238+ 0, 0, 0, 0, 46, 5,
239+ 0, 0, 124, 3, 0, 0,
240+ 4, 0, 0, 0, 52, 5,
241+ 0, 0, 124, 3, 0, 0,
242+ 8, 0, 0, 0, 59, 5,
243+ 0, 0, 124, 3, 0, 0,
244+ 12, 0, 0, 0, 5, 0,
245+ 0, 0, 1, 0, 4, 0,
246+ 0, 0, 4, 0, 64, 5,
247+ 0, 0, 217, 2, 0, 0,
248+ 224, 2, 0, 0, 0, 0,
249+ 0, 0, 240, 2, 0, 0,
250+ 224, 2, 0, 0, 4, 0,
251+ 0, 0, 253, 2, 0, 0,
252+ 60, 3, 0, 0, 8, 0,
253+ 0, 0, 76, 3, 0, 0,
254+ 60, 3, 0, 0, 24, 0,
255+ 0, 0, 89, 3, 0, 0,
256+ 132, 4, 0, 0, 40, 0,
257+ 0, 0, 148, 4, 0, 0,
258+ 196, 3, 0, 0, 112, 0,
259+ 0, 0, 161, 4, 0, 0,
260+ 12, 5, 0, 0, 128, 0,
261+ 0, 0, 28, 5, 0, 0,
262+ 112, 5, 0, 0, 144, 0,
263+ 0, 0, 5, 0, 0, 0,
264+ 1, 0, 40, 0, 0, 0,
265+ 8, 0, 128, 5, 0, 0,
266+ 77, 105, 99, 114, 111, 115,
267+ 111, 102, 116, 32, 40, 82,
268+ 41, 32, 72, 76, 83, 76,
269+ 32, 83, 104, 97, 100, 101,
270+ 114, 32, 67, 111, 109, 112,
271+ 105, 108, 101, 114, 32, 49,
272+ 48, 46, 49, 0, 73, 83,
273+ 71, 78, 84, 0, 0, 0,
274+ 2, 0, 0, 0, 8, 0,
275+ 0, 0, 56, 0, 0, 0,
276+ 0, 0, 0, 0, 6, 0,
277+ 0, 0, 1, 0, 0, 0,
278+ 0, 0, 0, 0, 1, 1,
279+ 0, 0, 68, 0, 0, 0,
280+ 0, 0, 0, 0, 8, 0,
281+ 0, 0, 1, 0, 0, 0,
282+ 1, 0, 0, 0, 1, 1,
283+ 0, 0, 83, 86, 95, 86,
284+ 101, 114, 116, 101, 120, 73,
285+ 68, 0, 83, 86, 95, 73,
286+ 110, 115, 116, 97, 110, 99,
287+ 101, 73, 68, 0, 171, 171,
288+ 79, 83, 71, 78, 180, 0,
289+ 0, 0, 6, 0, 0, 0,
290+ 8, 0, 0, 0, 152, 0,
291+ 0, 0, 0, 0, 0, 0,
292+ 0, 0, 0, 0, 1, 0,
293+ 0, 0, 0, 0, 0, 0,
294+ 1, 14, 0, 0, 152, 0,
295+ 0, 0, 2, 0, 0, 0,
296+ 0, 0, 0, 0, 1, 0,
297+ 0, 0, 0, 0, 0, 0,
298+ 2, 13, 0, 0, 161, 0,
299+ 0, 0, 0, 0, 0, 0,
300+ 1, 0, 0, 0, 3, 0,
301+ 0, 0, 1, 0, 0, 0,
302+ 15, 0, 0, 0, 173, 0,
303+ 0, 0, 0, 0, 0, 0,
304+ 0, 0, 0, 0, 3, 0,
305+ 0, 0, 2, 0, 0, 0,
306+ 15, 0, 0, 0, 173, 0,
307+ 0, 0, 1, 0, 0, 0,
308+ 0, 0, 0, 0, 3, 0,
309+ 0, 0, 3, 0, 0, 0,
310+ 15, 0, 0, 0, 173, 0,
311+ 0, 0, 2, 0, 0, 0,
312+ 0, 0, 0, 0, 3, 0,
313+ 0, 0, 4, 0, 0, 0,
314+ 15, 0, 0, 0, 84, 69,
315+ 88, 67, 79, 79, 82, 68,
316+ 0, 83, 86, 95, 80, 111,
317+ 115, 105, 116, 105, 111, 110,
318+ 0, 67, 79, 76, 79, 82,
319+ 0, 171, 83, 72, 69, 88,
320+ 200, 24, 0, 0, 65, 0,
321+ 1, 0, 50, 6, 0, 0,
322+ 106, 72, 0, 1, 89, 0,
323+ 0, 4, 70, 142, 32, 0,
324+ 0, 0, 0, 0, 3, 0,
325+ 0, 0, 89, 0, 0, 4,
326+ 70, 142, 32, 0, 1, 0,
327+ 0, 0, 1, 0, 0, 0,
328+ 162, 0, 0, 4, 0, 112,
329+ 16, 0, 1, 0, 0, 0,
330+ 160, 0, 0, 0, 96, 0,
331+ 0, 4, 18, 16, 16, 0,
332+ 0, 0, 0, 0, 6, 0,
333+ 0, 0, 96, 0, 0, 4,
334+ 18, 16, 16, 0, 1, 0,
335+ 0, 0, 8, 0, 0, 0,
336+ 101, 0, 0, 3, 18, 32,
337+ 16, 0, 0, 0, 0, 0,
338+ 101, 0, 0, 3, 34, 32,
339+ 16, 0, 0, 0, 0, 0,
340+ 103, 0, 0, 4, 242, 32,
341+ 16, 0, 1, 0, 0, 0,
342+ 1, 0, 0, 0, 101, 0,
343+ 0, 3, 242, 32, 16, 0,
344+ 2, 0, 0, 0, 101, 0,
345+ 0, 3, 242, 32, 16, 0,
346+ 3, 0, 0, 0, 101, 0,
347+ 0, 3, 242, 32, 16, 0,
348+ 4, 0, 0, 0, 104, 0,
349+ 0, 2, 8, 0, 0, 0,
350+ 30, 0, 0, 8, 18, 0,
351+ 16, 0, 0, 0, 0, 0,
352+ 10, 16, 16, 0, 1, 0,
353+ 0, 0, 10, 128, 32, 0,
354+ 1, 0, 0, 0, 0, 0,
355+ 0, 0, 167, 0, 0, 9,
356+ 242, 0, 16, 0, 1, 0,
357+ 0, 0, 10, 0, 16, 0,
358+ 0, 0, 0, 0, 1, 64,
359+ 0, 0, 40, 0, 0, 0,
360+ 70, 126, 16, 0, 1, 0,
361+ 0, 0, 167, 0, 0, 9,
362+ 98, 0, 16, 0, 0, 0,
363+ 0, 0, 10, 0, 16, 0,
364+ 0, 0, 0, 0, 1, 64,
365+ 0, 0, 56, 0, 0, 0,
366+ 6, 113, 16, 0, 1, 0,
367+ 0, 0, 167, 0, 0, 9,
368+ 242, 0, 16, 0, 2, 0,
369+ 0, 0, 10, 0, 16, 0,
370+ 0, 0, 0, 0, 1, 64,
371+ 0, 0, 128, 0, 0, 0,
372+ 70, 126, 16, 0, 1, 0,
373+ 0, 0, 167, 0, 0, 9,
374+ 242, 0, 16, 0, 3, 0,
375+ 0, 0, 10, 0, 16, 0,
376+ 0, 0, 0, 0, 1, 64,
377+ 0, 0, 144, 0, 0, 0,
378+ 70, 126, 16, 0, 1, 0,
379+ 0, 0, 32, 0, 0, 7,
380+ 130, 0, 16, 0, 0, 0,
381+ 0, 0, 10, 0, 16, 0,
382+ 1, 0, 0, 0, 1, 64,
383+ 0, 0, 0, 0, 0, 0,
384+ 29, 0, 0, 7, 18, 0,
385+ 16, 0, 4, 0, 0, 0,
386+ 42, 0, 16, 0, 0, 0,
387+ 0, 0, 1, 64, 0, 0,
388+ 0, 0, 128, 63, 1, 0,
389+ 0, 7, 18, 0, 16, 0,
390+ 4, 0, 0, 0, 58, 0,
391+ 16, 0, 0, 0, 0, 0,
392+ 10, 0, 16, 0, 4, 0,
393+ 0, 0, 57, 0, 0, 10,
394+ 242, 0, 16, 0, 2, 0,
395+ 0, 0, 70, 14, 16, 0,
396+ 2, 0, 0, 0, 2, 64,
397+ 0, 0, 0, 0, 0, 0,
398+ 0, 0, 0, 0, 0, 0,
399+ 0, 0, 0, 0, 0, 0,
400+ 60, 0, 0, 7, 18, 0,
401+ 16, 0, 2, 0, 0, 0,
402+ 26, 0, 16, 0, 2, 0,
403+ 0, 0, 10, 0, 16, 0,
404+ 2, 0, 0, 0, 60, 0,
405+ 0, 7, 18, 0, 16, 0,
406+ 2, 0, 0, 0, 42, 0,
407+ 16, 0, 2, 0, 0, 0,
408+ 10, 0, 16, 0, 2, 0,
409+ 0, 0, 60, 0, 0, 7,
410+ 18, 0, 16, 0, 2, 0,
411+ 0, 0, 58, 0, 16, 0,
412+ 2, 0, 0, 0, 10, 0,
413+ 16, 0, 2, 0, 0, 0,
414+ 59, 0, 0, 5, 34, 0,
415+ 16, 0, 2, 0, 0, 0,
416+ 10, 0, 16, 0, 2, 0,
417+ 0, 0, 1, 0, 0, 7,
418+ 34, 0, 16, 0, 2, 0,
419+ 0, 0, 26, 0, 16, 0,
420+ 2, 0, 0, 0, 10, 0,
421+ 16, 0, 4, 0, 0, 0,
422+ 57, 0, 0, 10, 242, 0,
423+ 16, 0, 3, 0, 0, 0,
424+ 70, 14, 16, 0, 3, 0,
425+ 0, 0, 2, 64, 0, 0,
426+ 0, 0, 0, 0, 0, 0,
427+ 0, 0, 0, 0, 0, 0,
428+ 0, 0, 0, 0, 60, 0,
429+ 0, 7, 66, 0, 16, 0,
430+ 2, 0, 0, 0, 26, 0,
431+ 16, 0, 3, 0, 0, 0,
432+ 10, 0, 16, 0, 3, 0,
433+ 0, 0, 60, 0, 0, 7,
434+ 66, 0, 16, 0, 2, 0,
435+ 0, 0, 42, 0, 16, 0,
436+ 3, 0, 0, 0, 42, 0,
437+ 16, 0, 2, 0, 0, 0,
438+ 60, 0, 0, 7, 66, 0,
439+ 16, 0, 2, 0, 0, 0,
440+ 58, 0, 16, 0, 3, 0,
441+ 0, 0, 42, 0, 16, 0,
442+ 2, 0, 0, 0, 59, 0,
443+ 0, 5, 130, 0, 16, 0,
444+ 2, 0, 0, 0, 42, 0,
445+ 16, 0, 2, 0, 0, 0,
446+ 1, 0, 0, 7, 34, 0,
447+ 16, 0, 2, 0, 0, 0,
448+ 58, 0, 16, 0, 2, 0,
449+ 0, 0, 26, 0, 16, 0,
450+ 2, 0, 0, 0, 31, 0,
451+ 4, 3, 26, 0, 16, 0,
452+ 2, 0, 0, 0, 54, 0,
453+ 0, 8, 242, 32, 16, 0,
454+ 1, 0, 0, 0, 2, 64,
455+ 0, 0, 0, 0, 0, 0,
456+ 0, 0, 0, 0, 0, 0,
457+ 0, 0, 0, 0, 128, 63,
458+ 54, 0, 0, 8, 242, 32,
459+ 16, 0, 2, 0, 0, 0,
460+ 2, 64, 0, 0, 0, 0,
461+ 0, 0, 0, 0, 0, 0,
462+ 0, 0, 0, 0, 0, 0,
463+ 0, 0, 54, 0, 0, 8,
464+ 242, 32, 16, 0, 3, 0,
465+ 0, 0, 2, 64, 0, 0,
466+ 0, 0, 0, 0, 0, 0,
467+ 0, 0, 0, 0, 0, 0,
468+ 0, 0, 0, 0, 54, 0,
469+ 0, 8, 242, 32, 16, 0,
470+ 4, 0, 0, 0, 2, 64,
471+ 0, 0, 0, 0, 0, 0,
472+ 0, 0, 0, 0, 0, 0,
473+ 0, 0, 0, 0, 0, 0,
474+ 54, 0, 0, 8, 50, 32,
475+ 16, 0, 0, 0, 0, 0,
476+ 2, 64, 0, 0, 0, 0,
477+ 0, 0, 0, 0, 0, 0,
478+ 0, 0, 0, 0, 0, 0,
479+ 0, 0, 62, 0, 0, 1,
480+ 21, 0, 0, 1, 167, 0,
481+ 0, 9, 242, 0, 16, 0,
482+ 3, 0, 0, 0, 10, 0,
483+ 16, 0, 0, 0, 0, 0,
484+ 1, 64, 0, 0, 8, 0,
485+ 0, 0, 70, 126, 16, 0,
486+ 1, 0, 0, 0, 167, 0,
487+ 0, 9, 242, 0, 16, 0,
488+ 4, 0, 0, 0, 10, 0,
489+ 16, 0, 0, 0, 0, 0,
490+ 1, 64, 0, 0, 24, 0,
491+ 0, 0, 70, 126, 16, 0,
492+ 1, 0, 0, 0, 167, 0,
493+ 0, 9, 242, 0, 16, 0,
494+ 5, 0, 0, 0, 10, 0,
495+ 16, 0, 0, 0, 0, 0,
496+ 1, 64, 0, 0, 112, 0,
497+ 0, 0, 70, 126, 16, 0,
498+ 1, 0, 0, 0, 1, 0,
499+ 0, 10, 162, 0, 16, 0,
500+ 2, 0, 0, 0, 6, 16,
501+ 16, 0, 0, 0, 0, 0,
502+ 2, 64, 0, 0, 0, 0,
503+ 0, 0, 1, 0, 0, 0,
504+ 0, 0, 0, 0, 2, 0,
505+ 0, 0, 86, 0, 0, 5,
506+ 50, 0, 16, 0, 6, 0,
507+ 0, 0, 214, 5, 16, 0,
508+ 2, 0, 0, 0, 52, 0,
509+ 0, 7, 162, 0, 16, 0,
510+ 2, 0, 0, 0, 6, 4,
511+ 16, 0, 3, 0, 0, 0,
512+ 6, 4, 16, 0, 4, 0,
513+ 0, 0, 0, 0, 0, 7,
514+ 50, 0, 16, 0, 3, 0,
515+ 0, 0, 230, 10, 16, 0,
516+ 3, 0, 0, 0, 70, 0,
517+ 16, 0, 3, 0, 0, 0,
518+ 0, 0, 0, 7, 194, 0,
519+ 16, 0, 3, 0, 0, 0,
520+ 166, 14, 16, 0, 4, 0,
521+ 0, 0, 6, 4, 16, 0,
522+ 4, 0, 0, 0, 51, 0,
523+ 0, 7, 50, 0, 16, 0,
524+ 3, 0, 0, 0, 230, 10,
525+ 16, 0, 3, 0, 0, 0,
526+ 70, 0, 16, 0, 3, 0,
527+ 0, 0, 0, 0, 0, 8,
528+ 50, 0, 16, 0, 3, 0,
529+ 0, 0, 214, 5, 16, 128,
530+ 65, 0, 0, 0, 2, 0,
531+ 0, 0, 70, 0, 16, 0,
532+ 3, 0, 0, 0, 52, 0,
533+ 0, 10, 50, 0, 16, 0,
534+ 3, 0, 0, 0, 70, 0,
535+ 16, 0, 3, 0, 0, 0,
536+ 2, 64, 0, 0, 0, 0,
537+ 0, 0, 0, 0, 0, 0,
538+ 0, 0, 0, 0, 0, 0,
539+ 0, 0, 56, 0, 0, 7,
540+ 66, 0, 16, 0, 6, 0,
541+ 0, 0, 26, 0, 16, 0,
542+ 6, 0, 0, 0, 1, 64,
543+ 0, 0, 0, 0, 0, 63,
544+ 50, 0, 0, 9, 162, 0,
545+ 16, 0, 2, 0, 0, 0,
546+ 6, 8, 16, 0, 6, 0,
547+ 0, 0, 6, 4, 16, 0,
548+ 3, 0, 0, 0, 86, 13,
549+ 16, 0, 2, 0, 0, 0,
550+ 14, 0, 0, 8, 162, 0,
551+ 16, 0, 2, 0, 0, 0,
552+ 86, 13, 16, 0, 2, 0,
553+ 0, 0, 6, 132, 32, 0,
554+ 0, 0, 0, 0, 1, 0,
555+ 0, 0, 50, 0, 0, 15,
556+ 50, 32, 16, 0, 1, 0,
557+ 0, 0, 214, 5, 16, 0,
558+ 2, 0, 0, 0, 2, 64,
559+ 0, 0, 0, 0, 0, 64,
560+ 0, 0, 0, 192, 0, 0,
561+ 0, 0, 0, 0, 0, 0,
562+ 2, 64, 0, 0, 0, 0,
563+ 128, 191, 0, 0, 128, 63,
564+ 0, 0, 0, 0, 0, 0,
565+ 0, 0, 50, 0, 0, 9,
566+ 34, 0, 16, 0, 2, 0,
567+ 0, 0, 42, 0, 16, 0,
568+ 5, 0, 0, 0, 1, 64,
569+ 0, 0, 0, 0, 0, 64,
570+ 1, 64, 0, 0, 0, 0,
571+ 128, 191, 0, 0, 0, 8,
572+ 34, 0, 16, 0, 2, 0,
573+ 0, 0, 26, 0, 16, 128,
574+ 193, 0, 0, 0, 2, 0,
575+ 0, 0, 1, 64, 0, 0,
576+ 0, 0, 128, 63, 56, 0,
577+ 0, 7, 18, 0, 16, 0,
578+ 3, 0, 0, 0, 26, 0,
579+ 16, 0, 5, 0, 0, 0,
580+ 26, 0, 16, 0, 2, 0,
581+ 0, 0, 56, 0, 0, 7,
582+ 34, 0, 16, 0, 2, 0,
583+ 0, 0, 10, 0, 16, 0,
584+ 5, 0, 0, 0, 1, 64,
585+ 0, 0, 0, 0, 64, 64,
586+ 29, 0, 0, 8, 130, 0,
587+ 16, 0, 2, 0, 0, 0,
588+ 26, 0, 16, 0, 2, 0,
589+ 0, 0, 26, 0, 16, 128,
590+ 65, 0, 0, 0, 2, 0,
591+ 0, 0, 26, 0, 0, 6,
592+ 34, 0, 16, 0, 2, 0,
593+ 0, 0, 26, 0, 16, 128,
594+ 129, 0, 0, 0, 2, 0,
595+ 0, 0, 55, 0, 0, 10,
596+ 34, 0, 16, 0, 2, 0,
597+ 0, 0, 58, 0, 16, 0,
598+ 2, 0, 0, 0, 26, 0,
599+ 16, 0, 2, 0, 0, 0,
600+ 26, 0, 16, 128, 65, 0,
601+ 0, 0, 2, 0, 0, 0,
602+ 50, 0, 0, 9, 34, 0,
603+ 16, 0, 2, 0, 0, 0,
604+ 26, 0, 16, 0, 2, 0,
605+ 0, 0, 1, 64, 0, 0,
606+ 0, 0, 0, 64, 1, 64,
607+ 0, 0, 0, 0, 128, 191,
608+ 0, 0, 0, 8, 34, 0,
609+ 16, 0, 2, 0, 0, 0,
610+ 26, 0, 16, 128, 193, 0,
611+ 0, 0, 2, 0, 0, 0,
612+ 1, 64, 0, 0, 0, 0,
613+ 128, 63, 56, 0, 0, 7,
614+ 34, 0, 16, 0, 3, 0,
615+ 0, 0, 26, 0, 16, 0,
616+ 2, 0, 0, 0, 10, 0,
617+ 16, 0, 3, 0, 0, 0,
618+ 50, 0, 0, 10, 34, 0,
619+ 16, 0, 2, 0, 0, 0,
620+ 10, 0, 16, 128, 65, 0,
621+ 0, 0, 3, 0, 0, 0,
622+ 1, 64, 0, 0, 0, 0,
623+ 0, 63, 42, 0, 16, 0,
624+ 5, 0, 0, 0, 29, 0,
625+ 0, 10, 242, 0, 16, 0,
626+ 4, 0, 0, 0, 6, 0,
627+ 16, 0, 5, 0, 0, 0,
628+ 2, 64, 0, 0, 0, 0,
629+ 0, 0, 171, 170, 42, 62,
630+ 171, 170, 170, 62, 0, 0,
631+ 0, 63, 49, 0, 0, 10,
632+ 242, 0, 16, 0, 6, 0,
633+ 0, 0, 6, 0, 16, 0,
634+ 5, 0, 0, 0, 2, 64,
635+ 0, 0, 171, 170, 42, 62,
636+ 171, 170, 170, 62, 0, 0,
637+ 0, 63, 171, 170, 42, 63,
638+ 1, 0, 0, 7, 242, 0,
639+ 16, 0, 4, 0, 0, 0,
640+ 70, 14, 16, 0, 4, 0,
641+ 0, 0, 70, 14, 16, 0,
642+ 6, 0, 0, 0, 29, 0,
643+ 0, 7, 130, 0, 16, 0,
644+ 2, 0, 0, 0, 10, 0,
645+ 16, 0, 5, 0, 0, 0,
646+ 1, 64, 0, 0, 171, 170,
647+ 42, 63, 49, 0, 0, 7,
648+ 130, 0, 16, 0, 3, 0,
649+ 0, 0, 10, 0, 16, 0,
650+ 5, 0, 0, 0, 1, 64,
651+ 0, 0, 85, 85, 85, 63,
652+ 1, 0, 0, 7, 130, 0,
653+ 16, 0, 2, 0, 0, 0,
654+ 58, 0, 16, 0, 2, 0,
655+ 0, 0, 58, 0, 16, 0,
656+ 3, 0, 0, 0, 54, 0,
657+ 0, 5, 66, 0, 16, 0,
658+ 3, 0, 0, 0, 1, 64,
659+ 0, 0, 0, 0, 0, 0,
660+ 55, 0, 0, 9, 114, 0,
661+ 16, 0, 5, 0, 0, 0,
662+ 246, 15, 16, 0, 2, 0,
663+ 0, 0, 150, 4, 16, 0,
664+ 3, 0, 0, 0, 134, 1,
665+ 16, 0, 3, 0, 0, 0,
666+ 55, 0, 0, 9, 114, 0,
667+ 16, 0, 5, 0, 0, 0,
668+ 246, 15, 16, 0, 4, 0,
669+ 0, 0, 102, 8, 16, 0,
670+ 3, 0, 0, 0, 70, 2,
671+ 16, 0, 5, 0, 0, 0,
672+ 55, 0, 0, 9, 114, 0,
673+ 16, 0, 5, 0, 0, 0,
674+ 166, 10, 16, 0, 4, 0,
675+ 0, 0, 38, 9, 16, 0,
676+ 3, 0, 0, 0, 70, 2,
677+ 16, 0, 5, 0, 0, 0,
678+ 55, 0, 0, 9, 226, 0,
679+ 16, 0, 4, 0, 0, 0,
680+ 86, 5, 16, 0, 4, 0,
681+ 0, 0, 86, 8, 16, 0,
682+ 3, 0, 0, 0, 6, 9,
683+ 16, 0, 5, 0, 0, 0,
684+ 55, 0, 0, 9, 114, 0,
685+ 16, 0, 3, 0, 0, 0,
686+ 6, 0, 16, 0, 4, 0,
687+ 0, 0, 70, 2, 16, 0,
688+ 3, 0, 0, 0, 150, 7,
689+ 16, 0, 4, 0, 0, 0,
690+ 0, 0, 0, 7, 114, 32,
691+ 16, 0, 2, 0, 0, 0,
692+ 86, 5, 16, 0, 2, 0,
693+ 0, 0, 70, 2, 16, 0,
694+ 3, 0, 0, 0, 30, 0,
695+ 0, 7, 34, 0, 16, 0,
696+ 2, 0, 0, 0, 10, 0,
697+ 16, 0, 0, 0, 0, 0,
698+ 1, 64, 0, 0, 1, 0,
699+ 0, 0, 86, 0, 0, 5,
700+ 34, 0, 16, 0, 2, 0,
701+ 0, 0, 26, 0, 16, 0,
702+ 2, 0, 0, 0, 56, 32,
703+ 0, 8, 66, 32, 16, 0,
704+ 1, 0, 0, 0, 26, 0,
705+ 16, 0, 2, 0, 0, 0,
706+ 26, 128, 32, 0, 0, 0,
707+ 0, 0, 2, 0, 0, 0,
708+ 60, 0, 0, 7, 18, 0,
709+ 16, 0, 2, 0, 0, 0,
710+ 42, 0, 16, 0, 2, 0,
711+ 0, 0, 10, 0, 16, 0,
712+ 2, 0, 0, 0, 59, 0,
713+ 0, 5, 18, 0, 16, 0,
714+ 2, 0, 0, 0, 10, 0,
715+ 16, 0, 2, 0, 0, 0,
716+ 1, 0, 0, 7, 130, 0,
717+ 16, 0, 0, 0, 0, 0,
718+ 58, 0, 16, 0, 0, 0,
719+ 0, 0, 10, 0, 16, 0,
720+ 2, 0, 0, 0, 1, 0,
721+ 0, 7, 130, 0, 16, 0,
722+ 0, 0, 0, 0, 58, 0,
723+ 16, 0, 0, 0, 0, 0,
724+ 1, 64, 0, 0, 0, 0,
725+ 0, 128, 60, 0, 0, 7,
726+ 18, 32, 16, 0, 0, 0,
727+ 0, 0, 58, 0, 16, 0,
728+ 0, 0, 0, 0, 10, 0,
729+ 16, 0, 0, 0, 0, 0,
730+ 32, 0, 0, 7, 130, 0,
731+ 16, 0, 0, 0, 0, 0,
732+ 10, 0, 16, 0, 1, 0,
733+ 0, 0, 1, 64, 0, 0,
734+ 1, 0, 0, 0, 31, 0,
735+ 4, 3, 58, 0, 16, 0,
736+ 0, 0, 0, 0, 167, 0,
737+ 0, 9, 242, 0, 16, 0,
738+ 2, 0, 0, 0, 10, 0,
739+ 16, 0, 0, 0, 0, 0,
740+ 1, 64, 0, 0, 68, 0,
741+ 0, 0, 70, 126, 16, 0,
742+ 1, 0, 0, 0, 167, 0,
743+ 0, 9, 242, 0, 16, 0,
744+ 3, 0, 0, 0, 10, 0,
745+ 16, 0, 0, 0, 0, 0,
746+ 1, 64, 0, 0, 88, 0,
747+ 0, 0, 70, 126, 16, 0,
748+ 1, 0, 0, 0, 50, 0,
749+ 0, 9, 18, 0, 16, 0,
750+ 0, 0, 0, 0, 42, 0,
751+ 16, 0, 2, 0, 0, 0,
752+ 1, 64, 0, 0, 0, 0,
753+ 0, 64, 1, 64, 0, 0,
754+ 0, 0, 128, 191, 0, 0,
755+ 0, 8, 18, 0, 16, 0,
756+ 0, 0, 0, 0, 10, 0,
757+ 16, 128, 193, 0, 0, 0,
758+ 0, 0, 0, 0, 1, 64,
759+ 0, 0, 0, 0, 128, 63,
760+ 56, 0, 0, 7, 18, 0,
761+ 16, 0, 4, 0, 0, 0,
762+ 26, 0, 16, 0, 2, 0,
763+ 0, 0, 10, 0, 16, 0,
764+ 0, 0, 0, 0, 56, 0,
765+ 0, 7, 18, 0, 16, 0,
766+ 0, 0, 0, 0, 10, 0,
767+ 16, 0, 2, 0, 0, 0,
768+ 1, 64, 0, 0, 0, 0,
769+ 64, 64, 29, 0, 0, 8,
770+ 130, 0, 16, 0, 0, 0,
771+ 0, 0, 10, 0, 16, 0,
772+ 0, 0, 0, 0, 10, 0,
773+ 16, 128, 65, 0, 0, 0,
774+ 0, 0, 0, 0, 26, 0,
775+ 0, 6, 18, 0, 16, 0,
776+ 0, 0, 0, 0, 10, 0,
777+ 16, 128, 129, 0, 0, 0,
778+ 0, 0, 0, 0, 55, 0,
779+ 0, 10, 18, 0, 16, 0,
780+ 0, 0, 0, 0, 58, 0,
781+ 16, 0, 0, 0, 0, 0,
782+ 10, 0, 16, 0, 0, 0,
783+ 0, 0, 10, 0, 16, 128,
784+ 65, 0, 0, 0, 0, 0,
785+ 0, 0, 50, 0, 0, 9,
786+ 18, 0, 16, 0, 0, 0,
787+ 0, 0, 10, 0, 16, 0,
788+ 0, 0, 0, 0, 1, 64,
789+ 0, 0, 0, 0, 0, 64,
790+ 1, 64, 0, 0, 0, 0,
791+ 128, 191, 0, 0, 0, 8,
792+ 18, 0, 16, 0, 0, 0,
793+ 0, 0, 10, 0, 16, 128,
794+ 193, 0, 0, 0, 0, 0,
795+ 0, 0, 1, 64, 0, 0,
796+ 0, 0, 128, 63, 56, 0,
797+ 0, 7, 34, 0, 16, 0,
798+ 4, 0, 0, 0, 10, 0,
799+ 16, 0, 0, 0, 0, 0,
800+ 10, 0, 16, 0, 4, 0,
801+ 0, 0, 50, 0, 0, 10,
802+ 18, 0, 16, 0, 0, 0,
803+ 0, 0, 10, 0, 16, 128,
804+ 65, 0, 0, 0, 4, 0,
805+ 0, 0, 1, 64, 0, 0,
806+ 0, 0, 0, 63, 42, 0,
807+ 16, 0, 2, 0, 0, 0,
808+ 29, 0, 0, 10, 242, 0,
809+ 16, 0, 6, 0, 0, 0,
810+ 6, 0, 16, 0, 2, 0,
811+ 0, 0, 2, 64, 0, 0,
812+ 0, 0, 0, 0, 171, 170,
813+ 42, 62, 171, 170, 170, 62,
814+ 0, 0, 0, 63, 49, 0,
815+ 0, 10, 242, 0, 16, 0,
816+ 7, 0, 0, 0, 6, 0,
817+ 16, 0, 2, 0, 0, 0,
818+ 2, 64, 0, 0, 171, 170,
819+ 42, 62, 171, 170, 170, 62,
820+ 0, 0, 0, 63, 171, 170,
821+ 42, 63, 1, 0, 0, 7,
822+ 242, 0, 16, 0, 6, 0,
823+ 0, 0, 70, 14, 16, 0,
824+ 6, 0, 0, 0, 70, 14,
825+ 16, 0, 7, 0, 0, 0,
826+ 29, 0, 0, 7, 130, 0,
827+ 16, 0, 0, 0, 0, 0,
828+ 10, 0, 16, 0, 2, 0,
829+ 0, 0, 1, 64, 0, 0,
830+ 171, 170, 42, 63, 49, 0,
831+ 0, 7, 130, 0, 16, 0,
832+ 4, 0, 0, 0, 10, 0,
833+ 16, 0, 2, 0, 0, 0,
834+ 1, 64, 0, 0, 85, 85,
835+ 85, 63, 1, 0, 0, 7,
836+ 130, 0, 16, 0, 0, 0,
837+ 0, 0, 58, 0, 16, 0,
838+ 0, 0, 0, 0, 58, 0,
839+ 16, 0, 4, 0, 0, 0,
840+ 54, 0, 0, 5, 66, 0,
841+ 16, 0, 4, 0, 0, 0,
842+ 1, 64, 0, 0, 0, 0,
843+ 0, 0, 55, 0, 0, 9,
844+ 114, 0, 16, 0, 5, 0,
845+ 0, 0, 246, 15, 16, 0,
846+ 0, 0, 0, 0, 150, 4,
847+ 16, 0, 4, 0, 0, 0,
848+ 134, 1, 16, 0, 4, 0,
849+ 0, 0, 55, 0, 0, 9,
850+ 114, 0, 16, 0, 5, 0,
851+ 0, 0, 246, 15, 16, 0,
852+ 6, 0, 0, 0, 102, 8,
853+ 16, 0, 4, 0, 0, 0,
854+ 70, 2, 16, 0, 5, 0,
855+ 0, 0, 55, 0, 0, 9,
856+ 114, 0, 16, 0, 5, 0,
857+ 0, 0, 166, 10, 16, 0,
858+ 6, 0, 0, 0, 38, 9,
859+ 16, 0, 4, 0, 0, 0,
860+ 70, 2, 16, 0, 5, 0,
861+ 0, 0, 55, 0, 0, 9,
862+ 114, 0, 16, 0, 5, 0,
863+ 0, 0, 86, 5, 16, 0,
864+ 6, 0, 0, 0, 22, 6,
865+ 16, 0, 4, 0, 0, 0,
866+ 70, 2, 16, 0, 5, 0,
867+ 0, 0, 55, 0, 0, 9,
868+ 114, 0, 16, 0, 4, 0,
869+ 0, 0, 6, 0, 16, 0,
870+ 6, 0, 0, 0, 70, 2,
871+ 16, 0, 4, 0, 0, 0,
872+ 70, 2, 16, 0, 5, 0,
873+ 0, 0, 0, 0, 0, 7,
874+ 114, 0, 16, 0, 2, 0,
875+ 0, 0, 6, 0, 16, 0,
876+ 0, 0, 0, 0, 70, 2,
877+ 16, 0, 4, 0, 0, 0,
878+ 50, 0, 0, 9, 18, 0,
879+ 16, 0, 0, 0, 0, 0,
880+ 42, 0, 16, 0, 3, 0,
881+ 0, 0, 1, 64, 0, 0,
882+ 0, 0, 0, 64, 1, 64,
883+ 0, 0, 0, 0, 128, 191,
884+ 0, 0, 0, 8, 18, 0,
885+ 16, 0, 0, 0, 0, 0,
886+ 10, 0, 16, 128, 193, 0,
887+ 0, 0, 0, 0, 0, 0,
888+ 1, 64, 0, 0, 0, 0,
889+ 128, 63, 56, 0, 0, 7,
890+ 18, 0, 16, 0, 4, 0,
891+ 0, 0, 26, 0, 16, 0,
892+ 3, 0, 0, 0, 10, 0,
893+ 16, 0, 0, 0, 0, 0,
894+ 56, 0, 0, 7, 18, 0,
895+ 16, 0, 0, 0, 0, 0,
896+ 10, 0, 16, 0, 3, 0,
897+ 0, 0, 1, 64, 0, 0,
898+ 0, 0, 64, 64, 29, 0,
899+ 0, 8, 130, 0, 16, 0,
900+ 0, 0, 0, 0, 10, 0,
901+ 16, 0, 0, 0, 0, 0,
902+ 10, 0, 16, 128, 65, 0,
903+ 0, 0, 0, 0, 0, 0,
904+ 26, 0, 0, 6, 18, 0,
905+ 16, 0, 0, 0, 0, 0,
906+ 10, 0, 16, 128, 129, 0,
907+ 0, 0, 0, 0, 0, 0,
908+ 55, 0, 0, 10, 18, 0,
909+ 16, 0, 0, 0, 0, 0,
910+ 58, 0, 16, 0, 0, 0,
911+ 0, 0, 10, 0, 16, 0,
912+ 0, 0, 0, 0, 10, 0,
913+ 16, 128, 65, 0, 0, 0,
914+ 0, 0, 0, 0, 50, 0,
915+ 0, 9, 18, 0, 16, 0,
916+ 0, 0, 0, 0, 10, 0,
917+ 16, 0, 0, 0, 0, 0,
918+ 1, 64, 0, 0, 0, 0,
919+ 0, 64, 1, 64, 0, 0,
920+ 0, 0, 128, 191, 0, 0,
921+ 0, 8, 18, 0, 16, 0,
922+ 0, 0, 0, 0, 10, 0,
923+ 16, 128, 193, 0, 0, 0,
924+ 0, 0, 0, 0, 1, 64,
925+ 0, 0, 0, 0, 128, 63,
926+ 56, 0, 0, 7, 34, 0,
927+ 16, 0, 4, 0, 0, 0,
928+ 10, 0, 16, 0, 0, 0,
929+ 0, 0, 10, 0, 16, 0,
930+ 4, 0, 0, 0, 50, 0,
931+ 0, 10, 18, 0, 16, 0,
932+ 0, 0, 0, 0, 10, 0,
933+ 16, 128, 65, 0, 0, 0,
934+ 4, 0, 0, 0, 1, 64,
935+ 0, 0, 0, 0, 0, 63,
936+ 42, 0, 16, 0, 3, 0,
937+ 0, 0, 29, 0, 0, 10,
938+ 242, 0, 16, 0, 6, 0,
939+ 0, 0, 6, 0, 16, 0,
940+ 3, 0, 0, 0, 2, 64,
941+ 0, 0, 0, 0, 0, 0,
942+ 171, 170, 42, 62, 171, 170,
943+ 170, 62, 0, 0, 0, 63,
944+ 49, 0, 0, 10, 242, 0,
945+ 16, 0, 7, 0, 0, 0,
946+ 6, 0, 16, 0, 3, 0,
947+ 0, 0, 2, 64, 0, 0,
948+ 171, 170, 42, 62, 171, 170,
949+ 170, 62, 0, 0, 0, 63,
950+ 171, 170, 42, 63, 1, 0,
951+ 0, 7, 242, 0, 16, 0,
952+ 6, 0, 0, 0, 70, 14,
953+ 16, 0, 6, 0, 0, 0,
954+ 70, 14, 16, 0, 7, 0,
955+ 0, 0, 29, 0, 0, 7,
956+ 130, 0, 16, 0, 0, 0,
957+ 0, 0, 10, 0, 16, 0,
958+ 3, 0, 0, 0, 1, 64,
959+ 0, 0, 171, 170, 42, 63,
960+ 49, 0, 0, 7, 130, 0,
961+ 16, 0, 4, 0, 0, 0,
962+ 10, 0, 16, 0, 3, 0,
963+ 0, 0, 1, 64, 0, 0,
964+ 85, 85, 85, 63, 1, 0,
965+ 0, 7, 130, 0, 16, 0,
966+ 0, 0, 0, 0, 58, 0,
967+ 16, 0, 0, 0, 0, 0,
968+ 58, 0, 16, 0, 4, 0,
969+ 0, 0, 54, 0, 0, 5,
970+ 66, 0, 16, 0, 4, 0,
971+ 0, 0, 1, 64, 0, 0,
972+ 0, 0, 0, 0, 55, 0,
973+ 0, 9, 114, 0, 16, 0,
974+ 5, 0, 0, 0, 246, 15,
975+ 16, 0, 0, 0, 0, 0,
976+ 150, 4, 16, 0, 4, 0,
977+ 0, 0, 134, 1, 16, 0,
978+ 4, 0, 0, 0, 55, 0,
979+ 0, 9, 114, 0, 16, 0,
980+ 5, 0, 0, 0, 246, 15,
981+ 16, 0, 6, 0, 0, 0,
982+ 102, 8, 16, 0, 4, 0,
983+ 0, 0, 70, 2, 16, 0,
984+ 5, 0, 0, 0, 55, 0,
985+ 0, 9, 114, 0, 16, 0,
986+ 5, 0, 0, 0, 166, 10,
987+ 16, 0, 6, 0, 0, 0,
988+ 38, 9, 16, 0, 4, 0,
989+ 0, 0, 70, 2, 16, 0,
990+ 5, 0, 0, 0, 55, 0,
991+ 0, 9, 114, 0, 16, 0,
992+ 5, 0, 0, 0, 86, 5,
993+ 16, 0, 6, 0, 0, 0,
994+ 22, 6, 16, 0, 4, 0,
995+ 0, 0, 70, 2, 16, 0,
996+ 5, 0, 0, 0, 55, 0,
997+ 0, 9, 114, 0, 16, 0,
998+ 4, 0, 0, 0, 6, 0,
999+ 16, 0, 6, 0, 0, 0,
1000+ 70, 2, 16, 0, 4, 0,
1001+ 0, 0, 70, 2, 16, 0,
1002+ 5, 0, 0, 0, 0, 0,
1003+ 0, 7, 114, 0, 16, 0,
1004+ 3, 0, 0, 0, 6, 0,
1005+ 16, 0, 0, 0, 0, 0,
1006+ 70, 2, 16, 0, 4, 0,
1007+ 0, 0, 32, 0, 0, 7,
1008+ 18, 0, 16, 0, 0, 0,
1009+ 0, 0, 26, 0, 16, 0,
1010+ 1, 0, 0, 0, 1, 64,
1011+ 0, 0, 1, 0, 0, 0,
1012+ 31, 0, 4, 3, 10, 0,
1013+ 16, 0, 0, 0, 0, 0,
1014+ 47, 0, 0, 5, 114, 0,
1015+ 16, 0, 4, 0, 0, 0,
1016+ 70, 2, 16, 0, 2, 0,
1017+ 0, 0, 56, 0, 0, 10,
1018+ 114, 0, 16, 0, 4, 0,
1019+ 0, 0, 70, 2, 16, 0,
1020+ 4, 0, 0, 0, 2, 64,
1021+ 0, 0, 205, 204, 12, 64,
1022+ 205, 204, 12, 64, 205, 204,
1023+ 12, 64, 0, 0, 0, 0,
1024+ 25, 0, 0, 5, 114, 0,
1025+ 16, 0, 4, 0, 0, 0,
1026+ 70, 2, 16, 0, 4, 0,
1027+ 0, 0, 16, 0, 0, 10,
1028+ 18, 0, 16, 0, 0, 0,
1029+ 0, 0, 70, 2, 16, 0,
1030+ 4, 0, 0, 0, 2, 64,
1031+ 0, 0, 177, 14, 211, 62,
1032+ 23, 77, 9, 63, 9, 185,
1033+ 82, 61, 0, 0, 0, 0,
1034+ 16, 0, 0, 10, 130, 0,
1035+ 16, 0, 0, 0, 0, 0,
1036+ 70, 2, 16, 0, 4, 0,
1037+ 0, 0, 2, 64, 0, 0,
1038+ 59, 253, 88, 62, 83, 66,
1039+ 46, 63, 240, 242, 219, 61,
1040+ 0, 0, 0, 0, 16, 0,
1041+ 0, 10, 34, 0, 16, 0,
1042+ 1, 0, 0, 0, 70, 2,
1043+ 16, 0, 4, 0, 0, 0,
1044+ 2, 64, 0, 0, 236, 215,
1045+ 180, 61, 116, 61, 144, 62,
1046+ 73, 70, 33, 63, 0, 0,
1047+ 0, 0, 47, 0, 0, 5,
1048+ 18, 0, 16, 0, 0, 0,
1049+ 0, 0, 10, 0, 16, 0,
1050+ 0, 0, 0, 0, 56, 0,
1051+ 0, 7, 18, 0, 16, 0,
1052+ 0, 0, 0, 0, 10, 0,
1053+ 16, 0, 0, 0, 0, 0,
1054+ 1, 64, 0, 0, 171, 170,
1055+ 170, 62, 25, 0, 0, 5,
1056+ 18, 0, 16, 0, 0, 0,
1057+ 0, 0, 10, 0, 16, 0,
1058+ 0, 0, 0, 0, 47, 0,
1059+ 0, 5, 130, 0, 16, 0,
1060+ 0, 0, 0, 0, 58, 0,
1061+ 16, 0, 0, 0, 0, 0,
1062+ 56, 0, 0, 7, 130, 0,
1063+ 16, 0, 0, 0, 0, 0,
1064+ 58, 0, 16, 0, 0, 0,
1065+ 0, 0, 1, 64, 0, 0,
1066+ 171, 170, 170, 62, 25, 0,
1067+ 0, 5, 130, 0, 16, 0,
1068+ 0, 0, 0, 0, 58, 0,
1069+ 16, 0, 0, 0, 0, 0,
1070+ 47, 0, 0, 5, 34, 0,
1071+ 16, 0, 1, 0, 0, 0,
1072+ 26, 0, 16, 0, 1, 0,
1073+ 0, 0, 56, 0, 0, 7,
1074+ 34, 0, 16, 0, 1, 0,
1075+ 0, 0, 26, 0, 16, 0,
1076+ 1, 0, 0, 0, 1, 64,
1077+ 0, 0, 171, 170, 170, 62,
1078+ 25, 0, 0, 5, 34, 0,
1079+ 16, 0, 1, 0, 0, 0,
1080+ 26, 0, 16, 0, 1, 0,
1081+ 0, 0, 56, 0, 0, 10,
1082+ 114, 0, 16, 0, 4, 0,
1083+ 0, 0, 246, 15, 16, 0,
1084+ 0, 0, 0, 0, 2, 64,
1085+ 0, 0, 137, 42, 75, 63,
1086+ 14, 110, 27, 64, 187, 99,
1087+ 72, 63, 0, 0, 0, 0,
1088+ 50, 0, 0, 12, 82, 0,
1089+ 16, 0, 4, 0, 0, 0,
1090+ 6, 0, 16, 0, 0, 0,
1091+ 0, 0, 2, 64, 0, 0,
1092+ 82, 129, 87, 62, 0, 0,
1093+ 0, 0, 180, 52, 212, 60,
1094+ 0, 0, 0, 0, 6, 2,
1095+ 16, 0, 4, 0, 0, 0,
1096+ 50, 0, 0, 10, 18, 0,
1097+ 16, 0, 0, 0, 0, 0,
1098+ 10, 0, 16, 0, 0, 0,
1099+ 0, 0, 1, 64, 0, 0,
1100+ 14, 47, 253, 63, 26, 0,
1101+ 16, 128, 65, 0, 0, 0,
1102+ 4, 0, 0, 0, 50, 0,
1103+ 0, 9, 34, 0, 16, 0,
1104+ 2, 0, 0, 0, 26, 0,
1105+ 16, 0, 1, 0, 0, 0,
1106+ 1, 64, 0, 0, 56, 180,
1107+ 230, 62, 10, 0, 16, 0,
1108+ 0, 0, 0, 0, 50, 0,
1109+ 0, 13, 82, 0, 16, 0,
1110+ 2, 0, 0, 0, 86, 5,
1111+ 16, 128, 65, 0, 0, 0,
1112+ 1, 0, 0, 0, 2, 64,
1113+ 0, 0, 206, 110, 133, 59,
1114+ 0, 0, 0, 0, 96, 5,
1115+ 79, 63, 0, 0, 0, 0,
1116+ 6, 2, 16, 0, 4, 0,
1117+ 0, 0, 47, 0, 0, 5,
1118+ 114, 0, 16, 0, 4, 0,
1119+ 0, 0, 70, 2, 16, 0,
1120+ 3, 0, 0, 0, 56, 0,
1121+ 0, 10, 114, 0, 16, 0,
1122+ 4, 0, 0, 0, 70, 2,
1123+ 16, 0, 4, 0, 0, 0,
1124+ 2, 64, 0, 0, 205, 204,
1125+ 12, 64, 205, 204, 12, 64,
1126+ 205, 204, 12, 64, 0, 0,
1127+ 0, 0, 25, 0, 0, 5,
1128+ 114, 0, 16, 0, 4, 0,
1129+ 0, 0, 70, 2, 16, 0,
1130+ 4, 0, 0, 0, 16, 0,
1131+ 0, 10, 18, 0, 16, 0,
1132+ 0, 0, 0, 0, 70, 2,
1133+ 16, 0, 4, 0, 0, 0,
1134+ 2, 64, 0, 0, 177, 14,
1135+ 211, 62, 23, 77, 9, 63,
1136+ 9, 185, 82, 61, 0, 0,
1137+ 0, 0, 16, 0, 0, 10,
1138+ 130, 0, 16, 0, 0, 0,
1139+ 0, 0, 70, 2, 16, 0,
1140+ 4, 0, 0, 0, 2, 64,
1141+ 0, 0, 59, 253, 88, 62,
1142+ 83, 66, 46, 63, 240, 242,
1143+ 219, 61, 0, 0, 0, 0,
1144+ 16, 0, 0, 10, 34, 0,
1145+ 16, 0, 1, 0, 0, 0,
1146+ 70, 2, 16, 0, 4, 0,
1147+ 0, 0, 2, 64, 0, 0,
1148+ 236, 215, 180, 61, 116, 61,
1149+ 144, 62, 73, 70, 33, 63,
1150+ 0, 0, 0, 0, 47, 0,
1151+ 0, 5, 18, 0, 16, 0,
1152+ 0, 0, 0, 0, 10, 0,
1153+ 16, 0, 0, 0, 0, 0,
1154+ 56, 0, 0, 7, 18, 0,
1155+ 16, 0, 0, 0, 0, 0,
1156+ 10, 0, 16, 0, 0, 0,
1157+ 0, 0, 1, 64, 0, 0,
1158+ 171, 170, 170, 62, 25, 0,
1159+ 0, 5, 18, 0, 16, 0,
1160+ 0, 0, 0, 0, 10, 0,
1161+ 16, 0, 0, 0, 0, 0,
1162+ 47, 0, 0, 5, 130, 0,
1163+ 16, 0, 0, 0, 0, 0,
1164+ 58, 0, 16, 0, 0, 0,
1165+ 0, 0, 56, 0, 0, 7,
1166+ 130, 0, 16, 0, 0, 0,
1167+ 0, 0, 58, 0, 16, 0,
1168+ 0, 0, 0, 0, 1, 64,
1169+ 0, 0, 171, 170, 170, 62,
1170+ 25, 0, 0, 5, 130, 0,
1171+ 16, 0, 0, 0, 0, 0,
1172+ 58, 0, 16, 0, 0, 0,
1173+ 0, 0, 47, 0, 0, 5,
1174+ 34, 0, 16, 0, 1, 0,
1175+ 0, 0, 26, 0, 16, 0,
1176+ 1, 0, 0, 0, 56, 0,
1177+ 0, 7, 34, 0, 16, 0,
1178+ 1, 0, 0, 0, 26, 0,
1179+ 16, 0, 1, 0, 0, 0,
1180+ 1, 64, 0, 0, 171, 170,
1181+ 170, 62, 25, 0, 0, 5,
1182+ 34, 0, 16, 0, 1, 0,
1183+ 0, 0, 26, 0, 16, 0,
1184+ 1, 0, 0, 0, 56, 0,
1185+ 0, 10, 114, 0, 16, 0,
1186+ 4, 0, 0, 0, 246, 15,
1187+ 16, 0, 0, 0, 0, 0,
1188+ 2, 64, 0, 0, 137, 42,
1189+ 75, 63, 14, 110, 27, 64,
1190+ 187, 99, 72, 63, 0, 0,
1191+ 0, 0, 50, 0, 0, 12,
1192+ 82, 0, 16, 0, 4, 0,
1193+ 0, 0, 6, 0, 16, 0,
1194+ 0, 0, 0, 0, 2, 64,
1195+ 0, 0, 82, 129, 87, 62,
1196+ 0, 0, 0, 0, 180, 52,
1197+ 212, 60, 0, 0, 0, 0,
1198+ 6, 2, 16, 0, 4, 0,
1199+ 0, 0, 50, 0, 0, 10,
1200+ 18, 0, 16, 0, 0, 0,
1201+ 0, 0, 10, 0, 16, 0,
1202+ 0, 0, 0, 0, 1, 64,
1203+ 0, 0, 14, 47, 253, 63,
1204+ 26, 0, 16, 128, 65, 0,
1205+ 0, 0, 4, 0, 0, 0,
1206+ 50, 0, 0, 9, 34, 0,
1207+ 16, 0, 3, 0, 0, 0,
1208+ 26, 0, 16, 0, 1, 0,
1209+ 0, 0, 1, 64, 0, 0,
1210+ 56, 180, 230, 62, 10, 0,
1211+ 16, 0, 0, 0, 0, 0,
1212+ 50, 0, 0, 13, 82, 0,
1213+ 16, 0, 3, 0, 0, 0,
1214+ 86, 5, 16, 128, 65, 0,
1215+ 0, 0, 1, 0, 0, 0,
1216+ 2, 64, 0, 0, 206, 110,
1217+ 133, 59, 0, 0, 0, 0,
1218+ 96, 5, 79, 63, 0, 0,
1219+ 0, 0, 6, 2, 16, 0,
1220+ 4, 0, 0, 0, 21, 0,
1221+ 0, 1, 54, 0, 0, 5,
1222+ 242, 32, 16, 0, 3, 0,
1223+ 0, 0, 70, 14, 16, 0,
1224+ 2, 0, 0, 0, 54, 0,
1225+ 0, 5, 242, 32, 16, 0,
1226+ 4, 0, 0, 0, 70, 14,
1227+ 16, 0, 3, 0, 0, 0,
1228+ 18, 0, 0, 1, 50, 0,
1229+ 0, 9, 18, 0, 16, 0,
1230+ 0, 0, 0, 0, 26, 0,
1231+ 16, 0, 0, 0, 0, 0,
1232+ 1, 64, 0, 0, 0, 0,
1233+ 0, 64, 1, 64, 0, 0,
1234+ 0, 0, 128, 191, 0, 0,
1235+ 0, 8, 18, 0, 16, 0,
1236+ 0, 0, 0, 0, 10, 0,
1237+ 16, 128, 193, 0, 0, 0,
1238+ 0, 0, 0, 0, 1, 64,
1239+ 0, 0, 0, 0, 128, 63,
1240+ 56, 0, 0, 7, 18, 0,
1241+ 16, 0, 2, 0, 0, 0,
1242+ 58, 0, 16, 0, 1, 0,
1243+ 0, 0, 10, 0, 16, 0,
1244+ 0, 0, 0, 0, 56, 0,
1245+ 0, 7, 18, 0, 16, 0,
1246+ 0, 0, 0, 0, 42, 0,
1247+ 16, 0, 1, 0, 0, 0,
1248+ 1, 64, 0, 0, 0, 0,
1249+ 64, 64, 29, 0, 0, 8,
1250+ 130, 0, 16, 0, 0, 0,
1251+ 0, 0, 10, 0, 16, 0,
1252+ 0, 0, 0, 0, 10, 0,
1253+ 16, 128, 65, 0, 0, 0,
1254+ 0, 0, 0, 0, 26, 0,
1255+ 0, 6, 18, 0, 16, 0,
1256+ 0, 0, 0, 0, 10, 0,
1257+ 16, 128, 129, 0, 0, 0,
1258+ 0, 0, 0, 0, 55, 0,
1259+ 0, 10, 18, 0, 16, 0,
1260+ 0, 0, 0, 0, 58, 0,
1261+ 16, 0, 0, 0, 0, 0,
1262+ 10, 0, 16, 0, 0, 0,
1263+ 0, 0, 10, 0, 16, 128,
1264+ 65, 0, 0, 0, 0, 0,
1265+ 0, 0, 50, 0, 0, 9,
1266+ 18, 0, 16, 0, 0, 0,
1267+ 0, 0, 10, 0, 16, 0,
1268+ 0, 0, 0, 0, 1, 64,
1269+ 0, 0, 0, 0, 0, 64,
1270+ 1, 64, 0, 0, 0, 0,
1271+ 128, 191, 0, 0, 0, 8,
1272+ 18, 0, 16, 0, 0, 0,
1273+ 0, 0, 10, 0, 16, 128,
1274+ 193, 0, 0, 0, 0, 0,
1275+ 0, 0, 1, 64, 0, 0,
1276+ 0, 0, 128, 63, 56, 0,
1277+ 0, 7, 34, 0, 16, 0,
1278+ 2, 0, 0, 0, 10, 0,
1279+ 16, 0, 0, 0, 0, 0,
1280+ 10, 0, 16, 0, 2, 0,
1281+ 0, 0, 50, 0, 0, 10,
1282+ 18, 0, 16, 0, 0, 0,
1283+ 0, 0, 10, 0, 16, 128,
1284+ 65, 0, 0, 0, 2, 0,
1285+ 0, 0, 1, 64, 0, 0,
1286+ 0, 0, 0, 63, 26, 0,
1287+ 16, 0, 0, 0, 0, 0,
1288+ 29, 0, 0, 10, 242, 0,
1289+ 16, 0, 3, 0, 0, 0,
1290+ 166, 10, 16, 0, 1, 0,
1291+ 0, 0, 2, 64, 0, 0,
1292+ 0, 0, 0, 0, 171, 170,
1293+ 42, 62, 171, 170, 170, 62,
1294+ 0, 0, 0, 63, 49, 0,
1295+ 0, 10, 242, 0, 16, 0,
1296+ 4, 0, 0, 0, 166, 10,
1297+ 16, 0, 1, 0, 0, 0,
1298+ 2, 64, 0, 0, 171, 170,
1299+ 42, 62, 171, 170, 170, 62,
1300+ 0, 0, 0, 63, 171, 170,
1301+ 42, 63, 1, 0, 0, 7,
1302+ 242, 0, 16, 0, 3, 0,
1303+ 0, 0, 70, 14, 16, 0,
1304+ 3, 0, 0, 0, 70, 14,
1305+ 16, 0, 4, 0, 0, 0,
1306+ 29, 0, 0, 7, 34, 0,
1307+ 16, 0, 0, 0, 0, 0,
1308+ 42, 0, 16, 0, 1, 0,
1309+ 0, 0, 1, 64, 0, 0,
1310+ 171, 170, 42, 63, 49, 0,
1311+ 0, 7, 130, 0, 16, 0,
1312+ 0, 0, 0, 0, 42, 0,
1313+ 16, 0, 1, 0, 0, 0,
1314+ 1, 64, 0, 0, 85, 85,
1315+ 85, 63, 1, 0, 0, 7,
1316+ 34, 0, 16, 0, 0, 0,
1317+ 0, 0, 58, 0, 16, 0,
1318+ 0, 0, 0, 0, 26, 0,
1319+ 16, 0, 0, 0, 0, 0,
1320+ 54, 0, 0, 5, 66, 0,
1321+ 16, 0, 2, 0, 0, 0,
1322+ 1, 64, 0, 0, 0, 0,
1323+ 0, 0, 55, 0, 0, 9,
1324+ 226, 0, 16, 0, 1, 0,
1325+ 0, 0, 86, 5, 16, 0,
1326+ 0, 0, 0, 0, 86, 2,
1327+ 16, 0, 2, 0, 0, 0,
1328+ 6, 6, 16, 0, 2, 0,
1329+ 0, 0, 55, 0, 0, 9,
1330+ 226, 0, 16, 0, 1, 0,
1331+ 0, 0, 246, 15, 16, 0,
1332+ 3, 0, 0, 0, 166, 1,
1333+ 16, 0, 2, 0, 0, 0,
1334+ 86, 14, 16, 0, 1, 0,
1335+ 0, 0, 55, 0, 0, 9,
1336+ 226, 0, 16, 0, 1, 0,
1337+ 0, 0, 166, 10, 16, 0,
1338+ 3, 0, 0, 0, 166, 4,
1339+ 16, 0, 2, 0, 0, 0,
1340+ 86, 14, 16, 0, 1, 0,
1341+ 0, 0, 55, 0, 0, 9,
1342+ 226, 0, 16, 0, 1, 0,
1343+ 0, 0, 86, 5, 16, 0,
1344+ 3, 0, 0, 0, 86, 8,
1345+ 16, 0, 2, 0, 0, 0,
1346+ 86, 14, 16, 0, 1, 0,
1347+ 0, 0, 55, 0, 0, 9,
1348+ 226, 0, 16, 0, 1, 0,
1349+ 0, 0, 6, 0, 16, 0,
1350+ 3, 0, 0, 0, 6, 9,
1351+ 16, 0, 2, 0, 0, 0,
1352+ 86, 14, 16, 0, 1, 0,
1353+ 0, 0, 0, 0, 0, 7,
1354+ 114, 32, 16, 0, 3, 0,
1355+ 0, 0, 6, 0, 16, 0,
1356+ 0, 0, 0, 0, 150, 7,
1357+ 16, 0, 1, 0, 0, 0,
1358+ 54, 0, 0, 5, 130, 32,
1359+ 16, 0, 3, 0, 0, 0,
1360+ 42, 0, 16, 0, 0, 0,
1361+ 0, 0, 54, 0, 0, 8,
1362+ 242, 32, 16, 0, 4, 0,
1363+ 0, 0, 2, 64, 0, 0,
1364+ 0, 0, 0, 0, 0, 0,
1365+ 0, 0, 0, 0, 0, 0,
1366+ 0, 0, 0, 0, 21, 0,
1367+ 0, 1, 54, 0, 0, 5,
1368+ 130, 32, 16, 0, 1, 0,
1369+ 0, 0, 1, 64, 0, 0,
1370+ 0, 0, 128, 63, 54, 0,
1371+ 0, 5, 130, 32, 16, 0,
1372+ 2, 0, 0, 0, 58, 0,
1373+ 16, 0, 5, 0, 0, 0,
1374+ 54, 0, 0, 5, 34, 32,
1375+ 16, 0, 0, 0, 0, 0,
1376+ 10, 0, 16, 0, 1, 0,
1377+ 0, 0, 62, 0, 0, 1,
1378+ 83, 70, 73, 48, 8, 0,
1379+ 0, 0, 2, 0, 0, 0,
1380+ 0, 0, 0, 0, 83, 84,
1381+ 65, 84, 116, 0, 0, 0,
1382+ 204, 0, 0, 0, 8, 0,
1383+ 0, 0, 0, 0, 0, 0,
1384+ 8, 0, 0, 0, 114, 0,
1385+ 0, 0, 5, 0, 0, 0,
1386+ 25, 0, 0, 0, 3, 0,
1387+ 0, 0, 3, 0, 0, 0,
1388+ 0, 0, 0, 0, 0, 0,
1389+ 0, 0, 0, 0, 0, 0,
1390+ 0, 0, 0, 0, 0, 0,
1391+ 0, 0, 0, 0, 0, 0,
1392+ 9, 0, 0, 0, 0, 0,
1393+ 0, 0, 0, 0, 0, 0,
1394+ 0, 0, 0, 0, 16, 0,
1395+ 0, 0, 24, 0, 0, 0,
1396+ 6, 0, 0, 0, 0, 0,
1397+ 0, 0, 0, 0, 0, 0,
1398+ 0, 0, 0, 0, 0, 0,
1399+ 0, 0, 0, 0, 0, 0,
1400+ 0, 0, 0, 0, 0, 0,
1401+ 0, 0
1402+];
1403+const QUAD_FRAGMENT_BYTES: &[u8] = &[
1404+ 68, 88, 66, 67, 84, 166,
1405+ 108, 182, 233, 141, 81, 251,
1406+ 207, 217, 101, 219, 167, 208,
1407+ 211, 72, 1, 0, 0, 0,
1408+ 188, 43, 0, 0, 6, 0,
1409+ 0, 0, 56, 0, 0, 0,
1410+ 252, 3, 0, 0, 184, 4,
1411+ 0, 0, 236, 4, 0, 0,
1412+ 48, 43, 0, 0, 64, 43,
1413+ 0, 0, 82, 68, 69, 70,
1414+ 188, 3, 0, 0, 1, 0,
1415+ 0, 0, 68, 0, 0, 0,
1416+ 1, 0, 0, 0, 28, 0,
1417+ 0, 0, 1, 4, 255, 255,
1418+ 0, 129, 0, 0, 148, 3,
1419+ 0, 0, 60, 0, 0, 0,
1420+ 5, 0, 0, 0, 6, 0,
1421+ 0, 0, 1, 0, 0, 0,
1422+ 160, 0, 0, 0, 1, 0,
1423+ 0, 0, 1, 0, 0, 0,
1424+ 1, 0, 0, 0, 113, 117,
1425+ 97, 100, 115, 0, 171, 171,
1426+ 60, 0, 0, 0, 1, 0,
1427+ 0, 0, 92, 0, 0, 0,
1428+ 160, 0, 0, 0, 0, 0,
1429+ 0, 0, 3, 0, 0, 0,
1430+ 116, 0, 0, 0, 0, 0,
1431+ 0, 0, 160, 0, 0, 0,
1432+ 2, 0, 0, 0, 132, 3,
1433+ 0, 0, 0, 0, 0, 0,
1434+ 36, 69, 108, 101, 109, 101,
1435+ 110, 116, 0, 111, 114, 100,
1436+ 101, 114, 0, 171, 0, 0,
1437+ 19, 0, 1, 0, 1, 0,
1438+ 0, 0, 0, 0, 0, 0,
1439+ 0, 0, 98, 111, 114, 100,
1440+ 101, 114, 95, 115, 116, 121,
1441+ 108, 101, 0, 98, 111, 117,
1442+ 110, 100, 115, 0, 111, 114,
1443+ 105, 103, 105, 110, 0, 171,
1444+ 1, 0, 3, 0, 1, 0,
1445+ 2, 0, 0, 0, 0, 0,
1446+ 0, 0, 0, 0, 115, 105,
1447+ 122, 101, 0, 171, 171, 171,
1448+ 168, 0, 0, 0, 176, 0,
1449+ 0, 0, 0, 0, 0, 0,
1450+ 192, 0, 0, 0, 176, 0,
1451+ 0, 0, 8, 0, 0, 0,
1452+ 5, 0, 0, 0, 1, 0,
1453+ 4, 0, 0, 0, 2, 0,
1454+ 200, 0, 0, 0, 99, 111,
1455+ 110, 116, 101, 110, 116, 95,
1456+ 109, 97, 115, 107, 0, 98,
1457+ 97, 99, 107, 103, 114, 111,
1458+ 117, 110, 100, 0, 116, 97,
1459+ 103, 0, 99, 111, 108, 111,
1460+ 114, 95, 115, 112, 97, 99,
1461+ 101, 0, 115, 111, 108, 105,
1462+ 100, 0, 104, 0, 0, 0,
1463+ 3, 0, 1, 0, 1, 0,
1464+ 0, 0, 0, 0, 0, 0,
1465+ 0, 0, 115, 0, 108, 0,
1466+ 97, 0, 171, 171, 30, 1,
1467+ 0, 0, 32, 1, 0, 0,
1468+ 0, 0, 0, 0, 48, 1,
1469+ 0, 0, 32, 1, 0, 0,
1470+ 4, 0, 0, 0, 50, 1,
1471+ 0, 0, 32, 1, 0, 0,
1472+ 8, 0, 0, 0, 52, 1,
1473+ 0, 0, 32, 1, 0, 0,
1474+ 12, 0, 0, 0, 5, 0,
1475+ 0, 0, 1, 0, 4, 0,
1476+ 0, 0, 4, 0, 56, 1,
1477+ 0, 0, 103, 114, 97, 100,
1478+ 105, 101, 110, 116, 95, 97,
1479+ 110, 103, 108, 101, 95, 111,
1480+ 114, 95, 112, 97, 116, 116,
1481+ 101, 114, 110, 95, 104, 101,
1482+ 105, 103, 104, 116, 0, 99,
1483+ 111, 108, 111, 114, 115, 0,
1484+ 99, 111, 108, 111, 114, 0,
1485+ 112, 101, 114, 99, 101, 110,
1486+ 116, 97, 103, 101, 0, 171,
1487+ 171, 171, 160, 1, 0, 0,
1488+ 104, 1, 0, 0, 0, 0,
1489+ 0, 0, 166, 1, 0, 0,
1490+ 32, 1, 0, 0, 16, 0,
1491+ 0, 0, 5, 0, 0, 0,
1492+ 1, 0, 5, 0, 2, 0,
1493+ 2, 0, 180, 1, 0, 0,
1494+ 112, 97, 100, 0, 8, 1,
1495+ 0, 0, 132, 0, 0, 0,
1496+ 0, 0, 0, 0, 12, 1,
1497+ 0, 0, 132, 0, 0, 0,
1498+ 4, 0, 0, 0, 24, 1,
1499+ 0, 0, 104, 1, 0, 0,
1500+ 8, 0, 0, 0, 120, 1,
1501+ 0, 0, 32, 1, 0, 0,
1502+ 24, 0, 0, 0, 153, 1,
1503+ 0, 0, 204, 1, 0, 0,
1504+ 28, 0, 0, 0, 220, 1,
1505+ 0, 0, 132, 0, 0, 0,
1506+ 68, 0, 0, 0, 5, 0,
1507+ 0, 0, 1, 0, 18, 0,
1508+ 0, 0, 6, 0, 224, 1,
1509+ 0, 0, 98, 111, 114, 100,
1510+ 101, 114, 95, 99, 111, 108,
1511+ 111, 114, 0, 99, 111, 114,
1512+ 110, 101, 114, 95, 114, 97,
1513+ 100, 105, 105, 0, 116, 111,
1514+ 112, 95, 108, 101, 102, 116,
1515+ 0, 116, 111, 112, 95, 114,
1516+ 105, 103, 104, 116, 0, 98,
1517+ 111, 116, 116, 111, 109, 95,
1518+ 114, 105, 103, 104, 116, 0,
1519+ 98, 111, 116, 116, 111, 109,
1520+ 95, 108, 101, 102, 116, 0,
1521+ 171, 171, 82, 2, 0, 0,
1522+ 32, 1, 0, 0, 0, 0,
1523+ 0, 0, 91, 2, 0, 0,
1524+ 32, 1, 0, 0, 4, 0,
1525+ 0, 0, 101, 2, 0, 0,
1526+ 32, 1, 0, 0, 8, 0,
1527+ 0, 0, 114, 2, 0, 0,
1528+ 32, 1, 0, 0, 12, 0,
1529+ 0, 0, 5, 0, 0, 0,
1530+ 1, 0, 4, 0, 0, 0,
1531+ 4, 0, 128, 2, 0, 0,
1532+ 98, 111, 114, 100, 101, 114,
1533+ 95, 119, 105, 100, 116, 104,
1534+ 115, 0, 116, 111, 112, 0,
1535+ 114, 105, 103, 104, 116, 0,
1536+ 98, 111, 116, 116, 111, 109,
1537+ 0, 108, 101, 102, 116, 0,
1538+ 206, 2, 0, 0, 32, 1,
1539+ 0, 0, 0, 0, 0, 0,
1540+ 210, 2, 0, 0, 32, 1,
1541+ 0, 0, 4, 0, 0, 0,
1542+ 216, 2, 0, 0, 32, 1,
1543+ 0, 0, 8, 0, 0, 0,
1544+ 223, 2, 0, 0, 32, 1,
1545+ 0, 0, 12, 0, 0, 0,
1546+ 5, 0, 0, 0, 1, 0,
1547+ 4, 0, 0, 0, 4, 0,
1548+ 228, 2, 0, 0, 125, 0,
1549+ 0, 0, 132, 0, 0, 0,
1550+ 0, 0, 0, 0, 148, 0,
1551+ 0, 0, 132, 0, 0, 0,
1552+ 4, 0, 0, 0, 161, 0,
1553+ 0, 0, 224, 0, 0, 0,
1554+ 8, 0, 0, 0, 240, 0,
1555+ 0, 0, 224, 0, 0, 0,
1556+ 24, 0, 0, 0, 253, 0,
1557+ 0, 0, 40, 2, 0, 0,
1558+ 40, 0, 0, 0, 56, 2,
1559+ 0, 0, 104, 1, 0, 0,
1560+ 112, 0, 0, 0, 69, 2,
1561+ 0, 0, 176, 2, 0, 0,
1562+ 128, 0, 0, 0, 192, 2,
1563+ 0, 0, 20, 3, 0, 0,
1564+ 144, 0, 0, 0, 5, 0,
1565+ 0, 0, 1, 0, 40, 0,
1566+ 0, 0, 8, 0, 36, 3,
1567+ 0, 0, 77, 105, 99, 114,
1568+ 111, 115, 111, 102, 116, 32,
1569+ 40, 82, 41, 32, 72, 76,
1570+ 83, 76, 32, 83, 104, 97,
1571+ 100, 101, 114, 32, 67, 111,
1572+ 109, 112, 105, 108, 101, 114,
1573+ 32, 49, 48, 46, 49, 0,
1574+ 73, 83, 71, 78, 180, 0,
1575+ 0, 0, 6, 0, 0, 0,
1576+ 8, 0, 0, 0, 152, 0,
1577+ 0, 0, 0, 0, 0, 0,
1578+ 0, 0, 0, 0, 1, 0,
1579+ 0, 0, 0, 0, 0, 0,
1580+ 1, 1, 0, 0, 152, 0,
1581+ 0, 0, 2, 0, 0, 0,
1582+ 0, 0, 0, 0, 1, 0,
1583+ 0, 0, 0, 0, 0, 0,
1584+ 2, 2, 0, 0, 161, 0,
1585+ 0, 0, 0, 0, 0, 0,
1586+ 1, 0, 0, 0, 3, 0,
1587+ 0, 0, 1, 0, 0, 0,
1588+ 15, 3, 0, 0, 173, 0,
1589+ 0, 0, 0, 0, 0, 0,
1590+ 0, 0, 0, 0, 3, 0,
1591+ 0, 0, 2, 0, 0, 0,
1592+ 15, 15, 0, 0, 173, 0,
1593+ 0, 0, 1, 0, 0, 0,
1594+ 0, 0, 0, 0, 3, 0,
1595+ 0, 0, 3, 0, 0, 0,
1596+ 15, 15, 0, 0, 173, 0,
1597+ 0, 0, 2, 0, 0, 0,
1598+ 0, 0, 0, 0, 3, 0,
1599+ 0, 0, 4, 0, 0, 0,
1600+ 15, 15, 0, 0, 84, 69,
1601+ 88, 67, 79, 79, 82, 68,
1602+ 0, 83, 86, 95, 80, 111,
1603+ 115, 105, 116, 105, 111, 110,
1604+ 0, 67, 79, 76, 79, 82,
1605+ 0, 171, 79, 83, 71, 78,
1606+ 44, 0, 0, 0, 1, 0,
1607+ 0, 0, 8, 0, 0, 0,
1608+ 32, 0, 0, 0, 0, 0,
1609+ 0, 0, 0, 0, 0, 0,
1610+ 3, 0, 0, 0, 0, 0,
1611+ 0, 0, 15, 0, 0, 0,
1612+ 83, 86, 95, 84, 97, 114,
1613+ 103, 101, 116, 0, 171, 171,
1614+ 83, 72, 69, 88, 60, 38,
1615+ 0, 0, 65, 0, 0, 0,
1616+ 143, 9, 0, 0, 106, 72,
1617+ 0, 1, 162, 0, 0, 4,
1618+ 0, 112, 16, 0, 1, 0,
1619+ 0, 0, 160, 0, 0, 0,
1620+ 98, 8, 0, 3, 18, 16,
1621+ 16, 0, 0, 0, 0, 0,
1622+ 98, 8, 0, 3, 34, 16,
1623+ 16, 0, 0, 0, 0, 0,
1624+ 100, 32, 0, 4, 50, 16,
1625+ 16, 0, 1, 0, 0, 0,
1626+ 1, 0, 0, 0, 98, 8,
1627+ 0, 3, 242, 16, 16, 0,
1628+ 2, 0, 0, 0, 98, 8,
1629+ 0, 3, 242, 16, 16, 0,
1630+ 3, 0, 0, 0, 98, 8,
1631+ 0, 3, 242, 16, 16, 0,
1632+ 4, 0, 0, 0, 101, 0,
1633+ 0, 3, 242, 32, 16, 0,
1634+ 0, 0, 0, 0, 104, 0,
1635+ 0, 2, 12, 0, 0, 0,
1636+ 1, 0, 0, 7, 18, 0,
1637+ 16, 0, 0, 0, 0, 0,
1638+ 10, 16, 16, 0, 0, 0,
1639+ 0, 0, 1, 64, 0, 0,
1640+ 0, 0, 0, 128, 31, 0,
1641+ 4, 3, 10, 0, 16, 0,
1642+ 0, 0, 0, 0, 54, 0,
1643+ 0, 5, 242, 32, 16, 0,
1644+ 0, 0, 0, 0, 70, 30,
1645+ 16, 0, 3, 0, 0, 0,
1646+ 62, 0, 0, 1, 21, 0,
1647+ 0, 1, 167, 0, 0, 9,
1648+ 242, 0, 16, 0, 0, 0,
1649+ 0, 0, 10, 16, 16, 0,
1650+ 0, 0, 0, 0, 1, 64,
1651+ 0, 0, 4, 0, 0, 0,
1652+ 70, 126, 16, 0, 1, 0,
1653+ 0, 0, 167, 0, 0, 9,
1654+ 18, 0, 16, 0, 1, 0,
1655+ 0, 0, 10, 16, 16, 0,
1656+ 0, 0, 0, 0, 1, 64,
1657+ 0, 0, 20, 0, 0, 0,
1658+ 6, 112, 16, 0, 1, 0,
1659+ 0, 0, 167, 0, 0, 9,
1660+ 242, 0, 16, 0, 2, 0,
1661+ 0, 0, 10, 16, 16, 0,
1662+ 0, 0, 0, 0, 1, 64,
1663+ 0, 0, 128, 0, 0, 0,
1664+ 70, 126, 16, 0, 1, 0,
1665+ 0, 0, 167, 0, 0, 9,
1666+ 242, 0, 16, 0, 3, 0,
1667+ 0, 0, 10, 16, 16, 0,
1668+ 0, 0, 0, 0, 1, 64,
1669+ 0, 0, 144, 0, 0, 0,
1670+ 70, 126, 16, 0, 1, 0,
1671+ 0, 0, 31, 0, 4, 3,
1672+ 26, 16, 16, 0, 0, 0,
1673+ 0, 0, 167, 0, 0, 9,
1674+ 130, 0, 16, 0, 1, 0,
1675+ 0, 0, 10, 16, 16, 0,
1676+ 0, 0, 0, 0, 1, 64,
1677+ 0, 0, 64, 0, 0, 0,
1678+ 6, 112, 16, 0, 1, 0,
1679+ 0, 0, 76, 0, 0, 3,
1680+ 26, 16, 16, 0, 0, 0,
1681+ 0, 0, 6, 0, 0, 3,
1682+ 1, 64, 0, 0, 1, 0,
1683+ 0, 0, 167, 0, 0, 9,
1684+ 18, 0, 16, 0, 5, 0,
1685+ 0, 0, 10, 16, 16, 0,
1686+ 0, 0, 0, 0, 1, 64,
1687+ 0, 0, 44, 0, 0, 0,
1688+ 6, 112, 16, 0, 1, 0,
1689+ 0, 0, 167, 0, 0, 9,
1690+ 34, 0, 16, 0, 5, 0,
1691+ 0, 0, 10, 16, 16, 0,
1692+ 0, 0, 0, 0, 1, 64,
1693+ 0, 0, 84, 0, 0, 0,
1694+ 6, 112, 16, 0, 1, 0,
1695+ 0, 0, 167, 0, 0, 9,
1696+ 66, 0, 16, 0, 5, 0,
1697+ 0, 0, 10, 16, 16, 0,
1698+ 0, 0, 0, 0, 1, 64,
1699+ 0, 0, 104, 0, 0, 0,
1700+ 6, 112, 16, 0, 1, 0,
1701+ 0, 0, 56, 0, 0, 7,
1702+ 130, 0, 16, 0, 5, 0,
1703+ 0, 0, 58, 0, 16, 0,
1704+ 1, 0, 0, 0, 1, 64,
1705+ 0, 0, 97, 11, 54, 59,
1706+ 29, 0, 0, 8, 18, 0,
1707+ 16, 0, 6, 0, 0, 0,
1708+ 58, 0, 16, 0, 5, 0,
1709+ 0, 0, 58, 0, 16, 128,
1710+ 65, 0, 0, 0, 5, 0,
1711+ 0, 0, 26, 0, 0, 6,
1712+ 130, 0, 16, 0, 5, 0,
1713+ 0, 0, 58, 0, 16, 128,
1714+ 129, 0, 0, 0, 5, 0,
1715+ 0, 0, 55, 0, 0, 10,
1716+ 130, 0, 16, 0, 5, 0,
1717+ 0, 0, 10, 0, 16, 0,
1718+ 6, 0, 0, 0, 58, 0,
1719+ 16, 0, 5, 0, 0, 0,
1720+ 58, 0, 16, 128, 65, 0,
1721+ 0, 0, 5, 0, 0, 0,
1722+ 50, 0, 0, 9, 130, 0,
1723+ 16, 0, 5, 0, 0, 0,
1724+ 58, 0, 16, 0, 5, 0,
1725+ 0, 0, 1, 64, 0, 0,
1726+ 0, 0, 180, 67, 1, 64,
1727+ 0, 0, 0, 0, 180, 194,
1728+ 56, 0, 0, 7, 130, 0,
1729+ 16, 0, 5, 0, 0, 0,
1730+ 58, 0, 16, 0, 5, 0,
1731+ 0, 0, 1, 64, 0, 0,
1732+ 53, 250, 142, 60, 77, 0,
1733+ 0, 7, 18, 0, 16, 0,
1734+ 6, 0, 0, 0, 18, 0,
1735+ 16, 0, 7, 0, 0, 0,
1736+ 58, 0, 16, 0, 5, 0,
1737+ 0, 0, 49, 0, 0, 7,
1738+ 130, 0, 16, 0, 5, 0,
1739+ 0, 0, 10, 0, 16, 0,
1740+ 1, 0, 0, 0, 58, 0,
1741+ 16, 0, 0, 0, 0, 0,
1742+ 14, 0, 0, 7, 34, 0,
1743+ 16, 0, 6, 0, 0, 0,
1744+ 10, 0, 16, 0, 1, 0,
1745+ 0, 0, 58, 0, 16, 0,
1746+ 0, 0, 0, 0, 56, 0,
1747+ 0, 7, 34, 0, 16, 0,
1748+ 7, 0, 0, 0, 26, 0,
1749+ 16, 0, 6, 0, 0, 0,
1750+ 10, 0, 16, 0, 6, 0,
1751+ 0, 0, 14, 0, 0, 7,
1752+ 34, 0, 16, 0, 6, 0,
1753+ 0, 0, 58, 0, 16, 0,
1754+ 0, 0, 0, 0, 10, 0,
1755+ 16, 0, 1, 0, 0, 0,
1756+ 56, 0, 0, 7, 18, 0,
1757+ 16, 0, 8, 0, 0, 0,
1758+ 26, 0, 16, 0, 6, 0,
1759+ 0, 0, 10, 0, 16, 0,
1760+ 7, 0, 0, 0, 54, 0,
1761+ 0, 5, 34, 0, 16, 0,
1762+ 8, 0, 0, 0, 10, 0,
1763+ 16, 0, 6, 0, 0, 0,
1764+ 55, 0, 0, 9, 50, 0,
1765+ 16, 0, 6, 0, 0, 0,
1766+ 246, 15, 16, 0, 5, 0,
1767+ 0, 0, 70, 0, 16, 0,
1768+ 7, 0, 0, 0, 70, 0,
1769+ 16, 0, 8, 0, 0, 0,
1770+ 49, 0, 0, 9, 130, 0,
1771+ 16, 0, 5, 0, 0, 0,
1772+ 26, 0, 16, 128, 129, 0,
1773+ 0, 0, 6, 0, 0, 0,
1774+ 10, 0, 16, 128, 129, 0,
1775+ 0, 0, 6, 0, 0, 0,
1776+ 55, 0, 0, 9, 130, 0,
1777+ 16, 0, 5, 0, 0, 0,
1778+ 58, 0, 16, 0, 5, 0,
1779+ 0, 0, 58, 0, 16, 0,
1780+ 0, 0, 0, 0, 10, 0,
1781+ 16, 0, 1, 0, 0, 0,
1782+ 15, 0, 0, 7, 66, 0,
1783+ 16, 0, 6, 0, 0, 0,
1784+ 70, 0, 16, 0, 6, 0,
1785+ 0, 0, 70, 0, 16, 0,
1786+ 6, 0, 0, 0, 75, 0,
1787+ 0, 5, 66, 0, 16, 0,
1788+ 6, 0, 0, 0, 42, 0,
1789+ 16, 0, 6, 0, 0, 0,
1790+ 0, 0, 0, 8, 66, 0,
1791+ 16, 0, 5, 0, 0, 0,
1792+ 26, 0, 16, 128, 65, 0,
1793+ 0, 0, 5, 0, 0, 0,
1794+ 42, 0, 16, 0, 5, 0,
1795+ 0, 0, 0, 0, 0, 8,
1796+ 34, 0, 16, 0, 5, 0,
1797+ 0, 0, 26, 0, 16, 128,
1798+ 65, 0, 0, 0, 5, 0,
1799+ 0, 0, 1, 64, 0, 0,
1800+ 0, 0, 0, 63, 57, 0,
1801+ 0, 7, 130, 0, 16, 0,
1802+ 6, 0, 0, 0, 42, 0,
1803+ 16, 0, 6, 0, 0, 0,
1804+ 1, 64, 0, 0, 0, 0,
1805+ 0, 0, 57, 0, 0, 7,
1806+ 18, 0, 16, 0, 7, 0,
1807+ 0, 0, 58, 0, 16, 0,
1808+ 5, 0, 0, 0, 1, 64,
1809+ 0, 0, 0, 0, 0, 0,
1810+ 1, 0, 0, 7, 130, 0,
1811+ 16, 0, 6, 0, 0, 0,
1812+ 58, 0, 16, 0, 6, 0,
1813+ 0, 0, 10, 0, 16, 0,
1814+ 7, 0, 0, 0, 24, 0,
1815+ 0, 7, 18, 0, 16, 0,
1816+ 7, 0, 0, 0, 42, 0,
1817+ 16, 0, 5, 0, 0, 0,
1818+ 1, 64, 0, 0, 0, 0,
1819+ 0, 0, 56, 0, 0, 7,
1820+ 130, 0, 16, 0, 5, 0,
1821+ 0, 0, 58, 0, 16, 0,
1822+ 5, 0, 0, 0, 42, 0,
1823+ 16, 0, 6, 0, 0, 0,
1824+ 14, 0, 0, 7, 98, 0,
1825+ 16, 0, 7, 0, 0, 0,
1826+ 6, 1, 16, 0, 6, 0,
1827+ 0, 0, 246, 15, 16, 0,
1828+ 5, 0, 0, 0, 56, 0,
1829+ 0, 10, 50, 0, 16, 0,
1830+ 8, 0, 0, 0, 150, 5,
1831+ 16, 0, 7, 0, 0, 0,
1832+ 2, 64, 0, 0, 202, 242,
1833+ 73, 113, 202, 242, 73, 113,
1834+ 0, 0, 0, 0, 0, 0,
1835+ 0, 0, 56, 0, 0, 7,
1836+ 66, 0, 16, 0, 8, 0,
1837+ 0, 0, 26, 0, 16, 0,
1838+ 5, 0, 0, 0, 1, 64,
1839+ 0, 0, 202, 242, 73, 113,
1840+ 56, 0, 0, 7, 130, 0,
1841+ 16, 0, 5, 0, 0, 0,
1842+ 42, 0, 16, 0, 5, 0,
1843+ 0, 0, 58, 0, 16, 0,
1844+ 5, 0, 0, 0, 14, 0,
1845+ 0, 7, 50, 0, 16, 0,
1846+ 6, 0, 0, 0, 70, 0,
1847+ 16, 0, 6, 0, 0, 0,
1848+ 246, 15, 16, 0, 5, 0,
1849+ 0, 0, 14, 0, 0, 7,
1850+ 66, 0, 16, 0, 6, 0,
1851+ 0, 0, 26, 0, 16, 0,
1852+ 5, 0, 0, 0, 42, 0,
1853+ 16, 0, 5, 0, 0, 0,
1854+ 55, 0, 0, 9, 226, 0,
1855+ 16, 0, 5, 0, 0, 0,
1856+ 6, 0, 16, 0, 7, 0,
1857+ 0, 0, 6, 9, 16, 0,
1858+ 8, 0, 0, 0, 6, 9,
1859+ 16, 0, 6, 0, 0, 0,
1860+ 1, 0, 0, 7, 226, 0,
1861+ 16, 0, 5, 0, 0, 0,
1862+ 86, 14, 16, 0, 5, 0,
1863+ 0, 0, 246, 15, 16, 0,
1864+ 6, 0, 0, 0, 54, 0,
1865+ 0, 5, 34, 0, 16, 0,
1866+ 1, 0, 0, 0, 58, 0,
1867+ 16, 0, 0, 0, 0, 0,
1868+ 50, 0, 0, 12, 50, 0,
1869+ 16, 0, 6, 0, 0, 0,
1870+ 22, 5, 16, 0, 1, 0,
1871+ 0, 0, 2, 64, 0, 0,
1872+ 0, 0, 0, 63, 0, 0,
1873+ 0, 63, 0, 0, 0, 0,
1874+ 0, 0, 0, 0, 150, 5,
1875+ 16, 0, 0, 0, 0, 0,
1876+ 0, 0, 0, 8, 50, 0,
1877+ 16, 0, 6, 0, 0, 0,
1878+ 70, 0, 16, 128, 65, 0,
1879+ 0, 0, 6, 0, 0, 0,
1880+ 70, 16, 16, 0, 1, 0,
1881+ 0, 0, 15, 0, 0, 7,
1882+ 34, 0, 16, 0, 1, 0,
1883+ 0, 0, 70, 0, 16, 0,
1884+ 6, 0, 0, 0, 150, 5,
1885+ 16, 0, 5, 0, 0, 0,
1886+ 0, 32, 0, 7, 34, 0,
1887+ 16, 0, 1, 0, 0, 0,
1888+ 58, 0, 16, 0, 5, 0,
1889+ 0, 0, 26, 0, 16, 0,
1890+ 1, 0, 0, 0, 0, 0,
1891+ 0, 8, 242, 0, 16, 0,
1892+ 6, 0, 0, 0, 70, 30,
1893+ 16, 128, 65, 0, 0, 0,
1894+ 3, 0, 0, 0, 70, 30,
1895+ 16, 0, 4, 0, 0, 0,
1896+ 50, 0, 0, 9, 242, 0,
1897+ 16, 0, 6, 0, 0, 0,
1898+ 86, 5, 16, 0, 1, 0,
1899+ 0, 0, 70, 14, 16, 0,
1900+ 6, 0, 0, 0, 70, 30,
1901+ 16, 0, 3, 0, 0, 0,
1902+ 32, 0, 0, 7, 34, 0,
1903+ 16, 0, 1, 0, 0, 0,
1904+ 10, 0, 16, 0, 5, 0,
1905+ 0, 0, 1, 64, 0, 0,
1906+ 1, 0, 0, 0, 50, 0,
1907+ 0, 9, 18, 0, 16, 0,
1908+ 5, 0, 0, 0, 26, 0,
1909+ 16, 0, 6, 0, 0, 0,
1910+ 1, 64, 0, 0, 201, 236,
1911+ 202, 62, 10, 0, 16, 0,
1912+ 6, 0, 0, 0, 50, 0,
1913+ 0, 9, 18, 0, 16, 0,
1914+ 5, 0, 0, 0, 42, 0,
1915+ 16, 0, 6, 0, 0, 0,
1916+ 1, 64, 0, 0, 169, 251,
1917+ 92, 62, 10, 0, 16, 0,
1918+ 5, 0, 0, 0, 50, 0,
1919+ 0, 10, 34, 0, 16, 0,
1920+ 5, 0, 0, 0, 26, 0,
1921+ 16, 128, 65, 0, 0, 0,
1922+ 6, 0, 0, 0, 1, 64,
1923+ 0, 0, 140, 48, 216, 61,
1924+ 10, 0, 16, 0, 6, 0,
1925+ 0, 0, 50, 0, 0, 10,
1926+ 34, 0, 16, 0, 5, 0,
1927+ 0, 0, 42, 0, 16, 128,
1928+ 65, 0, 0, 0, 6, 0,
1929+ 0, 0, 1, 64, 0, 0,
1930+ 250, 197, 130, 61, 26, 0,
1931+ 16, 0, 5, 0, 0, 0,
1932+ 50, 0, 0, 10, 66, 0,
1933+ 16, 0, 5, 0, 0, 0,
1934+ 26, 0, 16, 128, 65, 0,
1935+ 0, 0, 6, 0, 0, 0,
1936+ 1, 64, 0, 0, 123, 67,
1937+ 183, 61, 10, 0, 16, 0,
1938+ 6, 0, 0, 0, 50, 0,
1939+ 0, 10, 66, 0, 16, 0,
1940+ 5, 0, 0, 0, 42, 0,
1941+ 16, 128, 65, 0, 0, 0,
1942+ 6, 0, 0, 0, 1, 64,
1943+ 0, 0, 102, 79, 165, 63,
1944+ 42, 0, 16, 0, 5, 0,
1945+ 0, 0, 56, 0, 0, 7,
1946+ 130, 0, 16, 0, 5, 0,
1947+ 0, 0, 10, 0, 16, 0,
1948+ 5, 0, 0, 0, 10, 0,
1949+ 16, 0, 5, 0, 0, 0,
1950+ 56, 0, 0, 7, 18, 0,
1951+ 16, 0, 5, 0, 0, 0,
1952+ 10, 0, 16, 0, 5, 0,
1953+ 0, 0, 58, 0, 16, 0,
1954+ 5, 0, 0, 0, 56, 0,
1955+ 0, 7, 130, 0, 16, 0,
1956+ 5, 0, 0, 0, 26, 0,
1957+ 16, 0, 5, 0, 0, 0,
1958+ 26, 0, 16, 0, 5, 0,
1959+ 0, 0, 56, 0, 0, 7,
1960+ 34, 0, 16, 0, 5, 0,
1961+ 0, 0, 26, 0, 16, 0,
1962+ 5, 0, 0, 0, 58, 0,
1963+ 16, 0, 5, 0, 0, 0,
1964+ 56, 0, 0, 7, 130, 0,
1965+ 16, 0, 5, 0, 0, 0,
1966+ 42, 0, 16, 0, 5, 0,
1967+ 0, 0, 42, 0, 16, 0,
1968+ 5, 0, 0, 0, 56, 0,
1969+ 0, 7, 66, 0, 16, 0,
1970+ 5, 0, 0, 0, 42, 0,
1971+ 16, 0, 5, 0, 0, 0,
1972+ 58, 0, 16, 0, 5, 0,
1973+ 0, 0, 56, 0, 0, 10,
1974+ 114, 0, 16, 0, 7, 0,
1975+ 0, 0, 86, 5, 16, 0,
1976+ 5, 0, 0, 0, 2, 64,
1977+ 0, 0, 140, 177, 83, 64,
1978+ 68, 6, 39, 64, 62, 19,
1979+ 52, 63, 0, 0, 0, 0,
1980+ 50, 0, 0, 13, 162, 0,
1981+ 16, 0, 5, 0, 0, 0,
1982+ 6, 0, 16, 0, 5, 0,
1983+ 0, 0, 2, 64, 0, 0,
1984+ 0, 0, 0, 0, 171, 116,
1985+ 130, 64, 0, 0, 0, 0,
1986+ 83, 127, 137, 187, 6, 8,
1987+ 16, 128, 65, 0, 0, 0,
1988+ 7, 0, 0, 0, 50, 0,
1989+ 0, 9, 18, 0, 16, 0,
1990+ 5, 0, 0, 0, 10, 0,
1991+ 16, 0, 5, 0, 0, 0,
1992+ 1, 64, 0, 0, 45, 92,
1993+ 162, 191, 26, 0, 16, 0,
1994+ 7, 0, 0, 0, 50, 0,
1995+ 0, 10, 18, 0, 16, 0,
1996+ 5, 0, 0, 0, 42, 0,
1997+ 16, 128, 65, 0, 0, 0,
1998+ 5, 0, 0, 0, 1, 64,
1999+ 0, 0, 106, 193, 174, 62,
2000+ 10, 0, 16, 0, 5, 0,
crates/client/src/update.rsmodified+1 -0
@@ -93,6 +93,7 @@ static BUILD: LazyLock<Option<Sha>> = LazyLock::new(|| {
93 let exe = crate::exe()?;93 let exe = crate::exe()?;
94 let bytes = std::fs::read(exe).ok()?;94 let bytes = std::fs::read(exe).ok()?;
95 std::hint::black_box(MARK);95 std::hint::black_box(MARK);
96+ std::hint::black_box(common::transport::PROTOCOL_MARK);
96 Some(sha256(&bytes))97 Some(sha256(&bytes))
97 });98 });
98 99
crates/common/src/error.rsmodified+2 -0
@@ -167,4 +167,6 @@ pub enum ReleaseProblem {
167 NotStaged,167 NotStaged,
168 #[error("server binary does not start")]168 #[error("server binary does not start")]
169 ServerBroken,169 ServerBroken,
170+ #[error("a protocol change needs the server and every client in one release")]
171+ ProtocolSplit,
170 }172 }
crates/common/src/transport.rsmodified+9 -1
@@ -13,7 +13,15 @@ use quinn::{
13 use quinn_proto::RttEstimator;13 use quinn_proto::RttEstimator;
14 use socket2::{Domain, Protocol, Socket, Type};14 use socket2::{Domain, Protocol, Socket, Type};
15 15
16-pub const ALPN: &[u8] = b"yumush/5";16+macro_rules! protocol {
17+ () => {
18+ "yumush/6"
19+ };
20+}
21+
22+pub const PROTOCOL: &str = protocol!();
23+pub const ALPN: &[u8] = PROTOCOL.as_bytes();
24+pub const PROTOCOL_MARK: &str = concat!("yumush-protocol:", protocol!(), ";");
17 25
18 const IDLE_TIMEOUT: Duration = Duration::from_secs(10);26 const IDLE_TIMEOUT: Duration = Duration::from_secs(10);
19 pub const KEEP_ALIVE: Duration = Duration::from_secs(1);27 pub const KEEP_ALIVE: Duration = Duration::from_secs(1);
crates/common/src/update.rsmodified+31 -7
@@ -3,6 +3,7 @@ use bitcode::{Decode, Encode};
3 pub const ALPN: &[u8] = b"yumush-update/1";3 pub const ALPN: &[u8] = b"yumush-update/1";
4 pub const FILE_MAX: u64 = 512 << 20;4 pub const FILE_MAX: u64 = 512 << 20;
5 pub const MARK: &str = "yumush-target:";5 pub const MARK: &str = "yumush-target:";
6+pub const PROTOCOL_MARK_PREFIX: &str = "yumush-protocol:";
6 pub const SERVER_TARGET: &str = "server-x86_64-linux";7 pub const SERVER_TARGET: &str = "server-x86_64-linux";
7 pub const SERVER_MARK: &str = "yumush-target:server-x86_64-linux;";8 pub const SERVER_MARK: &str = "yumush-target:server-x86_64-linux;";
8 pub const SERVER_VERSION: &str = "yumush-server";9 pub const SERVER_VERSION: &str = "yumush-server";
@@ -66,8 +67,8 @@ pub fn hex(sha: &Sha) -> String {
66 sha.iter().map(|byte| format!("{byte:02x}")).collect()67 sha.iter().map(|byte| format!("{byte:02x}")).collect()
67 }68 }
68 69
69-pub fn target_of(bytes: &[u8]) -> Option<String> {70+fn marked(bytes: &[u8], mark: &str, valid: fn(&str) -> bool) -> Option<String> {
70- let mark = MARK.as_bytes();71+ let mark = mark.as_bytes();
71 let mut found: Option<String> = None;72 let mut found: Option<String> = None;
72 let mut start = 0;73 let mut start = 0;
73 while let Some(offset) = bytes[start..]74 while let Some(offset) = bytes[start..]
@@ -80,18 +81,22 @@ pub fn target_of(bytes: &[u8]) -> Option<String> {
80 let Some(end) = tail.iter().position(|byte| *byte == b';') else {81 let Some(end) = tail.iter().position(|byte| *byte == b';') else {
81 continue;82 continue;
82 };83 };
83- let Ok(target) = std::str::from_utf8(&tail[..end]) else {84+ let Ok(value) = std::str::from_utf8(&tail[..end]) else {
84 continue;85 continue;
85 };86 };
86- if !valid_target(target) {87+ if !valid(value) {
87 continue;88 continue;
88 }89 }
89 match &found {90 match &found {
90- Some(seen) if seen != target => return None,91+ Some(seen) if seen != value => return None,
91- _ => found = Some(target.to_string()),92+ _ => found = Some(value.to_string()),
92 }93 }
93 }94 }
94- let target = found?;95+ found
96+}
97+
98+pub fn target_of(bytes: &[u8]) -> Option<String> {
99+ let target = marked(bytes, MARK, valid_target)?;
95 let executable = if target.ends_with("-linux") {100 let executable = if target.ends_with("-linux") {
96 bytes.starts_with(b"\x7fELF")101 bytes.starts_with(b"\x7fELF")
97 } else if target.ends_with("-windows") {102 } else if target.ends_with("-windows") {
@@ -102,6 +107,12 @@ pub fn target_of(bytes: &[u8]) -> Option<String> {
102 executable.then_some(target)107 executable.then_some(target)
103 }108 }
104 109
110+pub fn protocol_of(bytes: &[u8]) -> Option<String> {
111+ marked(bytes, PROTOCOL_MARK_PREFIX, |value| {
112+ value.starts_with("yumush/") && valid_target(&value.replace('/', "-"))
113+ })
114+}
115+
105 #[cfg(test)]116 #[cfg(test)]
106 mod tests {117 mod tests {
107 use super::*;118 use super::*;
@@ -118,4 +129,17 @@ mod tests {
118 Some("x86_64_v1-windows")129 Some("x86_64_v1-windows")
119 );130 );
120 }131 }
132+
133+ #[test]
134+ fn finds_protocol() {
135+ let bytes = format!("..{}..", crate::transport::PROTOCOL_MARK);
136+ assert_eq!(
137+ protocol_of(bytes.as_bytes()).as_deref(),
138+ Some(crate::transport::PROTOCOL)
139+ );
140+ assert_eq!(
141+ protocol_of(b"yumush-protocol:yumush/5;yumush-protocol:yumush/6;"),
142+ None
143+ );
144+ }
121 }145 }
crates/server/src/call/release.rsmodified+12 -2
@@ -1,14 +1,16 @@
1 use common::{1 use common::{
2 call::{ListReleases, ListUpdateClients, PublishRelease, SetReleaseRequired},2 call::{ListReleases, ListUpdateClients, PublishRelease, SetReleaseRequired},
3+ error::{Error, ReleaseProblem},
3 event::Event,4 event::Event,
4 model::{AdminAction, ReleaseFile, ReleaseInfo, UpdateClient},5 model::{AdminAction, ReleaseFile, ReleaseInfo, UpdateClient},
5- update::Sha,6+ transport::PROTOCOL,
7+ update::{SERVER_TARGET, Sha},
6 };8 };
7 9
8 use super::{Cx, Handle, Me};10 use super::{Cx, Handle, Me};
9 use crate::{11 use crate::{
10 db::{self, log},12 db::{self, log},
11- error::ServerError,13+ error::{ServerError, ensure_with},
12 publish::To,14 publish::To,
13 };15 };
14 16
@@ -67,6 +69,14 @@ impl Handle for PublishRelease {
67 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ReleaseInfo, ServerError> {69 async fn handle(self, me: Me, cx: &mut Cx<'_>) -> Result<ReleaseInfo, ServerError> {
68 let me = me.user()?;70 let me = me.user()?;
69 let files = cx.sh.releases.staged(&self.files)?;71 let files = cx.sh.releases.staged(&self.files)?;
72+ if cx.sh.releases.protocol(&self.files)? != PROTOCOL {
73+ let released = db::release::targets(cx.db).await?;
74+ let has = |target: &str| files.iter().any(|file| file.target == target);
75+ ensure_with(
76+ has(SERVER_TARGET) && released.iter().all(|target| has(target)),
77+ Error::Release(ReleaseProblem::ProtocolSplit),
78+ )?;
79+ }
70 let releases = cx.sh.releases.clone();80 let releases = cx.sh.releases.clone();
71 let picked = files.clone();81 let picked = files.clone();
72 let next = tokio::task::spawn_blocking(move || releases.prepare_server(&picked)).await??;82 let next = tokio::task::spawn_blocking(move || releases.prepare_server(&picked)).await??;
crates/server/src/db/release.rsmodified+7 -0
@@ -65,6 +65,13 @@ pub async fn live(db: &Connection) -> Result<Vec<Sha>, ServerError> {
65 .await65 .await
66 }66 }
67 67
68+pub async fn targets(db: &Connection) -> Result<Vec<String>, ServerError> {
69+ all(db, "SELECT DISTINCT target FROM release_file", (), |r| {
70+ r.get()
71+ })
72+ .await
73+}
74+
68 pub async fn required_after(seq: u64, db: &Connection) -> Result<Vec<String>, ServerError> {75 pub async fn required_after(seq: u64, db: &Connection) -> Result<Vec<String>, ServerError> {
69 all(76 all(
70 db,77 db,
crates/server/src/main.rsmodified+1 -0
@@ -9,6 +9,7 @@ async fn main() -> Result<(), server::error::ServerError> {
9 .init();9 .init();
10 10
11 std::hint::black_box(common::update::SERVER_MARK);11 std::hint::black_box(common::update::SERVER_MARK);
12+ std::hint::black_box(common::transport::PROTOCOL_MARK);
12 let args: Vec<String> = std::env::args().skip(1).collect();13 let args: Vec<String> = std::env::args().skip(1).collect();
13 match args14 match args
14 .iter()15 .iter()
crates/server/src/update.rsmodified+22 -4
@@ -14,7 +14,7 @@ use common::{
14 time::now_ms,14 time::now_ms,
15 update::{15 update::{
16 Ask, FILE_MAX, Install, Me, Offer, Progress, SERVER_TARGET, SERVER_VERSION, Sha, Status,16 Ask, FILE_MAX, Install, Me, Offer, Progress, SERVER_TARGET, SERVER_VERSION, Sha, Status,
17- hex, sha256, target_of,17+ hex, protocol_of, sha256, target_of,
18 },18 },
19 };19 };
20 use quinn::{Connection, RecvStream, VarInt};20 use quinn::{Connection, RecvStream, VarInt};
@@ -104,7 +104,7 @@ pub struct Seen {
104 #[derive(Clone, Default)]104 #[derive(Clone, Default)]
105 pub struct Releases {105 pub struct Releases {
106 directory: PathBuf,106 directory: PathBuf,
107- staged: Arc<Mutex<HashMap<Sha, Staged>>>,107+ staged: Arc<Mutex<HashMap<Sha, (Staged, String)>>>,
108 board: Arc<Mutex<HashMap<Install, Seen>>>,108 board: Arc<Mutex<HashMap<Install, Seen>>>,
109 }109 }
110 110
@@ -190,6 +190,8 @@ impl Releases {
190 190
191 let file = sha256(&bytes);191 let file = sha256(&bytes);
192 let target = target_of(&bytes).ok_or(CommonError::Release(ReleaseProblem::NotClient))?;192 let target = target_of(&bytes).ok_or(CommonError::Release(ReleaseProblem::NotClient))?;
193+ let protocol =
194+ protocol_of(&bytes).ok_or(CommonError::Release(ReleaseProblem::NotClient))?;
193 if let Some(seq) = db195 if let Some(seq) = db
194 .run(async |conn| db::release::seq_of(&file, conn).await)196 .run(async |conn| db::release::seq_of(&file, conn).await)
195 .await?197 .await?
@@ -210,7 +212,10 @@ impl Releases {
210 size,212 size,
211 packed,213 packed,
212 };214 };
213- self.staged.lock().unwrap().insert(file, staged.clone());215+ self.staged
216+ .lock()
217+ .unwrap()
218+ .insert(file, (staged.clone(), protocol));
214 219
215 Ok(staged)220 Ok(staged)
216 }221 }
@@ -225,7 +230,7 @@ impl Releases {
225 .iter()230 .iter()
226 .map(|file| {231 .map(|file| {
227 map.get(file)232 map.get(file)
228- .cloned()233+ .map(|(staged, _)| staged.clone())
229 .ok_or(CommonError::Release(ReleaseProblem::NotStaged))234 .ok_or(CommonError::Release(ReleaseProblem::NotStaged))
230 })235 })
231 .collect::<Result<Vec<_>, _>>()?;236 .collect::<Result<Vec<_>, _>>()?;
@@ -239,6 +244,19 @@ impl Releases {
239 Ok(picked)244 Ok(picked)
240 }245 }
241 246
247+ pub fn protocol(&self, files: &[Sha]) -> Result<String, ServerError> {
248+ let map = self.staged.lock().unwrap();
249+ let protocols: std::collections::HashSet<&str> = files
250+ .iter()
251+ .filter_map(|file| map.get(file))
252+ .map(|(_, protocol)| protocol.as_str())
253+ .collect();
254+ match protocols.into_iter().collect::<Vec<_>>()[..] {
255+ [protocol] => Ok(protocol.to_string()),
256+ _ => Err(CommonError::Release(ReleaseProblem::ProtocolSplit).into()),
257+ }
258+ }
259+
242 pub fn prepare_server(&self, staged: &[Staged]) -> Result<Option<NextServer>, ServerError> {260 pub fn prepare_server(&self, staged: &[Staged]) -> Result<Option<NextServer>, ServerError> {
243 let Some(server) = staged.iter().find(|staged| staged.target == SERVER_TARGET) else {261 let Some(server) = staged.iter().find(|staged| staged.target == SERVER_TARGET) else {
244 return Ok(None);262 return Ok(None);
vendor/gpui-pre-windows/Cargo.tomladded+227 -0
@@ -0,0 +1,227 @@
1+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
2+#
3+# When uploading crates to the registry Cargo will automatically
4+# "normalize" Cargo.toml files for maximal compatibility
5+# with all versions of Cargo and also rewrite `path` dependencies
6+# to registry (e.g., crates.io) dependencies.
7+#
8+# If you are reading this file be aware that the original Cargo.toml
9+# will likely look very different (and much more reasonable).
10+# See Cargo.toml.orig for the original contents.
11+
12+[package]
13+edition = "2024"
14+name = "gpui-pre-windows"
15+version = "0.3.14"
16+build = "build.rs"
17+publish = true
18+autolib = false
19+autobins = false
20+autoexamples = false
21+autotests = false
22+autobenches = false
23+description = "Zed's `gpui_windows` crate (gpui-pre snapshot of zed@f126950)"
24+readme = false
25+license = "Apache-2.0"
26+repository = "https://github.com/zed-industries/zed"
27+resolver = "2"
28+
29+[package.metadata.cargo-shear]
30+ignored = ["scap"]
31+
32+[package.metadata.gpui-pre]
33+zed-crate = "gpui_windows"
34+zed-version = "0.1.0"
35+zed-rev = "f126950f9d3b62666f97437ae5d4ccac2272c4db"
36+
37+[features]
38+default = ["gpui/default"]
39+screen-capture = [
40+ "gpui/screen-capture",
41+ "scap",
42+]
43+test-support = ["gpui/test-support"]
44+
45+[lib]
46+name = "gpui_windows"
47+path = "src/gpui_windows.rs"
48+doctest = false
49+
50+[target.'cfg(target_os = "windows")'.dependencies.accesskit]
51+version = "0.24.0"
52+features = ["enumn"]
53+
54+[target.'cfg(target_os = "windows")'.dependencies.accesskit_windows]
55+version = "0.34"
56+
57+[target.'cfg(target_os = "windows")'.dependencies.anyhow]
58+version = "1.0.86"
59+
60+[target.'cfg(target_os = "windows")'.dependencies.collections]
61+version = "=0.3.14"
62+package = "gpui-pre-collections"
63+
64+[target.'cfg(target_os = "windows")'.dependencies.dunce]
65+version = "1.0"
66+
67+[target.'cfg(target_os = "windows")'.dependencies.etagere]
68+version = "0.2"
69+
70+[target.'cfg(target_os = "windows")'.dependencies.futures]
71+version = "0.3.34"
72+
73+[target.'cfg(target_os = "windows")'.dependencies.gpui]
74+version = "=0.3.14"
75+default-features = false
76+package = "gpui-pre"
77+
78+[target.'cfg(target_os = "windows")'.dependencies.gpui_util]
79+version = "=0.3.14"
80+package = "gpui-pre-util"
81+
82+[target.'cfg(target_os = "windows")'.dependencies.image]
83+version = "0.25.1"
84+features = [
85+ "bmp",
86+ "dds",
87+ "exr",
88+ "ff",
89+ "gif",
90+ "hdr",
91+ "ico",
92+ "jpeg",
93+ "png",
94+ "pnm",
95+ "qoi",
96+ "rayon",
97+ "tga",
98+ "tiff",
99+ "webp",
100+]
101+default-features = false
102+
103+[target.'cfg(target_os = "windows")'.dependencies.itertools]
104+version = "0.14.0"
105+
106+[target.'cfg(target_os = "windows")'.dependencies.log]
107+version = "0.4"
108+features = ["std"]
109+default-features = false
110+
111+[target.'cfg(target_os = "windows")'.dependencies.parking_lot]
112+version = "0.12.1"
113+
114+[target.'cfg(target_os = "windows")'.dependencies.rand]
115+version = "0.9"
116+features = [
117+ "std",
118+ "std_rng",
119+ "os_rng",
120+]
121+default-features = false
122+
123+[target.'cfg(target_os = "windows")'.dependencies.raw-window-handle]
124+version = "0.6"
125+
126+[target.'cfg(target_os = "windows")'.dependencies.scap]
127+version = "0.0.8-zed"
128+optional = true
129+default-features = false
130+package = "zed-scap"
131+
132+[target.'cfg(target_os = "windows")'.dependencies.scheduler]
133+version = "=0.3.14"
134+package = "gpui-pre-scheduler"
135+
136+[target.'cfg(target_os = "windows")'.dependencies.smallvec]
137+version = "1.6"
138+features = [
139+ "union",
140+ "const_new",
141+]
142+
143+[target.'cfg(target_os = "windows")'.dependencies.uuid]
144+version = "1.1"
145+features = [
146+ "serde",
147+ "v5",
148+]
149+
150+[target.'cfg(target_os = "windows")'.dependencies.windows]
151+version = "0.62"
152+features = [
153+ "Win32_Foundation",
154+ "Win32_Graphics_Gdi",
155+ "Win32_Security",
156+ "Win32_Storage_FileSystem",
157+ "Win32_System_Com",
158+ "Win32_System_Com_StructuredStorage",
159+ "Win32_System_IO",
160+ "Win32_System_LibraryLoader",
161+ "Win32_System_Ole",
162+ "Win32_System_Threading",
163+ "Win32_System_Variant",
164+ "Win32_UI_Shell",
165+ "Win32_UI_Shell_Common",
166+ "Win32_UI_Shell_PropertiesSystem",
167+ "Win32_UI_WindowsAndMessaging",
168+ "Data_Xml_Dom",
169+ "UI_Notifications",
170+ "UI_ViewManagement",
171+ "Wdk_System_SystemServices",
172+ "Win32_Graphics_Direct3D11",
173+ "Win32_Graphics_Direct3D_Fxc",
174+ "Win32_Graphics_DirectComposition",
175+ "Win32_Graphics_DirectManipulation",
176+ "Win32_Graphics_DirectWrite",
177+ "Win32_Graphics_Dwm",
178+ "Win32_Graphics_Dxgi_Common",
179+ "Win32_Graphics_Hlsl",
180+ "Win32_Media",
181+ "Win32_Security_Credentials",
182+ "Win32_Storage_Packaging_Appx",
183+ "Win32_System_DataExchange",
184+ "Win32_System_Diagnostics_Debug",
185+ "Win32_System_Memory",
186+ "Win32_System_Performance",
187+ "Win32_System_StationsAndDesktops",
188+ "Win32_System_SystemInformation",
189+ "Win32_System_SystemServices",
190+ "Win32_UI_Controls",
191+ "Win32_UI_HiDpi",
192+ "Win32_UI_Input_Ime",
193+ "Win32_UI_Input_Pointer",
194+]
195+
196+[target.'cfg(target_os = "windows")'.dependencies.windows-core]
197+version = "0.62"
198+
199+[target.'cfg(target_os = "windows")'.dependencies.windows-numerics]
200+version = "0.3"
201+
202+[target.'cfg(target_os = "windows")'.dependencies.windows-registry]
203+version = "0.6.0"
204+
205+[target.'cfg(target_os = "windows")'.build-dependencies.windows-registry]
206+version = "0.6.0"
207+
208+[lints.clippy]
209+dbg_macro = "deny"
210+declare_interior_mutable_const = "deny"
211+disallowed_methods = "deny"
212+large_enum_variant = "allow"
213+let_underscore_future = "allow"
214+nonminimal_bool = "allow"
215+redundant_clone = "deny"
216+single_range_in_vec_init = "allow"
217+todo = "deny"
218+too_many_arguments = "allow"
219+type_complexity = "allow"
220+
221+[lints.clippy.style]
222+level = "allow"
223+priority = -1
224+
225+[lints.rust.unexpected_cfgs]
226+level = "allow"
227+priority = 0
vendor/gpui-pre-windows/LICENSE-APACHEadded+222 -0
@@ -0,0 +1,222 @@
1+Copyright 2022 - 2025 Zed Industries, Inc.
2+
3+
4+ Licensed under the Apache License, Version 2.0 (the "License");
5+ you may not use this file except in compliance with the License.
6+ You may obtain a copy of the License at
7+
8+
9+ http://www.apache.org/licenses/LICENSE-2.0
10+
11+
12+ Unless required by applicable law or agreed to in writing, software
13+ distributed under the License is distributed on an "AS IS" BASIS,
14+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+ See the License for the specific language governing permissions and
16+ limitations under the License.
17+
18+
19+
20+
21+Apache License
22+ Version 2.0, January 2004
23+ http://www.apache.org/licenses/
24+
25+
26+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
27+
28+
29+ 1. Definitions.
30+
31+
32+ "License" shall mean the terms and conditions for use, reproduction,
33+ and distribution as defined by Sections 1 through 9 of this document.
34+
35+
36+ "Licensor" shall mean the copyright owner or entity authorized by
37+ the copyright owner that is granting the License.
38+
39+
40+ "Legal Entity" shall mean the union of the acting entity and all
41+ other entities that control, are controlled by, or are under common
42+ control with that entity. For the purposes of this definition,
43+ "control" means (i) the power, direct or indirect, to cause the
44+ direction or management of such entity, whether by contract or
45+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
46+ outstanding shares, or (iii) beneficial ownership of such entity.
47+
48+
49+ "You" (or "Your") shall mean an individual or Legal Entity
50+ exercising permissions granted by this License.
51+
52+
53+ "Source" form shall mean the preferred form for making modifications,
54+ including but not limited to software source code, documentation
55+ source, and configuration files.
56+
57+
58+ "Object" form shall mean any form resulting from mechanical
59+ transformation or translation of a Source form, including but
60+ not limited to compiled object code, generated documentation,
61+ and conversions to other media types.
62+
63+
64+ "Work" shall mean the work of authorship, whether in Source or
65+ Object form, made available under the License, as indicated by a
66+ copyright notice that is included in or attached to the work
67+ (an example is provided in the Appendix below).
68+
69+
70+ "Derivative Works" shall mean any work, whether in Source or Object
71+ form, that is based on (or derived from) the Work and for which the
72+ editorial revisions, annotations, elaborations, or other modifications
73+ represent, as a whole, an original work of authorship. For the purposes
74+ of this License, Derivative Works shall not include works that remain
75+ separable from, or merely link (or bind by name) to the interfaces of,
76+ the Work and Derivative Works thereof.
77+
78+
79+ "Contribution" shall mean any work of authorship, including
80+ the original version of the Work and any modifications or additions
81+ to that Work or Derivative Works thereof, that is intentionally
82+ submitted to Licensor for inclusion in the Work by the copyright owner
83+ or by an individual or Legal Entity authorized to submit on behalf of
84+ the copyright owner. For the purposes of this definition, "submitted"
85+ means any form of electronic, verbal, or written communication sent
86+ to the Licensor or its representatives, including but not limited to
87+ communication on electronic mailing lists, source code control systems,
88+ and issue tracking systems that are managed by, or on behalf of, the
89+ Licensor for the purpose of discussing and improving the Work, but
90+ excluding communication that is conspicuously marked or otherwise
91+ designated in writing by the copyright owner as "Not a Contribution."
92+
93+
94+ "Contributor" shall mean Licensor and any individual or Legal Entity
95+ on behalf of whom a Contribution has been received by Licensor and
96+ subsequently incorporated within the Work.
97+
98+
99+ 2. Grant of Copyright License. Subject to the terms and conditions of
100+ this License, each Contributor hereby grants to You a perpetual,
101+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
102+ copyright license to reproduce, prepare Derivative Works of,
103+ publicly display, publicly perform, sublicense, and distribute the
104+ Work and such Derivative Works in Source or Object form.
105+
106+
107+ 3. Grant of Patent License. Subject to the terms and conditions of
108+ this License, each Contributor hereby grants to You a perpetual,
109+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
110+ (except as stated in this section) patent license to make, have made,
111+ use, offer to sell, sell, import, and otherwise transfer the Work,
112+ where such license applies only to those patent claims licensable
113+ by such Contributor that are necessarily infringed by their
114+ Contribution(s) alone or by combination of their Contribution(s)
115+ with the Work to which such Contribution(s) was submitted. If You
116+ institute patent litigation against any entity (including a
117+ cross-claim or counterclaim in a lawsuit) alleging that the Work
118+ or a Contribution incorporated within the Work constitutes direct
119+ or contributory patent infringement, then any patent licenses
120+ granted to You under this License for that Work shall terminate
121+ as of the date such litigation is filed.
122+
123+
124+ 4. Redistribution. You may reproduce and distribute copies of the
125+ Work or Derivative Works thereof in any medium, with or without
126+ modifications, and in Source or Object form, provided that You
127+ meet the following conditions:
128+
129+
130+ (a) You must give any other recipients of the Work or
131+ Derivative Works a copy of this License; and
132+
133+
134+ (b) You must cause any modified files to carry prominent notices
135+ stating that You changed the files; and
136+
137+
138+ (c) You must retain, in the Source form of any Derivative Works
139+ that You distribute, all copyright, patent, trademark, and
140+ attribution notices from the Source form of the Work,
141+ excluding those notices that do not pertain to any part of
142+ the Derivative Works; and
143+
144+
145+ (d) If the Work includes a "NOTICE" text file as part of its
146+ distribution, then any Derivative Works that You distribute must
147+ include a readable copy of the attribution notices contained
148+ within such NOTICE file, excluding those notices that do not
149+ pertain to any part of the Derivative Works, in at least one
150+ of the following places: within a NOTICE text file distributed
151+ as part of the Derivative Works; within the Source form or
152+ documentation, if provided along with the Derivative Works; or,
153+ within a display generated by the Derivative Works, if and
154+ wherever such third-party notices normally appear. The contents
155+ of the NOTICE file are for informational purposes only and
156+ do not modify the License. You may add Your own attribution
157+ notices within Derivative Works that You distribute, alongside
158+ or as an addendum to the NOTICE text from the Work, provided
159+ that such additional attribution notices cannot be construed
160+ as modifying the License.
161+
162+
163+ You may add Your own copyright statement to Your modifications and
164+ may provide additional or different license terms and conditions
165+ for use, reproduction, or distribution of Your modifications, or
166+ for any such Derivative Works as a whole, provided Your use,
167+ reproduction, and distribution of the Work otherwise complies with
168+ the conditions stated in this License.
169+
170+
171+ 5. Submission of Contributions. Unless You explicitly state otherwise,
172+ any Contribution intentionally submitted for inclusion in the Work
173+ by You to the Licensor shall be under the terms and conditions of
174+ this License, without any additional terms or conditions.
175+ Notwithstanding the above, nothing herein shall supersede or modify
176+ the terms of any separate license agreement you may have executed
177+ with Licensor regarding such Contributions.
178+
179+
180+ 6. Trademarks. This License does not grant permission to use the trade
181+ names, trademarks, service marks, or product names of the Licensor,
182+ except as required for reasonable and customary use in describing the
183+ origin of the Work and reproducing the content of the NOTICE file.
184+
185+
186+ 7. Disclaimer of Warranty. Unless required by applicable law or
187+ agreed to in writing, Licensor provides the Work (and each
188+ Contributor provides its Contributions) on an "AS IS" BASIS,
189+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
190+ implied, including, without limitation, any warranties or conditions
191+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
192+ PARTICULAR PURPOSE. You are solely responsible for determining the
193+ appropriateness of using or redistributing the Work and assume any
194+ risks associated with Your exercise of permissions under this License.
195+
196+
197+ 8. Limitation of Liability. In no event and under no legal theory,
198+ whether in tort (including negligence), contract, or otherwise,
199+ unless required by applicable law (such as deliberate and grossly
200+ negligent acts) or agreed to in writing, shall any Contributor be
201+ liable to You for damages, including any direct, indirect, special,
202+ incidental, or consequential damages of any character arising as a
203+ result of this License or out of the use or inability to use the
204+ Work (including but not limited to damages for loss of goodwill,
205+ work stoppage, computer failure or malfunction, or any and all
206+ other commercial damages or losses), even if such Contributor
207+ has been advised of the possibility of such damages.
208+
209+
210+ 9. Accepting Warranty or Additional Liability. While redistributing
211+ the Work or Derivative Works thereof, You may choose to offer,
212+ and charge a fee for, acceptance of support, warranty, indemnity,
213+ or other liability obligations and/or rights consistent with this
214+ License. However, in accepting such obligations, You may act only
215+ on Your own behalf and on Your sole responsibility, not on behalf
216+ of any other Contributor, and only if You agree to indemnify,
217+ defend, and hold each Contributor harmless for any liability
218+ incurred by, or claims asserted against, such Contributor by reason
219+ of your accepting any such warranty or additional liability.
220+
221+
222+ END OF TERMS AND CONDITIONS
vendor/gpui-pre-windows/build.rsadded+256 -0
@@ -0,0 +1,256 @@
1+#![allow(clippy::disallowed_methods, reason = "build scripts are exempt")]
2+
3+use std::{env, fs, path::PathBuf};
4+
5+/// Release builds that target Windows embed precompiled HLSL shaders.
6+///
7+/// On Windows they are compiled with `fxc.exe`. Other hosts (e.g. cross-compiling
8+/// with `cargo-xwin`) have no `fxc.exe`, so set `GPUI_SHADERS_BYTES` to the
9+/// `shaders_bytes.rs` produced by a Windows build from the same `shaders.hlsl`.
10+fn main() {
11+ println!("cargo:rerun-if-changed=build.rs");
12+ println!("cargo:rerun-if-env-changed=GPUI_SHADERS_BYTES");
13+
14+ let targets_windows = env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "windows");
15+ let debug_assertions = env::var_os("CARGO_CFG_DEBUG_ASSERTIONS").is_some();
16+ if !targets_windows || debug_assertions {
17+ return;
18+ }
19+
20+ if let Ok(path) = env::var("GPUI_SHADERS_BYTES") {
21+ println!("cargo:rerun-if-changed={path}");
22+ let out = PathBuf::from(env::var("OUT_DIR").unwrap()).join("shaders_bytes.rs");
23+ fs::copy(&path, &out)
24+ .unwrap_or_else(|e| panic!("Failed to copy GPUI_SHADERS_BYTES ({path}): {e}"));
25+ return;
26+ }
27+
28+ #[cfg(windows)]
29+ compile_shaders();
30+
31+ #[cfg(not(windows))]
32+ panic!(
33+ "Release builds for Windows compile shaders with fxc.exe, which only runs on Windows. \
34+ Set GPUI_SHADERS_BYTES to a shaders_bytes.rs taken from a Windows build's OUT_DIR."
35+ );
36+}
37+
38+#[cfg(windows)]
39+mod shader_compilation {
40+ use std::{
41+ fs,
42+ io::Write,
43+ path::{Path, PathBuf},
44+ process::{self, Command},
45+ };
46+
47+ pub fn compile_shaders() {
48+ let shader_path =
49+ PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("src/shaders.hlsl");
50+ let out_dir = std::env::var("OUT_DIR").unwrap();
51+
52+ println!("cargo:rerun-if-changed={}", shader_path.display());
53+
54+ // Check if fxc.exe is available
55+ let fxc_path = find_fxc_compiler();
56+
57+ // Define all modules
58+ let modules = [
59+ "quad",
60+ "opaque_quad",
61+ "shadow",
62+ "path_tile",
63+ "underline",
64+ "monochrome_sprite",
65+ "subpixel_sprite",
66+ "polychrome_sprite",
67+ ];
68+
69+ let rust_binding_path = format!("{}/shaders_bytes.rs", out_dir);
70+ if Path::new(&rust_binding_path).exists() {
71+ fs::remove_file(&rust_binding_path)
72+ .expect("Failed to remove existing Rust binding file");
73+ }
74+ for module in modules {
75+ compile_shader_for_module(
76+ module,
77+ &out_dir,
78+ &fxc_path,
79+ shader_path.to_str().unwrap(),
80+ &rust_binding_path,
81+ );
82+ }
83+ }
84+
85+ /// Locate `binary` in the newest installed Windows SDK.
86+ pub fn find_latest_windows_sdk_binary(
87+ binary: &str,
88+ ) -> Result<Option<PathBuf>, Box<dyn std::error::Error>> {
89+ let key = windows_registry::LOCAL_MACHINE
90+ .open("SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SDKs\\Windows\\v10.0")?;
91+
92+ let install_folder: String = key.get_string("InstallationFolder")?; // "C:\Program Files (x86)\Windows Kits\10\"
93+ let install_folder_bin = Path::new(&install_folder).join("bin");
94+
95+ let mut versions: Vec<_> = std::fs::read_dir(&install_folder_bin)?
96+ .flatten()
97+ .filter(|entry| entry.path().is_dir())
98+ .filter_map(|entry| entry.file_name().into_string().ok())
99+ .collect();
100+
101+ versions.sort_by_key(|s| {
102+ s.split('.')
103+ .filter_map(|p| p.parse().ok())
104+ .collect::<Vec<u32>>()
105+ });
106+
107+ let arch = match std::env::consts::ARCH {
108+ "x86_64" => "x64",
109+ "aarch64" => "arm64",
110+ _ => Err(format!(
111+ "Unsupported architecture: {}",
112+ std::env::consts::ARCH
113+ ))?,
114+ };
115+
116+ if let Some(highest_version) = versions.last() {
117+ return Ok(Some(
118+ install_folder_bin
119+ .join(highest_version)
120+ .join(arch)
121+ .join(binary),
122+ ));
123+ }
124+
125+ Ok(None)
126+ }
127+
128+ /// You can set the `GPUI_FXC_PATH` environment variable to specify the path to the fxc.exe compiler.
129+ fn find_fxc_compiler() -> String {
130+ // Check environment variable
131+ if let Ok(path) = std::env::var("GPUI_FXC_PATH")
132+ && Path::new(&path).exists()
133+ {
134+ return path;
135+ }
136+
137+ // Try to find in PATH
138+ // NOTE: This has to be `where.exe` on Windows, not `where`, it must be ended with `.exe`
139+ if let Ok(output) = std::process::Command::new("where.exe")
140+ .arg("fxc.exe")
141+ .output()
142+ && output.status.success()
143+ {
144+ let path = String::from_utf8_lossy(&output.stdout);
145+ return path.trim().to_string();
146+ }
147+
148+ if let Ok(Some(path)) = find_latest_windows_sdk_binary("fxc.exe") {
149+ return path.to_string_lossy().into_owned();
150+ }
151+
152+ panic!("Failed to find fxc.exe");
153+ }
154+
155+ fn compile_shader_for_module(
156+ module: &str,
157+ out_dir: &str,
158+ fxc_path: &str,
159+ shader_path: &str,
160+ rust_binding_path: &str,
161+ ) {
162+ // Compile vertex shader
163+ let output_file = format!("{}/{}_vs.h", out_dir, module);
164+ let const_name = format!("{}_VERTEX_BYTES", module.to_uppercase());
165+ compile_shader_impl(
166+ fxc_path,
167+ &format!("{module}_vertex"),
168+ &output_file,
169+ &const_name,
170+ shader_path,
171+ "vs_4_1",
172+ );
173+ generate_rust_binding(&const_name, &output_file, rust_binding_path);
174+
175+ // Compile fragment shader
176+ let output_file = format!("{}/{}_ps.h", out_dir, module);
177+ let const_name = format!("{}_FRAGMENT_BYTES", module.to_uppercase());
178+ compile_shader_impl(
179+ fxc_path,
180+ &format!("{module}_fragment"),
181+ &output_file,
182+ &const_name,
183+ shader_path,
184+ "ps_4_1",
185+ );
186+ generate_rust_binding(&const_name, &output_file, rust_binding_path);
187+ }
188+
189+ fn compile_shader_impl(
190+ fxc_path: &str,
191+ entry_point: &str,
192+ output_path: &str,
193+ var_name: &str,
194+ shader_path: &str,
195+ target: &str,
196+ ) {
197+ let output = Command::new(fxc_path)
198+ .args([
199+ "/T",
200+ target,
201+ "/E",
202+ entry_point,
203+ "/Fh",
204+ output_path,
205+ "/Vn",
206+ var_name,
207+ "/O3",
208+ shader_path,
209+ ])
210+ .output();
211+
212+ match output {
213+ Ok(result) => {
214+ if result.status.success() {
215+ return;
216+ }
217+ println!(
218+ "cargo::error=Shader compilation failed for {}:\n{}",
219+ entry_point,
220+ String::from_utf8_lossy(&result.stderr)
221+ );
222+ process::exit(1);
223+ }
224+ Err(e) => {
225+ println!("cargo::error=Failed to run fxc for {}: {}", entry_point, e);
226+ process::exit(1);
227+ }
228+ }
229+ }
230+
231+ fn generate_rust_binding(const_name: &str, head_file: &str, output_path: &str) {
232+ let header_content = fs::read_to_string(head_file).expect("Failed to read header file");
233+ let const_definition = {
234+ let global_var_start = header_content.find("const BYTE").unwrap();
235+ let global_var = &header_content[global_var_start..];
236+ let equal = global_var.find('=').unwrap();
237+ global_var[equal + 1..].trim()
238+ };
239+ let rust_binding = format!(
240+ "const {}: &[u8] = &{}\n",
241+ const_name,
242+ const_definition.replace('{', "[").replace('}', "]")
243+ );
244+ let mut options = fs::OpenOptions::new()
245+ .create(true)
246+ .append(true)
247+ .open(output_path)
248+ .expect("Failed to open Rust binding file");
249+ options
250+ .write_all(rust_binding.as_bytes())
251+ .expect("Failed to write Rust binding file");
252+ }
253+}
254+
255+#[cfg(windows)]
256+use shader_compilation::compile_shaders;
vendor/gpui-pre-windows/src/alpha_correction.hlsladded+49 -0
@@ -0,0 +1,49 @@
1+// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.hlsl
2+// Copyright (c) Microsoft Corporation.
3+// Licensed under the MIT license.
4+
5+float color_brightness(float3 color) {
6+ // REC. 601 luminance coefficients for perceived brightness
7+ return dot(color, float3(0.30f, 0.59f, 0.11f));
8+}
9+
10+float light_on_dark_contrast(float enhancedContrast, float3 color) {
11+ float brightness = color_brightness(color);
12+ float multiplier = saturate(4.0f * (0.75f - brightness));
13+ return enhancedContrast * multiplier;
14+}
15+
16+float enhance_contrast(float alpha, float k) {
17+ return alpha * (k + 1.0f) / (alpha * k + 1.0f);
18+}
19+
20+float3 enhance_contrast3(float3 alpha, float k) {
21+ return alpha * (k + 1.0f) / (alpha * k + 1.0f);
22+}
23+
24+float apply_alpha_correction(float a, float b, float4 g) {
25+ float brightness_adjustment = g.x * b + g.y;
26+ float correction = brightness_adjustment * a + (g.z * b + g.w);
27+ return a + a * (1.0f - a) * correction;
28+}
29+
30+float3 apply_alpha_correction3(float3 a, float3 b, float4 g) {
31+ float3 brightness_adjustment = g.x * b + g.y;
32+ float3 correction = brightness_adjustment * a + (g.z * b + g.w);
33+ return a + a * (1.0f - a) * correction;
34+}
35+
36+float apply_contrast_and_gamma_correction(float sample, float3 color, float enhanced_contrast_factor, float4 gamma_ratios) {
37+ float enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);
38+ float brightness = color_brightness(color);
39+
40+ float contrasted = enhance_contrast(sample, enhanced_contrast);
41+ return apply_alpha_correction(contrasted, brightness, gamma_ratios);
42+}
43+
44+float3 apply_contrast_and_gamma_correction3(float3 sample, float3 color, float enhanced_contrast_factor, float4 gamma_ratios) {
45+ float enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);
46+
47+ float3 contrasted = enhance_contrast3(sample, enhanced_contrast);
48+ return apply_alpha_correction3(contrasted, color, gamma_ratios);
49+}
vendor/gpui-pre-windows/src/clipboard.rsadded+402 -0
@@ -0,0 +1,402 @@
1+use std::sync::LazyLock;
2+
3+use anyhow::Result;
4+use collections::FxHashMap;
5+use itertools::Itertools;
6+use windows::Win32::{
7+ Foundation::{HANDLE, HGLOBAL},
8+ System::{
9+ DataExchange::{
10+ CloseClipboard, CountClipboardFormats, EmptyClipboard, EnumClipboardFormats,
11+ GetClipboardData, GetClipboardFormatNameW, OpenClipboard, RegisterClipboardFormatW,
12+ SetClipboardData,
13+ },
14+ Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock},
15+ Ole::{CF_DIB, CF_HDROP, CF_UNICODETEXT},
16+ },
17+ UI::Shell::{DragQueryFileW, HDROP},
18+};
19+use windows::core::{Owned, PCWSTR};
20+
21+use gpui::{
22+ ClipboardEntry, ClipboardItem, ClipboardString, ExternalPaths, Image, ImageFormat, hash,
23+};
24+
25+const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
26+
27+static CLIPBOARD_HASH_FORMAT: LazyLock<u32> =
28+ LazyLock::new(|| register_clipboard_format(windows::core::w!("GPUI internal text hash")));
29+static CLIPBOARD_METADATA_FORMAT: LazyLock<u32> =
30+ LazyLock::new(|| register_clipboard_format(windows::core::w!("GPUI internal metadata")));
31+static CLIPBOARD_SVG_FORMAT: LazyLock<u32> =
32+ LazyLock::new(|| register_clipboard_format(windows::core::w!("image/svg+xml")));
33+static CLIPBOARD_GIF_FORMAT: LazyLock<u32> =
34+ LazyLock::new(|| register_clipboard_format(windows::core::w!("GIF")));
35+static CLIPBOARD_PNG_FORMAT: LazyLock<u32> =
36+ LazyLock::new(|| register_clipboard_format(windows::core::w!("PNG")));
37+static CLIPBOARD_JPG_FORMAT: LazyLock<u32> =
38+ LazyLock::new(|| register_clipboard_format(windows::core::w!("JFIF")));
39+
40+static IMAGE_FORMATS_MAP: LazyLock<FxHashMap<u32, ImageFormat>> = LazyLock::new(|| {
41+ let mut map = FxHashMap::default();
42+ map.insert(*CLIPBOARD_PNG_FORMAT, ImageFormat::Png);
43+ map.insert(*CLIPBOARD_GIF_FORMAT, ImageFormat::Gif);
44+ map.insert(*CLIPBOARD_JPG_FORMAT, ImageFormat::Jpeg);
45+ map.insert(*CLIPBOARD_SVG_FORMAT, ImageFormat::Svg);
46+ map
47+});
48+
49+fn register_clipboard_format(format: PCWSTR) -> u32 {
50+ let ret = unsafe { RegisterClipboardFormatW(format) };
51+ if ret == 0 {
52+ panic!(
53+ "Error when registering clipboard format: {}",
54+ std::io::Error::last_os_error()
55+ );
56+ }
57+ log::debug!(
58+ "Registered clipboard format {} as {}",
59+ unsafe { format.display() },
60+ ret
61+ );
62+ ret
63+}
64+
65+fn get_clipboard_data(format: u32) -> Option<LockedGlobal> {
66+ let global = HGLOBAL(unsafe { GetClipboardData(format).ok() }?.0);
67+ LockedGlobal::lock(global)
68+}
69+
70+pub(crate) fn write_to_clipboard(item: ClipboardItem) {
71+ let Some(_clip) = ClipboardGuard::open() else {
72+ return;
73+ };
74+
75+ let result: Result<()> = (|| {
76+ unsafe { EmptyClipboard()? };
77+ for entry in item.entries() {
78+ match entry {
79+ ClipboardEntry::String(string) => write_string(string)?,
80+ ClipboardEntry::Image(image) => write_image(image)?,
81+ ClipboardEntry::ExternalPaths(_) => {}
82+ }
83+ }
84+ Ok(())
85+ })();
86+
87+ if let Err(e) = result {
88+ log::error!("Failed to write to clipboard: {e}");
89+ }
90+}
91+
92+pub(crate) fn read_from_clipboard() -> Option<ClipboardItem> {
93+ let _clip = ClipboardGuard::open()?;
94+
95+ let mut entries = Vec::new();
96+ let mut have_text = false;
97+ let mut have_image = false;
98+ let mut have_files = false;
99+
100+ let count = unsafe { CountClipboardFormats() };
101+ let mut format = 0;
102+ for _ in 0..count {
103+ format = unsafe { EnumClipboardFormats(format) };
104+
105+ if !have_text && format == CF_UNICODETEXT.0 as u32 {
106+ if let Some(entry) = read_string() {
107+ entries.push(entry);
108+ have_text = true;
109+ }
110+ } else if !have_image && is_image_format(format) {
111+ if let Some(entry) = read_image(format) {
112+ entries.push(entry);
113+ have_image = true;
114+ }
115+ } else if !have_files && format == CF_HDROP.0 as u32 {
116+ if let Some(entry) = read_files() {
117+ entries.push(entry);
118+ have_files = true;
119+ }
120+ }
121+ }
122+
123+ if entries.is_empty() {
124+ log_unsupported_clipboard_formats();
125+ return None;
126+ }
127+ Some(ClipboardItem { entries })
128+}
129+
130+pub(crate) fn with_file_names<F>(hdrop: HDROP, mut f: F)
131+where
132+ F: FnMut(String),
133+{
134+ let file_count = unsafe { DragQueryFileW(hdrop, DRAGDROP_GET_FILES_COUNT, None) };
135+ for file_index in 0..file_count {
136+ let filename_length = unsafe { DragQueryFileW(hdrop, file_index, None) } as usize;
137+ let mut buffer = vec![0u16; filename_length + 1];
138+ let ret = unsafe { DragQueryFileW(hdrop, file_index, Some(buffer.as_mut_slice())) };
139+ if ret == 0 {
140+ log::error!("unable to read file name of dragged file");
141+ continue;
142+ }
143+ match String::from_utf16(&buffer[0..filename_length]) {
144+ Ok(file_name) => f(file_name),
145+ Err(e) => log::error!("dragged file name is not UTF-16: {}", e),
146+ }
147+ }
148+}
149+
150+fn set_clipboard_bytes<T>(data: &[T], format: u32) -> Result<()> {
151+ unsafe {
152+ let global = Owned::new(GlobalAlloc(GMEM_MOVEABLE, std::mem::size_of_val(data))?);
153+ let ptr = GlobalLock(*global);
154+ anyhow::ensure!(!ptr.is_null(), "GlobalLock returned null");
155+ std::ptr::copy_nonoverlapping(data.as_ptr(), ptr as _, data.len());
156+ GlobalUnlock(*global).ok();
157+ SetClipboardData(format, Some(HANDLE(global.0)))?;
158+ // SetClipboardData succeeded — the system now owns the memory.
159+ std::mem::forget(global);
160+ }
161+ Ok(())
162+}
163+
164+fn get_clipboard_string(format: u32) -> Option<String> {
165+ let locked = get_clipboard_data(format)?;
166+ let bytes = locked.as_bytes();
167+ let words_len = bytes.len() / std::mem::size_of::<u16>();
168+ if words_len == 0 {
169+ return Some(String::new());
170+ }
171+ let slice = unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u16, words_len) };
172+ let actual_len = slice.iter().position(|&c| c == 0).unwrap_or(words_len);
173+ Some(String::from_utf16_lossy(&slice[..actual_len]))
174+}
175+
176+fn is_image_format(format: u32) -> bool {
177+ IMAGE_FORMATS_MAP.contains_key(&format) || format == CF_DIB.0 as u32
178+}
179+
180+fn write_string(item: &ClipboardString) -> Result<()> {
181+ // CF_UNICODETEXT is null-terminated, so replace embedded NUL characters with spaces.
182+ let text = item.text.replace('\0', " ").replace("\r\n", "\n");
183+ // Windows applications expect CRLF line endings in CF_UNICODETEXT.
184+ let wide: Vec<u16> = text
185+ .replace('\n', "\r\n")
186+ .encode_utf16()
187+ .chain(Some(0))
188+ .collect_vec();
189+ set_clipboard_bytes(&wide, CF_UNICODETEXT.0 as u32)?;
190+
191+ if let Some(metadata) = item.metadata.as_ref() {
192+ let hash_bytes = ClipboardString::text_hash(&text).to_ne_bytes();
193+ set_clipboard_bytes(&hash_bytes, *CLIPBOARD_HASH_FORMAT)?;
194+
195+ let wide: Vec<u16> = metadata.encode_utf16().chain(Some(0)).collect_vec();
196+ set_clipboard_bytes(&wide, *CLIPBOARD_METADATA_FORMAT)?;
197+ }
198+ Ok(())
199+}
200+
201+fn write_image(item: &Image) -> Result<()> {
202+ let native_format = match item.format {
203+ ImageFormat::Svg => Some(*CLIPBOARD_SVG_FORMAT),
204+ ImageFormat::Gif => Some(*CLIPBOARD_GIF_FORMAT),
205+ ImageFormat::Png => Some(*CLIPBOARD_PNG_FORMAT),
206+ ImageFormat::Jpeg => Some(*CLIPBOARD_JPG_FORMAT),
207+ _ => None,
208+ };
209+ if let Some(format) = native_format {
210+ set_clipboard_bytes(item.bytes(), format)?;
211+ }
212+
213+ // Also provide a PNG copy for broad compatibility.
214+ // SVG can't be rasterized by the image crate, so skip it.
215+ if item.format != ImageFormat::Svg && native_format != Some(*CLIPBOARD_PNG_FORMAT) {
216+ if let Some(png_bytes) = convert_to_png(item.bytes(), item.format) {
217+ set_clipboard_bytes(&png_bytes, *CLIPBOARD_PNG_FORMAT)?;
218+ }
219+ }
220+ Ok(())
221+}
222+
223+fn convert_to_png(bytes: &[u8], format: ImageFormat) -> Option<Vec<u8>> {
224+ let img_format = gpui_to_image_format(format)?;
225+ let image = image::load_from_memory_with_format(bytes, img_format)
226+ .map_err(|e| log::warn!("Failed to decode image for PNG conversion: {e}"))
227+ .ok()?;
228+ let mut buf = Vec::new();
229+ image
230+ .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
231+ .map_err(|e| log::warn!("Failed to encode PNG: {e}"))
232+ .ok()?;
233+ Some(buf)
234+}
235+
236+fn read_string() -> Option<ClipboardEntry> {
237+ // Normalize to LF so that apps the same line endings on every platform.
238+ let text = get_clipboard_string(CF_UNICODETEXT.0 as u32)?.replace("\r\n", "\n");
239+ let metadata = read_clipboard_metadata(&text);
240+ Some(ClipboardEntry::String(ClipboardString { text, metadata }))
241+}
242+
243+fn read_clipboard_metadata(text: &str) -> Option<String> {
244+ let locked = get_clipboard_data(*CLIPBOARD_HASH_FORMAT)?;
245+ let hash_bytes: [u8; 8] = locked.as_bytes().get(..8)?.try_into().ok()?;
246+ let hash = u64::from_ne_bytes(hash_bytes);
247+ if hash != ClipboardString::text_hash(text) {
248+ return None;
249+ }
250+ get_clipboard_string(*CLIPBOARD_METADATA_FORMAT)
251+}
252+
253+fn read_image(format: u32) -> Option<ClipboardEntry> {
254+ let locked = get_clipboard_data(format)?;
255+ let (bytes, image_format) = if format == CF_DIB.0 as u32 {
256+ (convert_dib_to_bmp(locked.as_bytes())?, ImageFormat::Bmp)
257+ } else {
258+ let image_format = *IMAGE_FORMATS_MAP.get(&format)?;
259+ (locked.as_bytes().to_vec(), image_format)
260+ };
261+ let id = hash(&bytes);
262+ Some(ClipboardEntry::Image(Image {
263+ format: image_format,
264+ bytes,
265+ id,
266+ }))
267+}
268+
269+fn read_files() -> Option<ClipboardEntry> {
270+ let locked = get_clipboard_data(CF_HDROP.0 as u32)?;
271+ let hdrop = HDROP(locked.ptr as *mut _);
272+ let mut filenames = Vec::new();
273+ with_file_names(hdrop, |name| filenames.push(std::path::PathBuf::from(name)));
274+ Some(ClipboardEntry::ExternalPaths(ExternalPaths(
275+ filenames.into(),
276+ )))
277+}
278+
279+/// DIB is BMP without the 14-byte BITMAPFILEHEADER. Prepend one.
280+fn convert_dib_to_bmp(dib: &[u8]) -> Option<Vec<u8>> {
281+ if dib.len() < 40 {
282+ return None;
283+ }
284+
285+ let header_size = u32::from_le_bytes(dib[0..4].try_into().ok()?);
286+ let bit_count = u16::from_le_bytes(dib[14..16].try_into().ok()?);
287+ let compression = u32::from_le_bytes(dib[16..20].try_into().ok()?);
288+
289+ let color_table_size = if bit_count <= 8 {
290+ let colors_used = u32::from_le_bytes(dib[32..36].try_into().ok()?);
291+ (if colors_used == 0 {
292+ 1u32 << bit_count
293+ } else {
294+ colors_used
295+ }) * 4
296+ } else if compression == 3 {
297+ 12 // BI_BITFIELDS
298+ } else {
299+ 0
300+ };
301+
302+ let pixel_offset = 14 + header_size + color_table_size;
303+ let file_size = 14 + dib.len() as u32;
304+
305+ let mut bmp = Vec::with_capacity(file_size as usize);
306+ bmp.extend_from_slice(b"BM");
307+ bmp.extend_from_slice(&file_size.to_le_bytes());
308+ bmp.extend_from_slice(&[0u8; 4]); // reserved
309+ bmp.extend_from_slice(&pixel_offset.to_le_bytes());
310+ bmp.extend_from_slice(dib);
311+ Some(bmp)
312+}
313+
314+fn log_unsupported_clipboard_formats() {
315+ let count = unsafe { CountClipboardFormats() };
316+ let mut format = 0;
317+ for _ in 0..count {
318+ format = unsafe { EnumClipboardFormats(format) };
319+ let mut buffer = [0u16; 64];
320+ unsafe { GetClipboardFormatNameW(format, &mut buffer) };
321+ let format_name = String::from_utf16_lossy(&buffer);
322+ log::warn!(
323+ "Try to paste with unsupported clipboard format: {}, {}.",
324+ format,
325+ format_name
326+ );
327+ }
328+}
329+
330+fn gpui_to_image_format(value: ImageFormat) -> Option<image::ImageFormat> {
331+ match value {
332+ ImageFormat::Png => Some(image::ImageFormat::Png),
333+ ImageFormat::Jpeg => Some(image::ImageFormat::Jpeg),
334+ ImageFormat::Webp => Some(image::ImageFormat::WebP),
335+ ImageFormat::Gif => Some(image::ImageFormat::Gif),
336+ ImageFormat::Bmp => Some(image::ImageFormat::Bmp),
337+ ImageFormat::Tiff => Some(image::ImageFormat::Tiff),
338+ other => {
339+ log::warn!("No image crate equivalent for format: {other:?}");
340+ None
341+ }
342+ }
343+}
344+
345+struct ClipboardGuard;
346+
347+impl ClipboardGuard {
348+ fn open() -> Option<Self> {
349+ match unsafe { OpenClipboard(None) } {
350+ Ok(()) => Some(Self),
351+ Err(e) => {
352+ log::error!("Failed to open clipboard: {e}");
353+ None
354+ }
355+ }
356+ }
357+}
358+
359+impl Drop for ClipboardGuard {
360+ fn drop(&mut self) {
361+ if let Err(e) = unsafe { CloseClipboard() } {
362+ log::error!("Failed to close clipboard: {e}");
363+ }
364+ }
365+}
366+
367+struct LockedGlobal {
368+ global: HGLOBAL,
369+ ptr: *const u8,
370+ size: usize,
371+}
372+
373+impl LockedGlobal {
374+ fn lock(global: HGLOBAL) -> Option<Self> {
375+ let size = unsafe { GlobalSize(global) };
376+ let ptr = unsafe { GlobalLock(global) };
377+ if ptr.is_null() {
378+ return None;
379+ }
380+ Some(Self {
381+ global,
382+ ptr: ptr as *const u8,
383+ size,
384+ })
385+ }
386+
387+ fn as_bytes(&self) -> &[u8] {
388+ unsafe { std::slice::from_raw_parts(self.ptr, self.size) }
389+ }
390+}
391+
392+impl Drop for LockedGlobal {
393+ fn drop(&mut self) {
394+ unsafe { GlobalUnlock(self.global).ok() };
395+ }
396+}
397+
398+#[cfg(test)]
399+pub(crate) fn read_raw_clipboard_text() -> Option<String> {
400+ let _clip = ClipboardGuard::open()?;
401+ get_clipboard_string(CF_UNICODETEXT.0 as u32)
402+}
vendor/gpui-pre-windows/src/destination_list.rsadded+207 -0
@@ -0,0 +1,207 @@
1+use std::{path::PathBuf, sync::Arc};
2+
3+use itertools::Itertools;
4+use smallvec::SmallVec;
5+use windows::{
6+ Win32::{
7+ Foundation::PROPERTYKEY,
8+ Globalization::u_strlen,
9+ System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, StructuredStorage::PROPVARIANT},
10+ UI::{
11+ Controls::INFOTIPSIZE,
12+ Shell::{
13+ Common::{IObjectArray, IObjectCollection},
14+ DestinationList, EnumerableObjectCollection, ICustomDestinationList, IShellLinkW,
15+ PropertiesSystem::IPropertyStore,
16+ ShellLink,
17+ },
18+ },
19+ },
20+ core::{GUID, HSTRING, Interface},
21+};
22+
23+use gpui::{Action, MenuItem, SharedString};
24+
25+pub(crate) struct JumpList {
26+ pub(crate) dock_menus: Vec<DockMenuItem>,
27+ pub(crate) recent_workspaces: Arc<[SmallVec<[PathBuf; 2]>]>,
28+}
29+
30+impl JumpList {
31+ pub(crate) fn new() -> Self {
32+ Self {
33+ dock_menus: Vec::default(),
34+ recent_workspaces: Arc::default(),
35+ }
36+ }
37+}
38+
39+pub(crate) struct DockMenuItem {
40+ pub(crate) name: SharedString,
41+ pub(crate) description: SharedString,
42+ pub(crate) action: Box<dyn Action>,
43+}
44+
45+impl DockMenuItem {
46+ pub(crate) fn new(item: MenuItem) -> anyhow::Result<Self> {
47+ match item {
48+ MenuItem::Action { name, action, .. } => Ok(Self {
49+ name: name.clone(),
50+ description: if name == "New Window" {
51+ "Opens a new window".into()
52+ } else {
53+ name
54+ },
55+ action,
56+ }),
57+ _ => anyhow::bail!("Only `MenuItem::Action` is supported for dock menu on Windows."),
58+ }
59+ }
60+}
61+
62+// This code is based on the example from Microsoft:
63+// https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/Win7Samples/winui/shell/appshellintegration/RecipePropertyHandler/RecipePropertyHandler.cpp
64+pub(crate) fn update_jump_list(
65+ recent_workspaces: &[SmallVec<[PathBuf; 2]>],
66+ dock_menus: &[(SharedString, SharedString)],
67+) -> anyhow::Result<Vec<SmallVec<[PathBuf; 2]>>> {
68+ let (list, removed) = create_destination_list()?;
69+ add_recent_folders(&list, recent_workspaces, removed.as_ref())?;
70+ add_dock_menu(&list, dock_menus)?;
71+ unsafe { list.CommitList() }?;
72+ Ok(removed)
73+}
74+
75+// Copied from:
76+// https://github.com/microsoft/windows-rs/blob/0fc3c2e5a13d4316d242bdeb0a52af611eba8bd4/crates/libs/windows/src/Windows/Win32/Storage/EnhancedStorage/mod.rs#L1881
77+const PKEY_TITLE: PROPERTYKEY = PROPERTYKEY {
78+ fmtid: GUID::from_u128(0xf29f85e0_4ff9_1068_ab91_08002b27b3d9),
79+ pid: 2,
80+};
81+
82+fn create_destination_list() -> anyhow::Result<(ICustomDestinationList, Vec<SmallVec<[PathBuf; 2]>>)>
83+{
84+ let list: ICustomDestinationList =
85+ unsafe { CoCreateInstance(&DestinationList, None, CLSCTX_INPROC_SERVER) }?;
86+
87+ let mut slots = 0;
88+ let user_removed: IObjectArray = unsafe { list.BeginList(&mut slots) }?;
89+
90+ let count = unsafe { user_removed.GetCount() }?;
91+ if count == 0 {
92+ return Ok((list, Vec::new()));
93+ }
94+
95+ let mut removed = Vec::with_capacity(count as usize);
96+ for i in 0..count {
97+ let shell_link: IShellLinkW = unsafe { user_removed.GetAt(i)? };
98+ let description = {
99+ // INFOTIPSIZE is the maximum size of the buffer
100+ // see https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getdescription
101+ let mut buffer = [0u16; INFOTIPSIZE as usize];
102+ unsafe { shell_link.GetDescription(&mut buffer)? };
103+ let len = unsafe { u_strlen(buffer.as_ptr()) };
104+ String::from_utf16_lossy(&buffer[..len as usize])
105+ };
106+ let args = description.split('\n').map(PathBuf::from).collect();
107+
108+ removed.push(args);
109+ }
110+
111+ Ok((list, removed))
112+}
113+
114+fn add_dock_menu(
115+ list: &ICustomDestinationList,
116+ dock_menus: &[(SharedString, SharedString)],
117+) -> anyhow::Result<()> {
118+ unsafe {
119+ let tasks: IObjectCollection =
120+ CoCreateInstance(&EnumerableObjectCollection, None, CLSCTX_INPROC_SERVER)?;
121+ for (idx, (name, description)) in dock_menus.iter().enumerate() {
122+ let argument = HSTRING::from(format!("--dock-action {}", idx));
123+ let description = HSTRING::from(description.as_str());
124+ let display = name.as_str();
125+ let task = create_shell_link(argument, description, None, display)?;
126+ tasks.AddObject(&task)?;
127+ }
128+ list.AddUserTasks(&tasks)?;
129+ Ok(())
130+ }
131+}
132+
133+fn add_recent_folders(
134+ list: &ICustomDestinationList,
135+ entries: &[SmallVec<[PathBuf; 2]>],
136+ removed: &Vec<SmallVec<[PathBuf; 2]>>,
137+) -> anyhow::Result<()> {
138+ unsafe {
139+ let tasks: IObjectCollection =
140+ CoCreateInstance(&EnumerableObjectCollection, None, CLSCTX_INPROC_SERVER)?;
141+
142+ for folder_path in entries.iter().filter(|path| !removed.contains(path)) {
143+ let argument = HSTRING::from(
144+ folder_path
145+ .iter()
146+ .map(|path| format!("\"{}\"", path.display()))
147+ .join(" "),
148+ );
149+
150+ let description = HSTRING::from(
151+ folder_path
152+ .iter()
153+ .map(|path| path.to_string_lossy())
154+ .collect::<Vec<_>>()
155+ .join("\n"),
156+ );
157+ // simulate folder icon
158+ // https://github.com/microsoft/vscode/blob/7a5dc239516a8953105da34f84bae152421a8886/src/vs/platform/workspaces/electron-main/workspacesHistoryMainService.ts#L380
159+ let icon = HSTRING::from("explorer.exe");
160+
161+ let display = folder_path
162+ .iter()
163+ .map(|p| {
164+ p.file_name()
165+ .map(|name| name.to_string_lossy())
166+ .unwrap_or_else(|| p.to_string_lossy())
167+ })
168+ .join(", ");
169+
170+ tasks.AddObject(&create_shell_link(
171+ argument,
172+ description,
173+ Some(icon),
174+ &display,
175+ )?)?;
176+ }
177+
178+ if tasks.GetCount().unwrap_or(0) > 0 {
179+ list.AppendCategory(&HSTRING::from("Recent Folders"), &tasks)?;
180+ }
181+ Ok(())
182+ }
183+}
184+
185+fn create_shell_link(
186+ argument: HSTRING,
187+ description: HSTRING,
188+ icon: Option<HSTRING>,
189+ display: &str,
190+) -> anyhow::Result<IShellLinkW> {
191+ unsafe {
192+ let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?;
193+ let exe_path = HSTRING::from(std::env::current_exe()?.as_os_str());
194+ link.SetPath(&exe_path)?;
195+ link.SetArguments(&argument)?;
196+ link.SetDescription(&description)?;
197+ if let Some(icon) = icon {
198+ link.SetIconLocation(&icon, 0)?;
199+ }
200+ let store: IPropertyStore = link.cast()?;
201+ let title = PROPVARIANT::from(display);
202+ store.SetValue(&PKEY_TITLE, &title)?;
203+ store.Commit()?;
204+
205+ Ok(link)
206+ }
207+}
vendor/gpui-pre-windows/src/dialog.rsadded+340 -0
@@ -0,0 +1,340 @@
1+use std::{
2+ cell::RefCell,
3+ rc::Rc,
4+ sync::{
5+ Arc,
6+ atomic::{AtomicBool, Ordering},
7+ },
8+};
9+
10+use anyhow::{Context as _, Result, anyhow};
11+use futures::{
12+ channel::oneshot,
13+ future::{Either, select},
14+ lock::Mutex,
15+};
16+use gpui::ForegroundExecutor;
17+use gpui_util::ResultExt;
18+use windows::{
19+ Win32::{
20+ Foundation::*,
21+ System::{Com::*, Threading::GetCurrentThreadId},
22+ UI::{
23+ Controls::{TASKDIALOG_NOTIFICATIONS, TDN_BUTTON_CLICKED},
24+ WindowsAndMessaging::*,
25+ },
26+ },
27+ core::{BOOL, HRESULT, w},
28+};
29+
30+use crate::SafeHwnd;
31+
32+pub(crate) struct DialogOwner {
33+ hwnd: HWND,
34+ closed: Arc<AtomicBool>,
35+ serialization: Mutex<()>,
36+}
37+
38+impl DialogOwner {
39+ pub(crate) fn new(hwnd: HWND) -> Rc<Self> {
40+ Rc::new(Self {
41+ hwnd,
42+ closed: Arc::new(AtomicBool::new(false)),
43+ serialization: Mutex::new(()),
44+ })
45+ }
46+
47+ pub(crate) fn close(&self) {
48+ self.closed.store(true, Ordering::Release);
49+ }
50+
51+ pub(crate) async fn when_idle(&self) {
52+ // After close(), queued requests cannot start a native dialog. Only the
53+ // active dialog can still use the HWND, and it holds this lock until exit.
54+ let _guard = self.serialization.lock().await;
55+ }
56+}
57+
58+#[derive(Clone, Default)]
59+struct Cancellation {
60+ requested: Arc<AtomicBool>,
61+ owner_closed: Option<Arc<AtomicBool>>,
62+}
63+
64+impl Cancellation {
65+ fn new(owner: Option<&DialogOwner>) -> Self {
66+ Self {
67+ owner_closed: owner.map(|owner| owner.closed.clone()),
68+ ..Self::default()
69+ }
70+ }
71+
72+ fn is_requested(&self) -> bool {
73+ self.requested.load(Ordering::Acquire)
74+ || self
75+ .owner_closed
76+ .as_ref()
77+ .is_some_and(|closed| closed.load(Ordering::Acquire))
78+ }
79+}
80+
81+/// Native modal loops may synchronously message their owner, so the foreground
82+/// thread must keep pumping messages rather than waiting for the dialog thread.
83+/// Holding the owner's lock through native completion also allows window
84+/// destruction to wait for the dialog without blocking the foreground thread.
85+pub(crate) fn show_dialog<T: Send + 'static>(
86+ owner: Option<Rc<DialogOwner>>,
87+ executor: &ForegroundExecutor,
88+ dialog: impl FnOnce(HWND) -> Result<T> + Send + 'static,
89+) -> oneshot::Receiver<Result<T>> {
90+ let (mut sender, receiver) = oneshot::channel();
91+ let cancellation = Cancellation::new(owner.as_deref());
92+ if cancellation.is_requested() {
93+ sender.send(Err(anyhow!("dialog owner has closed"))).ok();
94+ return receiver;
95+ }
96+ let hwnd = owner.as_ref().map(|owner| SafeHwnd::from(owner.hwnd));
97+ executor
98+ .spawn(async move {
99+ // Let Windows manage enabling and activating the owner. Overlapping
100+ // modal loops could otherwise re-enable it while another dialog is open.
101+ let serialization = if let Some(owner) = owner.as_ref() {
102+ match select(owner.serialization.lock(), sender.cancellation()).await {
103+ Either::Left((guard, _)) => Some(guard),
104+ Either::Right(((), _)) => return,
105+ }
106+ } else {
107+ None
108+ };
109+ if sender.is_canceled() || cancellation.is_requested() {
110+ return;
111+ }
112+ let (result_sender, mut result_receiver) = oneshot::channel();
113+ let thread = std::thread::Builder::new()
114+ .name("windows-native-dialog".into())
115+ .spawn({
116+ let cancellation = cancellation.clone();
117+ move || {
118+ let result = (|| {
119+ let _apartment = Apartment::new()?;
120+ let _timer = CancellationTimer::new(cancellation.clone())?;
121+ if cancellation.is_requested() {
122+ return Err(anyhow!("dialog cancelled"));
123+ }
124+ let result = dialog(hwnd.map(|hwnd| hwnd.as_raw()).unwrap_or_default());
125+ if cancellation.is_requested() {
126+ return Err(anyhow!("dialog cancelled"));
127+ }
128+ result
129+ })();
130+ result_sender.send(result).ok();
131+ }
132+ });
133+ if let Err(error) = thread {
134+ drop(serialization);
135+ sender.send(Err(error.into())).ok();
136+ return;
137+ }
138+ let result = match select(&mut result_receiver, sender.cancellation()).await {
139+ Either::Left((result, _)) => result,
140+ Either::Right(((), _)) => {
141+ cancellation.requested.store(true, Ordering::Release);
142+ result_receiver.await
143+ }
144+ };
145+ // Neither launch another dialog nor destroy the owner until the
146+ // native loop exits, even if the caller no longer wants its result.
147+ drop(serialization);
148+ sender
149+ .send(result.unwrap_or_else(|error| Err(error.into())))
150+ .ok();
151+ })
152+ .detach();
153+ receiver
154+}
155+
156+struct Apartment;
157+
158+impl Apartment {
159+ fn new() -> Result<Self> {
160+ unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok()? };
161+ Ok(Self)
162+ }
163+}
164+
165+impl Drop for Apartment {
166+ fn drop(&mut self) {
167+ unsafe { CoUninitialize() };
168+ }
169+}
170+
171+thread_local! {
172+ static CANCELLATION: RefCell<Option<Cancellation>> = const { RefCell::new(None) };
173+}
174+
175+struct CancellationTimer(usize);
176+
177+impl CancellationTimer {
178+ fn new(cancellation: Cancellation) -> Result<Self> {
179+ let timer = unsafe { SetTimer(None, 0, 100, Some(cancel_dialog)) };
180+ if timer == 0 {
181+ return Err(windows::core::Error::from_thread())
182+ .context("starting native dialog cancellation timer");
183+ }
184+ CANCELLATION.with(|slot| slot.replace(Some(cancellation)));
185+ Ok(Self(timer))
186+ }
187+}
188+
189+impl Drop for CancellationTimer {
190+ fn drop(&mut self) {
191+ CANCELLATION.with(|slot| slot.take());
192+ unsafe { KillTimer(None, self.0).log_err() };
193+ }
194+}
195+
196+unsafe extern "system" fn cancel_dialog(_: HWND, _: u32, _: usize, _: u32) {
197+ if cancellation_requested() {
198+ unsafe {
199+ EnumThreadWindows(GetCurrentThreadId(), Some(close_dialog), LPARAM(0))
200+ .ok()
201+ .log_err();
202+ };
203+ }
204+}
205+
206+fn cancellation_requested() -> bool {
207+ CANCELLATION.with(|slot| {
208+ slot.borrow()
209+ .as_ref()
210+ .is_some_and(Cancellation::is_requested)
211+ })
212+}
213+
214+pub(crate) unsafe extern "system" fn task_dialog_callback(
215+ _: HWND,
216+ notification: TASKDIALOG_NOTIFICATIONS,
217+ button: WPARAM,
218+ _: LPARAM,
219+ has_cancel_button: isize,
220+) -> HRESULT {
221+ // WM_CLOSE requires TDF_ALLOW_DIALOG_CANCELLATION, which also enables Esc/X.
222+ // Only allow those user gestures when the prompt offered a Cancel button.
223+ if notification == TDN_BUTTON_CLICKED
224+ && button.0 == IDCANCEL.0 as usize
225+ && has_cancel_button == 0
226+ && !cancellation_requested()
227+ {
228+ S_FALSE
229+ } else {
230+ S_OK
231+ }
232+}
233+
234+unsafe extern "system" fn close_dialog(hwnd: HWND, _: LPARAM) -> BOOL {
235+ // Shell dialogs can open further modal dialogs. Close only dialog windows
236+ // on this dedicated thread, not hidden COM infrastructure windows.
237+ let mut class_name = [0u16; 32];
238+ let length = unsafe { GetClassNameW(hwnd, &mut class_name) } as usize;
239+ let dialog_class = w!("#32770");
240+ if class_name.get(..length) == Some(unsafe { dialog_class.as_wide() }) {
241+ unsafe { PostMessageW(Some(hwnd), WM_CLOSE, WPARAM(0), LPARAM(0)).log_err() };
242+ }
243+ TRUE
244+}
245+
246+#[cfg(test)]
247+mod tests {
248+ use super::*;
249+ use futures::FutureExt as _;
250+
251+ #[test]
252+ fn task_dialog_cancellation_requires_cancel_button_or_internal_request() {
253+ let cancellation = Cancellation::default();
254+ CANCELLATION.with(|slot| slot.replace(Some(cancellation.clone())));
255+ for internally_cancelled in [false, true] {
256+ cancellation
257+ .requested
258+ .store(internally_cancelled, Ordering::Release);
259+ for has_cancel_button in [false, true] {
260+ for button in [IDCANCEL.0, IDOK.0, -1] {
261+ let result = unsafe {
262+ task_dialog_callback(
263+ HWND::default(),
264+ TDN_BUTTON_CLICKED,
265+ WPARAM(button as usize),
266+ LPARAM(0),
267+ has_cancel_button as isize,
268+ )
269+ };
270+ let should_veto =
271+ button == IDCANCEL.0 && !has_cancel_button && !internally_cancelled;
272+ assert_eq!(result, if should_veto { S_FALSE } else { S_OK });
273+ }
274+ }
275+ }
276+ CANCELLATION.with(|slot| slot.take());
277+ }
278+
279+ #[test]
280+ fn closing_owner_cancels_every_outstanding_dialog() {
281+ let owner = DialogOwner::new(HWND::default());
282+ let first = Cancellation::new(Some(&owner));
283+ let second = Cancellation::new(Some(&owner));
284+ assert!(!first.is_requested());
285+ assert!(!second.is_requested());
286+
287+ owner.close();
288+ owner.close();
289+
290+ assert!(first.is_requested());
291+ assert!(second.is_requested());
292+ assert!(Cancellation::new(Some(&owner)).is_requested());
293+ }
294+
295+ #[test]
296+ fn closed_owner_waits_for_active_dialog_but_queued_requests_stay_cancelled() {
297+ let owner = DialogOwner::new(HWND::default());
298+ let active = owner.serialization.try_lock().expect("first dialog");
299+ let queued = Cancellation::new(Some(&owner));
300+
301+ owner.close();
302+ assert!(owner.when_idle().now_or_never().is_none());
303+ drop(active);
304+ assert!(owner.when_idle().now_or_never().is_some());
305+
306+ let _guard = owner.serialization.try_lock().expect("queued request");
307+ assert!(queued.is_requested());
308+ }
309+
310+ #[test]
311+ fn cancelling_one_request_does_not_cancel_its_owner_or_other_requests() {
312+ let owner = DialogOwner::new(HWND::default());
313+ let first = Cancellation::new(Some(&owner));
314+ let second = Cancellation::new(Some(&owner));
315+ first.requested.store(true, Ordering::Release);
316+ assert!(first.is_requested());
317+ assert!(!second.is_requested());
318+ assert!(!owner.closed.load(Ordering::Acquire));
319+ }
320+
321+ #[test]
322+ fn dialogs_serialize_per_owner() {
323+ let owner = DialogOwner::new(HWND::default());
324+ let other_owner = DialogOwner::new(HWND::default());
325+ let guard = owner.serialization.try_lock().expect("first dialog");
326+
327+ assert!(owner.serialization.try_lock().is_none());
328+ assert!(other_owner.serialization.try_lock().is_some());
329+ drop(guard);
330+ assert!(owner.serialization.try_lock().is_some());
331+ }
332+
333+ #[test]
334+ fn ownerless_request_can_be_cancelled_without_a_window() {
335+ let cancellation = Cancellation::new(None);
336+ assert!(!cancellation.is_requested());
337+ cancellation.requested.store(true, Ordering::Release);
338+ assert!(cancellation.is_requested());
339+ }
340+}
vendor/gpui-pre-windows/src/direct_manipulation.rsadded+361 -0
@@ -0,0 +1,361 @@
1+use std::cell::{Cell, RefCell};
2+use std::rc::Rc;
3+
4+use anyhow::Result;
5+use gpui::*;
6+use gpui_util::ResultExt;
7+use windows::Win32::{
8+ Foundation::*,
9+ Graphics::{DirectManipulation::*, Gdi::*},
10+ System::Com::*,
11+ UI::{Input::Pointer::*, WindowsAndMessaging::*},
12+};
13+
14+use crate::*;
15+
16+/// Default viewport size in pixels. The actual content size doesn't matter
17+/// because we're using the viewport only for gesture recognition, not for
18+/// visual output.
19+const DEFAULT_VIEWPORT_SIZE: i32 = 1000;
20+
21+pub(crate) struct DirectManipulationHandler {
22+ manager: IDirectManipulationManager,
23+ update_manager: IDirectManipulationUpdateManager,
24+ viewport: IDirectManipulationViewport,
25+ _handler_cookie: u32,
26+ window: HWND,
27+ scale_factor: Rc<Cell<f32>>,
28+ pending_events: Rc<RefCell<Vec<PlatformInput>>>,
29+}
30+
31+impl DirectManipulationHandler {
32+ pub fn new(window: HWND, scale_factor: f32) -> Result<Self> {
33+ unsafe {
34+ let manager: IDirectManipulationManager =
35+ CoCreateInstance(&DirectManipulationManager, None, CLSCTX_INPROC_SERVER)?;
36+
37+ let update_manager: IDirectManipulationUpdateManager = manager.GetUpdateManager()?;
38+
39+ let viewport: IDirectManipulationViewport = manager.CreateViewport(None, window)?;
40+
41+ let configuration = DIRECTMANIPULATION_CONFIGURATION_INTERACTION
42+ | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_X
43+ | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_Y
44+ | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_INERTIA
45+ | DIRECTMANIPULATION_CONFIGURATION_RAILS_X
46+ | DIRECTMANIPULATION_CONFIGURATION_RAILS_Y
47+ | DIRECTMANIPULATION_CONFIGURATION_SCALING;
48+ viewport.ActivateConfiguration(configuration)?;
49+
50+ viewport.SetViewportOptions(
51+ DIRECTMANIPULATION_VIEWPORT_OPTIONS_MANUALUPDATE
52+ | DIRECTMANIPULATION_VIEWPORT_OPTIONS_DISABLEPIXELSNAPPING,
53+ )?;
54+
55+ let mut rect = RECT {
56+ left: 0,
57+ top: 0,
58+ right: DEFAULT_VIEWPORT_SIZE,
59+ bottom: DEFAULT_VIEWPORT_SIZE,
60+ };
61+ viewport.SetViewportRect(&mut rect)?;
62+
63+ manager.Activate(window)?;
64+ viewport.Enable()?;
65+
66+ let scale_factor = Rc::new(Cell::new(scale_factor));
67+ let pending_events = Rc::new(RefCell::new(Vec::new()));
68+
69+ let event_handler: IDirectManipulationViewportEventHandler =
70+ DirectManipulationEventHandler::new(
71+ window,
72+ Rc::clone(&scale_factor),
73+ Rc::clone(&pending_events),
74+ )
75+ .into();
76+
77+ let handler_cookie = viewport.AddEventHandler(Some(window), &event_handler)?;
78+
79+ update_manager.Update(None)?;
80+
81+ Ok(Self {
82+ manager,
83+ update_manager,
84+ viewport,
85+ _handler_cookie: handler_cookie,
86+ window,
87+ scale_factor,
88+ pending_events,
89+ })
90+ }
91+ }
92+
93+ pub fn set_scale_factor(&self, scale_factor: f32) {
94+ self.scale_factor.set(scale_factor);
95+ }
96+
97+ pub fn on_pointer_hit_test(&self, wparam: WPARAM) {
98+ unsafe {
99+ let pointer_id = wparam.loword() as u32;
100+ let mut pointer_type = POINTER_INPUT_TYPE::default();
101+ if GetPointerType(pointer_id, &mut pointer_type).is_ok() && pointer_type == PT_TOUCHPAD
102+ {
103+ self.viewport.SetContact(pointer_id).log_err();
104+ }
105+ }
106+ }
107+
108+ pub fn update(&self) {
109+ unsafe {
110+ self.update_manager.Update(None).log_err();
111+ }
112+ }
113+
114+ pub fn drain_events(&self) -> Vec<PlatformInput> {
115+ std::mem::take(&mut *self.pending_events.borrow_mut())
116+ }
117+}
118+
119+impl Drop for DirectManipulationHandler {
120+ fn drop(&mut self) {
121+ unsafe {
122+ self.viewport.Stop().log_err();
123+ self.viewport.Abandon().log_err();
124+ self.manager.Deactivate(self.window).log_err();
125+ }
126+ }
127+}
128+
129+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130+enum GestureKind {
131+ None,
132+ Scroll,
133+ Pinch,
134+}
135+
136+#[windows_core::implement(IDirectManipulationViewportEventHandler)]
137+struct DirectManipulationEventHandler {
138+ window: HWND,
139+ scale_factor: Rc<Cell<f32>>,
140+ gesture_kind: Cell<GestureKind>,
141+ last_scale: Cell<f32>,
142+ last_x_offset: Cell<f32>,
143+ last_y_offset: Cell<f32>,
144+ scroll_phase: Cell<TouchPhase>,
145+ pending_events: Rc<RefCell<Vec<PlatformInput>>>,
146+}
147+
148+impl DirectManipulationEventHandler {
149+ fn new(
150+ window: HWND,
151+ scale_factor: Rc<Cell<f32>>,
152+ pending_events: Rc<RefCell<Vec<PlatformInput>>>,
153+ ) -> Self {
154+ Self {
155+ window,
156+ scale_factor,
157+ gesture_kind: Cell::new(GestureKind::None),
158+ last_scale: Cell::new(1.0),
159+ last_x_offset: Cell::new(0.0),
160+ last_y_offset: Cell::new(0.0),
161+ scroll_phase: Cell::new(TouchPhase::Started),
162+ pending_events,
163+ }
164+ }
165+
166+ fn end_gesture(&self) {
167+ let position = self.mouse_position();
168+ let modifiers = current_modifiers();
169+ match self.gesture_kind.get() {
170+ GestureKind::Scroll => {
171+ self.pending_events
172+ .borrow_mut()
173+ .push(PlatformInput::Scroll(ScrollEvent {
174+ position,
175+ delta: ScrollDelta::Pixels(point(px(0.0), px(0.0))),
176+ modifiers,
177+ touch_phase: TouchPhase::Ended,
178+ source: ScrollSource::Pointer,
179+ }));
180+ }
181+ GestureKind::Pinch => {
182+ self.pending_events
183+ .borrow_mut()
184+ .push(PlatformInput::Pinch(PinchEvent {
185+ position,
186+ delta: 0.0,
187+ modifiers,
188+ phase: TouchPhase::Ended,
189+ }));
190+ }
191+ GestureKind::None => {}
192+ }
193+ self.gesture_kind.set(GestureKind::None);
194+ }
195+
196+ fn mouse_position(&self) -> Point<Pixels> {
197+ let scale_factor = self.scale_factor.get();
198+ unsafe {
199+ let mut point: POINT = std::mem::zeroed();
200+ let _ = GetCursorPos(&mut point);
201+ let _ = ScreenToClient(self.window, &mut point);
202+ logical_point(point.x as f32, point.y as f32, scale_factor)
203+ }
204+ }
205+}
206+
207+impl IDirectManipulationViewportEventHandler_Impl for DirectManipulationEventHandler_Impl {
208+ fn OnViewportStatusChanged(
209+ &self,
210+ viewport: windows_core::Ref<'_, IDirectManipulationViewport>,
211+ current: DIRECTMANIPULATION_STATUS,
212+ previous: DIRECTMANIPULATION_STATUS,
213+ ) -> windows_core::Result<()> {
214+ if current == previous {
215+ return Ok(());
216+ }
217+
218+ // A new gesture interrupted inertia, so end the old sequence.
219+ if current == DIRECTMANIPULATION_RUNNING && previous == DIRECTMANIPULATION_INERTIA {
220+ self.end_gesture();
221+ }
222+
223+ if current == DIRECTMANIPULATION_READY {
224+ self.end_gesture();
225+
226+ // Reset the content transform so the viewport is ready for the next gesture.
227+ // ZoomToRect triggers a second RUNNING -> READY cycle, so prevent an infinite loop here.
228+ if self.last_scale.get() != 1.0
229+ || self.last_x_offset.get() != 0.0
230+ || self.last_y_offset.get() != 0.0
231+ {
232+ if let Some(viewport) = viewport.as_ref() {
233+ unsafe {
234+ viewport
235+ .ZoomToRect(
236+ 0.0,
237+ 0.0,
238+ DEFAULT_VIEWPORT_SIZE as f32,
239+ DEFAULT_VIEWPORT_SIZE as f32,
240+ false,
241+ )
242+ .log_err();
243+ }
244+ }
245+ }
246+
247+ self.last_scale.set(1.0);
248+ self.last_x_offset.set(0.0);
249+ self.last_y_offset.set(0.0);
250+ }
251+
252+ Ok(())
253+ }
254+
255+ fn OnViewportUpdated(
256+ &self,
257+ _viewport: windows_core::Ref<'_, IDirectManipulationViewport>,
258+ ) -> windows_core::Result<()> {
259+ Ok(())
260+ }
261+
262+ fn OnContentUpdated(
263+ &self,
264+ _viewport: windows_core::Ref<'_, IDirectManipulationViewport>,
265+ content: windows_core::Ref<'_, IDirectManipulationContent>,
266+ ) -> windows_core::Result<()> {
267+ let content = content.as_ref().ok_or(E_POINTER)?;
268+
269+ // Get the 6-element content transform: [scale, 0, 0, scale, tx, ty]
270+ let mut xform = [0.0f32; 6];
271+ unsafe {
272+ content.GetContentTransform(&mut xform)?;
273+ }
274+
275+ let scale = xform[0];
276+ let scale_factor = self.scale_factor.get();
277+ let x_offset = xform[4] / scale_factor;
278+ let y_offset = xform[5] / scale_factor;
279+
280+ if scale == 0.0 {
281+ return Ok(());
282+ }
283+
284+ let last_scale = self.last_scale.get();
285+ let last_x = self.last_x_offset.get();
286+ let last_y = self.last_y_offset.get();
287+
288+ if float_equals(scale, last_scale)
289+ && float_equals(x_offset, last_x)
290+ && float_equals(y_offset, last_y)
291+ {
292+ return Ok(());
293+ }
294+
295+ let position = self.mouse_position();
296+ let modifiers = current_modifiers();
297+
298+ // Direct Manipulation reports both translation and scale in every content update.
299+ // Translation values can shift during a pinch due to the zoom center shifting.
300+ // We classify each gesture as either scroll or pinch and only emit one type of event.
301+ // We allow Scroll -> Pinch (a pinch can start with a small pan) but not the reverse.
302+ if !float_equals(scale, 1.0) {
303+ if self.gesture_kind.get() != GestureKind::Pinch {
304+ self.end_gesture();
305+ self.gesture_kind.set(GestureKind::Pinch);
306+ self.pending_events
307+ .borrow_mut()
308+ .push(PlatformInput::Pinch(PinchEvent {
309+ position,
310+ delta: 0.0,
311+ modifiers,
312+ phase: TouchPhase::Started,
313+ }));
314+ }
315+ } else if self.gesture_kind.get() == GestureKind::None {
316+ self.gesture_kind.set(GestureKind::Scroll);
317+ self.scroll_phase.set(TouchPhase::Started);
318+ }
319+
320+ match self.gesture_kind.get() {
321+ GestureKind::Scroll => {
322+ let dx = x_offset - last_x;
323+ let dy = y_offset - last_y;
324+ let touch_phase = self.scroll_phase.get();
325+ self.scroll_phase.set(TouchPhase::Moved);
326+ self.pending_events
327+ .borrow_mut()
328+ .push(PlatformInput::Scroll(ScrollEvent {
329+ position,
330+ delta: ScrollDelta::Pixels(point(px(dx), px(dy))),
331+ modifiers,
332+ touch_phase,
333+ source: ScrollSource::Pointer,
334+ }));
335+ }
336+ GestureKind::Pinch => {
337+ let scale_delta = scale / last_scale;
338+ self.pending_events
339+ .borrow_mut()
340+ .push(PlatformInput::Pinch(PinchEvent {
341+ position,
342+ delta: scale_delta - 1.0,
343+ modifiers,
344+ phase: TouchPhase::Moved,
345+ }));
346+ }
347+ GestureKind::None => {}
348+ }
349+
350+ self.last_scale.set(scale);
351+ self.last_x_offset.set(x_offset);
352+ self.last_y_offset.set(y_offset);
353+
354+ Ok(())
355+ }
356+}
357+
358+fn float_equals(f1: f32, f2: f32) -> bool {
359+ const EPSILON_SCALE: f32 = 0.00001;
360+ (f1 - f2).abs() < EPSILON_SCALE * f1.abs().max(f2.abs()).max(EPSILON_SCALE)
361+}
vendor/gpui-pre-windows/src/direct_write.rsadded+2076 -0

Diff too large; view file

@@ -0,0 +1,2076 @@
1+use std::{
2+ borrow::Cow,
3+ ffi::{c_uint, c_void},
4+ mem::ManuallyDrop,
5+};
6+
7+use anyhow::{Context, Result};
8+use collections::HashMap;
9+use gpui_util::{ResultExt, maybe};
10+use parking_lot::{RwLock, RwLockUpgradableReadGuard};
11+use smallvec::SmallVec;
12+use windows::{
13+ Win32::{
14+ Foundation::*,
15+ Globalization::GetUserDefaultLocaleName,
16+ Graphics::{DirectWrite::*, Gdi::LOGFONTW},
17+ System::SystemServices::LOCALE_NAME_MAX_LENGTH,
18+ UI::WindowsAndMessaging::*,
19+ },
20+ core::*,
21+};
22+use windows_numerics::Vector2;
23+
24+use crate::*;
25+use gpui::*;
26+
27+#[derive(Debug)]
28+struct FontInfo {
29+ font_family_h: HSTRING,
30+ font_face: IDWriteFontFace3,
31+ features: IDWriteTypography,
32+ fallbacks: Option<IDWriteFontFallback>,
33+ font_collection: IDWriteFontCollection1,
34+}
35+
36+pub(crate) struct DirectWriteTextSystem {
37+ components: DirectWriteComponents,
38+ state: RwLock<DirectWriteState>,
39+}
40+
41+struct DirectWriteComponents {
42+ locale: HSTRING,
43+ factory: IDWriteFactory5,
44+ in_memory_loader: IDWriteInMemoryFontFileLoader,
45+ builder: IDWriteFontSetBuilder1,
46+ text_renderer: TextRendererWrapper,
47+ system_ui_font_name: SharedString,
48+ system_subpixel_rendering: bool,
49+}
50+
51+impl Drop for DirectWriteComponents {
52+ fn drop(&mut self) {
53+ unsafe {
54+ let _ = self
55+ .factory
56+ .UnregisterFontFileLoader(&self.in_memory_loader);
57+ }
58+ }
59+}
60+
61+struct DirectWriteState {
62+ system_font_collection: IDWriteFontCollection1,
63+ custom_font_collection: IDWriteFontCollection1,
64+ fonts: Vec<FontInfo>,
65+ font_to_font_id: HashMap<Font, FontId>,
66+ font_info_cache: HashMap<usize, FontId>,
67+ layout_line_scratch: Vec<u16>,
68+}
69+
70+impl DirectWriteTextSystem {
71+ pub(crate) fn new() -> Result<Self> {
72+ let factory: IDWriteFactory5 = unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)? };
73+ // The `IDWriteInMemoryFontFileLoader` here is supported starting from
74+ // Windows 10 Creators Update, which consequently requires the entire
75+ // `DirectWriteTextSystem` to run on `win10 1703`+.
76+ let in_memory_loader = unsafe { factory.CreateInMemoryFontFileLoader()? };
77+ unsafe { factory.RegisterFontFileLoader(&in_memory_loader)? };
78+ let builder = unsafe { factory.CreateFontSetBuilder()? };
79+ let mut locale = [0u16; LOCALE_NAME_MAX_LENGTH as usize];
80+ unsafe { GetUserDefaultLocaleName(&mut locale) };
81+ let locale = HSTRING::from_wide(&locale);
82+ let text_renderer = TextRendererWrapper::new(locale.clone());
83+
84+ let system_subpixel_rendering = get_system_subpixel_rendering();
85+ let system_ui_font_name = get_system_ui_font_name();
86+ let components = DirectWriteComponents {
87+ locale,
88+ factory,
89+ in_memory_loader,
90+ builder,
91+ text_renderer,
92+ system_ui_font_name,
93+ system_subpixel_rendering,
94+ };
95+
96+ let system_font_collection = unsafe {
97+ let mut result = None;
98+ components
99+ .factory
100+ .GetSystemFontCollection(false, &mut result, true)?;
101+ result.context("Failed to get system font collection")?
102+ };
103+ let custom_font_set = unsafe { components.builder.CreateFontSet()? };
104+ let custom_font_collection = unsafe {
105+ components
106+ .factory
107+ .CreateFontCollectionFromFontSet(&custom_font_set)?
108+ };
109+
110+ Ok(Self {
111+ components,
112+ state: RwLock::new(DirectWriteState {
113+ system_font_collection,
114+ custom_font_collection,
115+ fonts: Vec::new(),
116+ font_to_font_id: HashMap::default(),
117+ font_info_cache: HashMap::default(),
118+ layout_line_scratch: Vec::new(),
119+ }),
120+ })
121+ }
122+}
123+
124+impl PlatformTextSystem for DirectWriteTextSystem {
125+ fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
126+ self.state.write().add_fonts(&self.components, fonts)
127+ }
128+
129+ fn all_font_names(&self) -> Vec<String> {
130+ self.state.read().all_font_names(&self.components)
131+ }
132+
133+ fn font_id(&self, font: &Font) -> Result<FontId> {
134+ let lock = self.state.upgradable_read();
135+ if let Some(font_id) = lock.font_to_font_id.get(font) {
136+ Ok(*font_id)
137+ } else {
138+ RwLockUpgradableReadGuard::upgrade(lock)
139+ .select_and_cache_font(&self.components, font)
140+ .with_context(|| format!("Failed to select font: {:?}", font))
141+ }
142+ }
143+
144+ fn font_metrics(&self, font_id: FontId) -> FontMetrics {
145+ self.state.read().font_metrics(font_id)
146+ }
147+
148+ fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
149+ self.state.read().get_typographic_bounds(font_id, glyph_id)
150+ }
151+
152+ fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
153+ self.state.read().get_advance(font_id, glyph_id)
154+ }
155+
156+ fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
157+ self.state.read().glyph_for_char(font_id, ch)
158+ }
159+
160+ fn glyph_raster_bounds(
161+ &self,
162+ params: &RenderGlyphParams,
163+ ) -> anyhow::Result<Bounds<DevicePixels>> {
164+ self.state.read().raster_bounds(&self.components, params)
165+ }
166+
167+ fn rasterize_glyph(
168+ &self,
169+ params: &RenderGlyphParams,
170+ raster_bounds: Bounds<DevicePixels>,
171+ ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
172+ self.state
173+ .read()
174+ .rasterize_glyph(&self.components, params, raster_bounds)
175+ }
176+
177+ fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
178+ self.state
179+ .write()
180+ .layout_line(&self.components, text, font_size, runs)
181+ .log_err()
182+ .unwrap_or(LineLayout {
183+ font_size,
184+ ..Default::default()
185+ })
186+ }
187+
188+ fn recommended_rendering_mode(
189+ &self,
190+ _font_id: FontId,
191+ _font_size: Pixels,
192+ ) -> TextRenderingMode {
193+ if self.components.system_subpixel_rendering {
194+ TextRenderingMode::Subpixel
195+ } else {
196+ TextRenderingMode::Grayscale
197+ }
198+ }
199+}
200+
201+impl DirectWriteState {
202+ fn select_and_cache_font(
203+ &mut self,
204+ components: &DirectWriteComponents,
205+ font: &Font,
206+ ) -> Option<FontId> {
207+ let select_font = |this: &mut DirectWriteState, font: &Font| -> Option<FontId> {
208+ let info = [&this.custom_font_collection, &this.system_font_collection]
209+ .into_iter()
210+ .find_map(|font_collection| unsafe {
211+ DirectWriteState::make_font_from_font_collection(
212+ font,
213+ font_collection,
214+ &components.factory,
215+ &this.system_font_collection,
216+ &components.system_ui_font_name,
217+ )
218+ })?;
219+
220+ let font_id = FontId(this.fonts.len());
221+ let font_face_key = info.font_face.cast::<IUnknown>().unwrap().as_raw().addr();
222+ this.fonts.push(info);
223+ this.font_info_cache.insert(font_face_key, font_id);
224+ Some(font_id)
225+ };
226+
227+ let mut font_id = select_font(self, font);
228+ if font_id.is_none() {
229+ // try updating system fonts and reselect
230+ let mut collection = None;
231+ let font_collection_updated = unsafe {
232+ components
233+ .factory
234+ .GetSystemFontCollection(false, &mut collection, true)
235+ }
236+ .log_err()
237+ .is_some();
238+ if font_collection_updated && let Some(collection) = collection {
239+ self.system_font_collection = collection;
240+ }
241+ font_id = select_font(self, font);
242+ };
243+ let font_id = font_id?;
244+ self.font_to_font_id.insert(font.clone(), font_id);
245+ Some(font_id)
246+ }
247+
248+ fn add_fonts(
249+ &mut self,
250+ components: &DirectWriteComponents,
251+ fonts: Vec<Cow<'static, [u8]>>,
252+ ) -> Result<()> {
253+ for font_data in fonts {
254+ match font_data {
255+ Cow::Borrowed(data) => unsafe {
256+ let font_file = components
257+ .in_memory_loader
258+ .CreateInMemoryFontFileReference(
259+ &components.factory,
260+ data.as_ptr().cast(),
261+ data.len() as _,
262+ None,
263+ )?;
264+ components.builder.AddFontFile(&font_file)?;
265+ },
266+ Cow::Owned(data) => unsafe {
267+ let font_file = components
268+ .in_memory_loader
269+ .CreateInMemoryFontFileReference(
270+ &components.factory,
271+ data.as_ptr().cast(),
272+ data.len() as _,
273+ None,
274+ )?;
275+ components.builder.AddFontFile(&font_file)?;
276+ },
277+ }
278+ }
279+ let set = unsafe { components.builder.CreateFontSet()? };
280+ let collection = unsafe { components.factory.CreateFontCollectionFromFontSet(&set)? };
281+ self.custom_font_collection = collection;
282+
283+ Ok(())
284+ }
285+
286+ fn generate_font_fallbacks(
287+ fallbacks: &FontFallbacks,
288+ factory: &IDWriteFactory5,
289+ system_font_collection: &IDWriteFontCollection1,
290+ ) -> Result<Option<IDWriteFontFallback>> {
291+ let fallback_list = fallbacks.fallback_list();
292+ if fallback_list.is_empty() {
293+ return Ok(None);
294+ }
295+ unsafe {
296+ let builder = factory.CreateFontFallbackBuilder()?;
297+ let font_set = &system_font_collection.GetFontSet()?;
298+ let mut unicode_ranges = Vec::new();
299+ for family_name in fallback_list {
300+ let family_name = HSTRING::from(family_name);
301+ let Some(fonts) = font_set
302+ .GetMatchingFonts(
303+ &family_name,
304+ DWRITE_FONT_WEIGHT_NORMAL,
305+ DWRITE_FONT_STRETCH_NORMAL,
306+ DWRITE_FONT_STYLE_NORMAL,
307+ )
308+ .log_err()
309+ else {
310+ continue;
311+ };
312+ let Ok(font_face) = fonts.GetFontFaceReference(0) else {
313+ continue;
314+ };
315+ let font = font_face.CreateFontFace()?;
316+ let mut count = 0;
317+ font.GetUnicodeRanges(None, &mut count).ok();
318+ if count == 0 {
319+ continue;
320+ }
321+ unicode_ranges.clear();
322+ unicode_ranges.resize_with(count as usize, DWRITE_UNICODE_RANGE::default);
323+ let Some(_) = font
324+ .GetUnicodeRanges(Some(&mut unicode_ranges), &mut count)
325+ .log_err()
326+ else {
327+ continue;
328+ };
329+ builder.AddMapping(
330+ &unicode_ranges,
331+ &[family_name.as_ptr()],
332+ None,
333+ None,
334+ None,
335+ 1.0,
336+ )?;
337+ }
338+ let system_fallbacks = factory.GetSystemFontFallback()?;
339+ builder.AddMappings(&system_fallbacks)?;
340+ Ok(Some(builder.CreateFontFallback()?))
341+ }
342+ }
343+
344+ unsafe fn generate_font_features(
345+ factory: &IDWriteFactory5,
346+ font_features: &FontFeatures,
347+ ) -> Result<IDWriteTypography> {
348+ let direct_write_features = unsafe { factory.CreateTypography()? };
349+ apply_font_features(&direct_write_features, font_features)?;
350+ Ok(direct_write_features)
351+ }
352+
353+ unsafe fn make_font_from_font_collection(
354+ &Font {
355+ ref family,
356+ ref features,
357+ ref fallbacks,
358+ weight,
359+ style,
360+ }: &Font,
361+ collection: &IDWriteFontCollection1,
362+ factory: &IDWriteFactory5,
363+ system_font_collection: &IDWriteFontCollection1,
364+ system_ui_font_name: &SharedString,
365+ ) -> Option<FontInfo> {
366+ const SYSTEM_UI_FONT_NAME: &str = ".SystemUIFont";
367+ let family = if family == SYSTEM_UI_FONT_NAME {
368+ system_ui_font_name
369+ } else {
370+ gpui::font_name_with_fallbacks_shared(&family, &system_ui_font_name)
371+ };
372+ let fontset = unsafe { collection.GetFontSet().log_err()? };
373+ let font_family_h = HSTRING::from(family.as_str());
374+ let font = unsafe {
375+ fontset
376+ .GetMatchingFonts(
377+ &font_family_h,
378+ font_weight_to_dwrite(weight),
379+ DWRITE_FONT_STRETCH_NORMAL,
380+ font_style_to_dwrite(style),
381+ )
382+ .log_err()?
383+ };
384+ let total_number = unsafe { font.GetFontCount() };
385+ for index in 0..total_number {
386+ let res = maybe!({
387+ let font_face_ref = unsafe { font.GetFontFaceReference(index).log_err()? };
388+ let font_face = unsafe { font_face_ref.CreateFontFace().log_err()? };
389+ let direct_write_features =
390+ unsafe { Self::generate_font_features(factory, features).log_err()? };
391+ let fallbacks = fallbacks.as_ref().and_then(|fallbacks| {
392+ Self::generate_font_fallbacks(fallbacks, factory, system_font_collection)
393+ .log_err()
394+ .flatten()
395+ });
396+ let font_info = FontInfo {
397+ font_family_h: font_family_h.clone(),
398+ font_face,
399+ features: direct_write_features,
400+ fallbacks,
401+ font_collection: collection.clone(),
402+ };
403+ Some(font_info)
404+ });
405+ if res.is_some() {
406+ return res;
407+ }
408+ }
409+ None
410+ }
411+
412+ fn layout_line(
413+ &mut self,
414+ components: &DirectWriteComponents,
415+ text: &str,
416+ font_size: Pixels,
417+ font_runs: &[FontRun],
418+ ) -> Result<LineLayout> {
419+ if !text.contains(is_line_separator) {
420+ return self.layout_line_without_separators(components, text, font_size, font_runs);
421+ }
422+
423+ // DirectWrite honors mandatory breaks even without wrapping. Keep each
424+ // separator at a segment's end so no subsequent text moves to a new baseline.
425+ let mut layout = LineLayout {
426+ font_size,
427+ len: text.len(),
428+ ..Default::default()
429+ };
430+ let mut remaining_runs = font_runs;
431+ let mut run_offset = 0;
432+ let mut text_offset = 0;
433+ let mut segment_runs = SmallVec::<[FontRun; 4]>::new();
434+ for segment in text.split_inclusive(is_line_separator) {
435+ segment_runs.clear();
436+ let mut remaining_bytes = segment.len();
437+ while remaining_bytes > 0 {
438+ let Some(run) = remaining_runs.first() else {
439+ break;
440+ };
441+ let len = remaining_bytes.min(run.len - run_offset);
442+ if len > 0 {
443+ segment_runs.push(FontRun {
444+ len,
445+ font_id: run.font_id,
446+ });
447+ }
448+ remaining_bytes -= len;
449+ run_offset += len;
450+ if run_offset == run.len {
451+ remaining_runs = &remaining_runs[1..];
452+ run_offset = 0;
453+ }
454+ }
455+
456+ let segment_layout =
457+ self.layout_line_without_separators(components, segment, font_size, &segment_runs)?;
458+ for mut run in segment_layout.runs {
459+ for glyph in &mut run.glyphs {
460+ glyph.index += text_offset;
461+ glyph.position.x += layout.width;
462+ }
463+ if let Some(last) = layout.runs.last_mut()
464+ && last.font_id == run.font_id
465+ {
466+ last.glyphs.append(&mut run.glyphs);
467+ } else {
468+ layout.runs.push(run);
469+ }
470+ }
471+ layout.width += segment_layout.width;
472+ layout.ascent = layout.ascent.max(segment_layout.ascent);
473+ layout.descent = layout.descent.max(segment_layout.descent);
474+ text_offset += segment.len();
475+ }
476+ Ok(layout)
477+ }
478+
479+ fn layout_line_without_separators(
480+ &mut self,
481+ components: &DirectWriteComponents,
482+ text: &str,
483+ font_size: Pixels,
484+ font_runs: &[FontRun],
485+ ) -> Result<LineLayout> {
486+ if font_runs.is_empty() {
487+ return Ok(LineLayout {
488+ font_size,
489+ ..Default::default()
490+ });
491+ }
492+ unsafe {
493+ self.layout_line_scratch.clear();
494+ self.layout_line_scratch.extend(text.encode_utf16());
495+ let text_wide = &*self.layout_line_scratch;
496+
497+ let mut utf8_offset = 0usize;
498+ let mut utf16_offset = 0u32;
499+ let text_layout = {
500+ let first_run = &font_runs[0];
501+ let font_info = &self.fonts[first_run.font_id.0];
502+ let collection = &font_info.font_collection;
503+ let format: IDWriteTextFormat1 = components
504+ .factory
505+ .CreateTextFormat(
506+ &font_info.font_family_h,
507+ collection,
508+ font_info.font_face.GetWeight(),
509+ font_info.font_face.GetStyle(),
510+ DWRITE_FONT_STRETCH_NORMAL,
511+ font_size.as_f32(),
512+ &components.locale,
513+ )?
514+ .cast()?;
515+ if let Some(ref fallbacks) = font_info.fallbacks {
516+ format.SetFontFallback(fallbacks)?;
517+ }
518+
519+ let layout = components.factory.CreateTextLayout(
520+ text_wide,
521+ &format,
522+ f32::INFINITY,
523+ f32::INFINITY,
524+ )?;
525+ let current_text = &text[utf8_offset..(utf8_offset + first_run.len)];
526+ utf8_offset += first_run.len;
527+ let current_text_utf16_length = current_text.encode_utf16().count() as u32;
528+ let text_range = DWRITE_TEXT_RANGE {
529+ startPosition: utf16_offset,
530+ length: current_text_utf16_length,
531+ };
532+ layout.SetTypography(&font_info.features, text_range)?;
533+ utf16_offset += current_text_utf16_length;
534+
535+ layout
536+ };
537+
538+ let (ascent, descent) = {
539+ let mut first_metrics = [DWRITE_LINE_METRICS::default(); 4];
540+ let mut line_count = 0u32;
541+ text_layout.GetLineMetrics(Some(&mut first_metrics), &mut line_count)?;
542+ (
543+ px(first_metrics[0].baseline),
544+ px(first_metrics[0].height - first_metrics[0].baseline),
545+ )
546+ };
547+ let mut break_ligatures = true;
548+ for run in &font_runs[1..] {
549+ let font_info = &self.fonts[run.font_id.0];
550+ let current_text = &text[utf8_offset..(utf8_offset + run.len)];
551+ utf8_offset += run.len;
552+ let current_text_utf16_length = current_text.encode_utf16().count() as u32;
553+
554+ let collection = &font_info.font_collection;
555+ let text_range = DWRITE_TEXT_RANGE {
556+ startPosition: utf16_offset,
557+ length: current_text_utf16_length,
558+ };
559+ utf16_offset += current_text_utf16_length;
560+ text_layout.SetFontCollection(collection, text_range)?;
561+ text_layout.SetFontFamilyName(&font_info.font_family_h, text_range)?;
562+ let font_size = if break_ligatures {
563+ font_size.as_f32().next_up()
564+ } else {
565+ font_size.as_f32()
566+ };
567+ text_layout.SetFontSize(font_size, text_range)?;
568+ text_layout.SetFontStyle(font_info.font_face.GetStyle(), text_range)?;
569+ text_layout.SetFontWeight(font_info.font_face.GetWeight(), text_range)?;
570+ text_layout.SetTypography(&font_info.features, text_range)?;
571+
572+ break_ligatures = !break_ligatures;
573+ }
574+
575+ let mut runs = Vec::new();
576+ let mut renderer_context = RendererContext {
577+ text_system: self,
578+ components,
579+ index_converter: StringIndexConverter::new(text),
580+ runs: &mut runs,
581+ layout: &text_layout,
582+ width: 0.0,
583+ };
584+ text_layout.Draw(
585+ Some((&raw mut renderer_context).cast::<c_void>().cast_const()),
586+ &components.text_renderer.0,
587+ 0.0,
588+ 0.0,
589+ )?;
590+ let width = px(renderer_context.width);
591+
592+ Ok(LineLayout {
593+ font_size,
594+ width,
595+ ascent,
596+ descent,
597+ runs,
598+ len: text.len(),
599+ })
600+ }
601+ }
602+
603+ fn font_metrics(&self, font_id: FontId) -> FontMetrics {
604+ unsafe {
605+ let font_info = &self.fonts[font_id.0];
606+ let mut metrics = std::mem::zeroed();
607+ font_info.font_face.GetMetrics(&mut metrics);
608+
609+ FontMetrics {
610+ units_per_em: metrics.Base.designUnitsPerEm as _,
611+ ascent: metrics.Base.ascent as _,
612+ descent: -(metrics.Base.descent as f32),
613+ line_gap: metrics.Base.lineGap as _,
614+ underline_position: metrics.Base.underlinePosition as _,
615+ underline_thickness: metrics.Base.underlineThickness as _,
616+ cap_height: metrics.Base.capHeight as _,
617+ x_height: metrics.Base.xHeight as _,
618+ bounding_box: Bounds {
619+ origin: Point {
620+ x: metrics.glyphBoxLeft as _,
621+ y: metrics.glyphBoxBottom as _,
622+ },
623+ size: Size {
624+ width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,
625+ height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,
626+ },
627+ },
628+ }
629+ }
630+ }
631+
632+ fn with_glyph_run<R>(
633+ &self,
634+ params: &RenderGlyphParams,
635+ f: impl FnOnce(&DWRITE_GLYPH_RUN, Vector2) -> R,
636+ ) -> R {
637+ let font = &self.fonts[params.font_id.0];
638+ let glyph_id = [params.glyph_id.0 as u16];
639+ let advance = [0.0];
640+ let offset = [DWRITE_GLYPH_OFFSET::default()];
641+ let glyph_run = DWRITE_GLYPH_RUN {
642+ fontFace: ManuallyDrop::new(Some(unsafe { std::ptr::read(&***font.font_face) })),
643+ fontEmSize: params.font_size.as_f32() * params.scale_factor,
644+ glyphCount: 1,
645+ glyphIndices: glyph_id.as_ptr(),
646+ glyphAdvances: advance.as_ptr(),
647+ glyphOffsets: offset.as_ptr(),
648+ isSideways: BOOL(0),
649+ bidiLevel: 0,
650+ };
651+ let baseline_origin = Vector2::new(
652+ params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32,
653+ params.subpixel_variant.y as f32 / gpui::SUBPIXEL_VARIANTS_Y as f32,
654+ );
655+ f(&glyph_run, baseline_origin)
656+ }
657+
658+ fn rendering_mode(
659+ &self,
660+ params: &RenderGlyphParams,
661+ ) -> Result<(DWRITE_RENDERING_MODE1, DWRITE_GRID_FIT_MODE)> {
662+ let font = &self.fonts[params.font_id.0];
663+ let mut rendering_mode = DWRITE_RENDERING_MODE1::default();
664+ let mut grid_fit_mode = DWRITE_GRID_FIT_MODE::default();
665+ unsafe {
666+ font.font_face.GetRecommendedRenderingMode(
667+ params.font_size.as_f32() * params.scale_factor,
668+ 96.0,
669+ 96.0,
670+ None,
671+ false,
672+ DWRITE_OUTLINE_THRESHOLD_ANTIALIASED,
673+ DWRITE_MEASURING_MODE_NATURAL,
674+ None,
675+ &mut rendering_mode,
676+ &mut grid_fit_mode,
677+ )?;
678+ }
679+ // We rasterize into bitmaps, which outline rendering can't produce.
680+ let rendering_mode = match rendering_mode {
681+ DWRITE_RENDERING_MODE1_OUTLINE => DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,
682+ mode => mode,
683+ };
684+ Ok((rendering_mode, grid_fit_mode))
685+ }
686+
687+ fn glyph_analysis(
688+ &self,
689+ components: &DirectWriteComponents,
690+ params: &RenderGlyphParams,
691+ ) -> Result<IDWriteGlyphRunAnalysis> {
692+ let (rendering_mode, grid_fit_mode) = self.rendering_mode(params)?;
693+ let antialias_mode = if params.subpixel_rendering {
694+ DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE
695+ } else {
696+ DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE
697+ };
698+ self.with_glyph_run(params, |glyph_run, origin| unsafe {
699+ Ok(components.factory.CreateGlyphRunAnalysis(
700+ glyph_run,
701+ None,
702+ rendering_mode,
703+ DWRITE_MEASURING_MODE_NATURAL,
704+ grid_fit_mode,
705+ antialias_mode,
706+ origin.X,
707+ origin.Y,
708+ )?)
709+ })
710+ }
711+
712+ fn color_layers(
713+ &self,
714+ components: &DirectWriteComponents,
715+ params: &RenderGlyphParams,
716+ ) -> Result<Vec<ColorLayer>> {
717+ let (rendering_mode, grid_fit_mode) = self.rendering_mode(params)?;
718+ self.with_glyph_run(params, |glyph_run, origin| {
719+ // todo: support formats other than COLR
720+ let color_runs = match unsafe {
721+ components.factory.TranslateColorGlyphRun(
722+ origin,
723+ glyph_run,
724+ None,
725+ DWRITE_GLYPH_IMAGE_FORMATS_COLR,
726+ DWRITE_MEASURING_MODE_NATURAL,
727+ None,
728+ 0,
729+ )
730+ } {
731+ Ok(color_runs) => color_runs,
732+ Err(error) if error.code() == DWRITE_E_NOCOLOR => return Ok(Vec::new()),
733+ Err(error) => return Err(error.into()),
734+ };
735+ let mut layers = Vec::new();
736+ while unsafe { color_runs.MoveNext() }?.as_bool() {
737+ let color_run = unsafe { &*color_runs.GetCurrentRun()? };
738+ let image_format =
739+ color_run.glyphImageFormat & !DWRITE_GLYPH_IMAGE_FORMATS_TRUETYPE;
740+ if image_format != DWRITE_GLYPH_IMAGE_FORMATS_COLR {
741+ continue;
742+ }
743+ let analysis = unsafe {
744+ components.factory.CreateGlyphRunAnalysis(
745+ &color_run.Base.glyphRun,
746+ None,
747+ rendering_mode,
748+ DWRITE_MEASURING_MODE_NATURAL,
749+ grid_fit_mode,
750+ DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,
751+ color_run.Base.baselineOriginX,
752+ color_run.Base.baselineOriginY,
753+ )?
754+ };
755+ let color = color_run.Base.runColor;
756+ layers.push(ColorLayer {
757+ color: Rgba {
758+ r: color.r,
759+ g: color.g,
760+ b: color.b,
761+ a: color.a,
762+ },
763+ analysis,
764+ });
765+ }
766+ Ok(layers)
767+ })
768+ }
769+
770+ fn raster_bounds(
771+ &self,
772+ components: &DirectWriteComponents,
773+ params: &RenderGlyphParams,
774+ ) -> Result<Bounds<DevicePixels>> {
775+ let color_layers = if params.is_emoji {
776+ self.color_layers(components, params)
777+ .context("Failed to measure color glyph layers")
778+ .log_err()
779+ .unwrap_or_default()
780+ } else {
781+ Vec::new()
782+ };
783+ let analyses: SmallVec<[IDWriteGlyphRunAnalysis; 1]> = if color_layers.is_empty() {
784+ smallvec::smallvec![self.glyph_analysis(components, params)?]
785+ } else {
786+ color_layers
787+ .into_iter()
788+ .map(|layer| layer.analysis)
789+ .collect()
790+ };
791+ let texture_type = if params.subpixel_rendering {
792+ DWRITE_TEXTURE_CLEARTYPE_3x1
793+ } else {
794+ DWRITE_TEXTURE_ALIASED_1x1
795+ };
796+
797+ let mut union: Option<Bounds<DevicePixels>> = None;
798+ for analysis in analyses {
799+ let rect = unsafe { analysis.GetAlphaTextureBounds(texture_type)? };
800+ let bounds = Bounds::from_corners(
801+ point(rect.left.into(), rect.top.into()),
802+ point(rect.right.into(), rect.bottom.into()),
803+ );
804+ if !bounds.is_empty() {
805+ union = Some(union.map_or(bounds, |union| union.union(&bounds)));
806+ }
807+ }
808+ Ok(union.unwrap_or_default())
809+ }
810+
811+ fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
812+ let font_info = &self.fonts[font_id.0];
813+ let codepoints = ch as u32;
814+ let mut glyph_indices = 0u16;
815+ unsafe {
816+ font_info
817+ .font_face
818+ .GetGlyphIndices(&raw const codepoints, 1, &raw mut glyph_indices)
819+ .log_err()
820+ }
821+ .map(|_| GlyphId(glyph_indices as u32))
822+ }
823+
824+ fn rasterize_glyph(
825+ &self,
826+ components: &DirectWriteComponents,
827+ params: &RenderGlyphParams,
828+ glyph_bounds: Bounds<DevicePixels>,
829+ ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
830+ if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
831+ anyhow::bail!("glyph bounds are empty");
832+ }
833+
834+ let bitmap_data = if params.is_emoji {
835+ if let Ok(color) = self.rasterize_color(components, params, glyph_bounds) {
836+ color
837+ } else {
838+ let monochrome = self.rasterize_monochrome(components, params, glyph_bounds)?;
839+ monochrome
840+ .into_iter()
841+ .flat_map(|pixel| [0, 0, 0, pixel])
842+ .collect::<Vec<_>>()
843+ }
844+ } else {
845+ self.rasterize_monochrome(components, params, glyph_bounds)?
846+ };
847+
848+ Ok((glyph_bounds.size, bitmap_data))
849+ }
850+
851+ fn rasterize_monochrome(
852+ &self,
853+ components: &DirectWriteComponents,
854+ params: &RenderGlyphParams,
855+ glyph_bounds: Bounds<DevicePixels>,
856+ ) -> Result<Vec<u8>> {
857+ let glyph_analysis = self.glyph_analysis(components, params)?;
858+ if !params.subpixel_rendering {
859+ let mut bitmap_data =
860+ vec![0u8; glyph_bounds.size.width.0 as usize * glyph_bounds.size.height.0 as usize];
861+ unsafe {
862+ glyph_analysis.CreateAlphaTexture(
863+ DWRITE_TEXTURE_ALIASED_1x1,
864+ &RECT {
865+ left: glyph_bounds.origin.x.0,
866+ top: glyph_bounds.origin.y.0,
867+ right: glyph_bounds.size.width.0 + glyph_bounds.origin.x.0,
868+ bottom: glyph_bounds.size.height.0 + glyph_bounds.origin.y.0,
869+ },
870+ &mut bitmap_data,
871+ )?;
872+ }
873+
874+ return Ok(bitmap_data);
875+ }
876+
877+ let width = glyph_bounds.size.width.0 as usize;
878+ let height = glyph_bounds.size.height.0 as usize;
879+ let pixel_count = width * height;
880+
881+ let mut bitmap_data = vec![0u8; pixel_count * 4];
882+
883+ unsafe {
884+ glyph_analysis.CreateAlphaTexture(
885+ DWRITE_TEXTURE_CLEARTYPE_3x1,
886+ &RECT {
887+ left: glyph_bounds.origin.x.0,
888+ top: glyph_bounds.origin.y.0,
889+ right: glyph_bounds.size.width.0 + glyph_bounds.origin.x.0,
890+ bottom: glyph_bounds.size.height.0 + glyph_bounds.origin.y.0,
891+ },
892+ &mut bitmap_data[..pixel_count * 3],
893+ )?;
894+ }
895+
896+ // The output buffer expects RGBA data, so pad the alpha channel with zeros.
897+ for pixel_ix in (0..pixel_count).rev() {
898+ let src = pixel_ix * 3;
899+ let dst = pixel_ix * 4;
900+ (
901+ bitmap_data[dst],
902+ bitmap_data[dst + 1],
903+ bitmap_data[dst + 2],
904+ bitmap_data[dst + 3],
905+ ) = (
906+ bitmap_data[src],
907+ bitmap_data[src + 1],
908+ bitmap_data[src + 2],
909+ 0,
910+ );
911+ }
912+
913+ Ok(bitmap_data)
914+ }
915+
916+ fn rasterize_color(
917+ &self,
918+ components: &DirectWriteComponents,
919+ params: &RenderGlyphParams,
920+ glyph_bounds: Bounds<DevicePixels>,
921+ ) -> Result<Vec<u8>> {
922+ let layers = self.color_layers(components, params)?;
923+ anyhow::ensure!(!layers.is_empty(), "the glyph has no color layers");
924+ let mut bitmap = ColorGlyphBitmap::new(glyph_bounds.size);
925+ let font_info = DirectXRenderer::get_font_info();
926+ let mut coverage = Vec::new();
927+ for layer in layers {
928+ let layer_bounds = unsafe {
929+ layer
930+ .analysis
931+ .GetAlphaTextureBounds(DWRITE_TEXTURE_ALIASED_1x1)?
932+ };
933+ let layer_size = size(
934+ layer_bounds.right - layer_bounds.left,
935+ layer_bounds.bottom - layer_bounds.top,
936+ );
937+ if layer_size.width <= 0 || layer_size.height <= 0 {
938+ continue;
939+ }
940+ coverage.clear();
941+ coverage.resize((layer_size.width * layer_size.height) as usize, 0);
942+ unsafe {
943+ layer.analysis.CreateAlphaTexture(
944+ DWRITE_TEXTURE_ALIASED_1x1,
945+ &layer_bounds,
946+ &mut coverage,
947+ )?
948+ };
949+ bitmap.composite(
950+ layer.color,
951+ bounds(
952+ point(
953+ layer_bounds.left - glyph_bounds.origin.x.0,
954+ layer_bounds.top - glyph_bounds.origin.y.0,
955+ ),
956+ layer_size,
957+ ),
958+ &coverage,
959+ font_info,
960+ );
961+ }
962+ Ok(bitmap.into_straight_bgra())
963+ }
964+
965+ fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
966+ unsafe {
967+ let font = &self.fonts[font_id.0].font_face;
968+ let glyph_indices = [glyph_id.0 as u16];
969+ let mut metrics = [DWRITE_GLYPH_METRICS::default()];
970+ font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
971+
972+ let metrics = &metrics[0];
973+ let advance_width = metrics.advanceWidth as i32;
974+ let advance_height = metrics.advanceHeight as i32;
975+ let left_side_bearing = metrics.leftSideBearing;
976+ let right_side_bearing = metrics.rightSideBearing;
977+ let top_side_bearing = metrics.topSideBearing;
978+ let bottom_side_bearing = metrics.bottomSideBearing;
979+ let vertical_origin_y = metrics.verticalOriginY;
980+
981+ let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;
982+ let width = advance_width - (left_side_bearing + right_side_bearing);
983+ let height = advance_height - (top_side_bearing + bottom_side_bearing);
984+
985+ Ok(Bounds {
986+ origin: Point {
987+ x: left_side_bearing as f32,
988+ y: y_offset as f32,
989+ },
990+ size: Size {
991+ width: width as f32,
992+ height: height as f32,
993+ },
994+ })
995+ }
996+ }
997+
998+ fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
999+ unsafe {
1000+ let font = &self.fonts[font_id.0].font_face;
1001+ let glyph_indices = [glyph_id.0 as u16];
1002+ let mut metrics = [DWRITE_GLYPH_METRICS::default()];
1003+ font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;
1004+
1005+ let metrics = &metrics[0];
1006+
1007+ Ok(Size {
1008+ width: metrics.advanceWidth as f32,
1009+ height: 0.0,
1010+ })
1011+ }
1012+ }
1013+
1014+ fn all_font_names(&self, components: &DirectWriteComponents) -> Vec<String> {
1015+ let mut result =
1016+ get_font_names_from_collection(&self.system_font_collection, &components.locale);
1017+ result.extend(get_font_names_from_collection(
1018+ &self.custom_font_collection,
1019+ &components.locale,
1020+ ));
1021+ result
1022+ }
1023+}
1024+
1025+struct ColorLayer {
1026+ color: Rgba,
1027+ analysis: IDWriteGlyphRunAnalysis,
1028+}
1029+
1030+struct ColorGlyphBitmap {
1031+ width: usize,
1032+ height: usize,
1033+ blue: Vec<f32>,
1034+ green: Vec<f32>,
1035+ red: Vec<f32>,
1036+ alpha: Vec<f32>,
1037+}
1038+
1039+impl ColorGlyphBitmap {
1040+ fn new(size: Size<DevicePixels>) -> Self {
1041+ let width = size.width.0.max(0) as usize;
1042+ let height = size.height.0.max(0) as usize;
1043+ let len = width * height;
1044+ Self {
1045+ width,
1046+ height,
1047+ blue: vec![0.0; len],
1048+ green: vec![0.0; len],
1049+ red: vec![0.0; len],
1050+ alpha: vec![0.0; len],
1051+ }
1052+ }
1053+
1054+ fn composite(
1055+ &mut self,
1056+ color: Rgba,
1057+ bounds: Bounds<i32>,
1058+ coverage: &[u8],
1059+ font_info: &crate::FontInfo,
1060+ ) {
1061+ let Rgba {
1062+ r: red,
1063+ g: green,
1064+ b: blue,
1065+ a: color_alpha,
1066+ } = color;
1067+ let brightness = color_brightness([red, green, blue]);
1068+ let contrast = light_on_dark_contrast(font_info.grayscale_enhanced_contrast, brightness);
1069+
1070+ let width = self.width as i32;
1071+ let height = self.height as i32;
1072+ let left = bounds.origin.x.clamp(0, width);
1073+ let right = (bounds.origin.x + bounds.size.width).clamp(left, width);
1074+ let top = bounds.origin.y.clamp(0, height);
1075+ let bottom = (bounds.origin.y + bounds.size.height).clamp(top, height);
1076+ let len = (right - left) as usize;
1077+ let skipped_columns = (left - bounds.origin.x) as usize;
1078+ for y in top..bottom {
1079+ let coverage_start =
1080+ (y - bounds.origin.y) as usize * bounds.size.width as usize + skipped_columns;
1081+ let pixel_start = y as usize * self.width + left as usize;
1082+ let pixels = pixel_start..pixel_start + len;
1083+ // Equal-length slices let the compiler drop the bounds checks in the loop below.
1084+ let (
1085+ Some(coverage_row),
1086+ Some(blue_row),
1087+ Some(green_row),
1088+ Some(red_row),
1089+ Some(alpha_row),
1090+ ) = (
1091+ coverage.get(coverage_start..coverage_start + len),
1092+ self.blue.get_mut(pixels.clone()),
1093+ self.green.get_mut(pixels.clone()),
1094+ self.red.get_mut(pixels.clone()),
1095+ self.alpha.get_mut(pixels),
1096+ )
1097+ else {
1098+ log::error!("color glyph layer coverage is smaller than its bounds");
1099+ return;
1100+ };
1101+ for index in 0..len {
1102+ let corrected = apply_alpha_correction(
1103+ enhance_contrast(coverage_row[index] as f32 / 255.0, contrast),
1104+ brightness,
1105+ font_info.gamma_ratios,
1106+ );
1107+ let alpha = (corrected * color_alpha).clamp(0.0, 1.0);
1108+ let remaining = 1.0 - alpha;
1109+ blue_row[index] = blue * alpha + blue_row[index] * remaining;
1110+ green_row[index] = green * alpha + green_row[index] * remaining;
1111+ red_row[index] = red * alpha + red_row[index] * remaining;
1112+ alpha_row[index] = alpha + alpha_row[index] * remaining;
1113+ }
1114+ }
1115+ }
1116+
1117+ fn into_straight_bgra(self) -> Vec<u8> {
1118+ let len = self.alpha.len();
1119+ let mut bytes = vec![0u8; len * 4];
1120+ let (blue, green, red, alpha) = (
1121+ &self.blue[..len],
1122+ &self.green[..len],
1123+ &self.red[..len],
1124+ &self.alpha[..len],
1125+ );
1126+ for (index, pixel) in bytes.chunks_exact_mut(4).enumerate() {
1127+ let pixel_alpha = alpha[index].clamp(0.0, 1.0);
1128+ let unpremultiply = if pixel_alpha > 0.0 {
1129+ 1.0 / pixel_alpha
1130+ } else {
1131+ 0.0
1132+ };
1133+ pixel[0] = to_unorm8(blue[index] * unpremultiply);
1134+ pixel[1] = to_unorm8(green[index] * unpremultiply);
1135+ pixel[2] = to_unorm8(red[index] * unpremultiply);
1136+ pixel[3] = to_unorm8(pixel_alpha);
1137+ }
1138+ bytes
1139+ }
1140+}
1141+
1142+fn to_unorm8(value: f32) -> u8 {
1143+ // Not `round()`, since SSE2 has no rounding instruction.
1144+ (value.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
1145+}
1146+
1147+// These mirror the functions of the same names in `alpha_correction.hlsl`.
1148+
1149+fn color_brightness([red, green, blue]: [f32; 3]) -> f32 {
1150+ red * 0.30 + green * 0.59 + blue * 0.11
1151+}
1152+
1153+fn light_on_dark_contrast(enhanced_contrast: f32, brightness: f32) -> f32 {
1154+ enhanced_contrast * (4.0 * (0.75 - brightness)).clamp(0.0, 1.0)
1155+}
1156+
1157+fn enhance_contrast(alpha: f32, contrast: f32) -> f32 {
1158+ alpha * (contrast + 1.0) / (alpha * contrast + 1.0)
1159+}
1160+
1161+fn apply_alpha_correction(alpha: f32, brightness: f32, gamma_ratios: [f32; 4]) -> f32 {
1162+ let brightness_adjustment = gamma_ratios[0] * brightness + gamma_ratios[1];
1163+ let correction =
1164+ brightness_adjustment * alpha + (gamma_ratios[2] * brightness + gamma_ratios[3]);
1165+ alpha + alpha * (1.0 - alpha) * correction
1166+}
1167+
1168+struct TextRendererWrapper(IDWriteTextRenderer);
1169+
1170+impl TextRendererWrapper {
1171+ fn new(locale_str: HSTRING) -> Self {
1172+ let inner = TextRenderer::new(locale_str);
1173+ TextRendererWrapper(inner.into())
1174+ }
1175+}
1176+
1177+#[implement(IDWriteTextRenderer)]
1178+struct TextRenderer {
1179+ locale: HSTRING,
1180+}
1181+
1182+impl TextRenderer {
1183+ fn new(locale: HSTRING) -> Self {
1184+ TextRenderer { locale }
1185+ }
1186+}
1187+
1188+struct RendererContext<'t, 'a, 'b> {
1189+ text_system: &'t mut DirectWriteState,
1190+ components: &'a DirectWriteComponents,
1191+ index_converter: StringIndexConverter<'a>,
1192+ runs: &'b mut Vec<ShapedRun>,
1193+ layout: &'b IDWriteTextLayout,
1194+ width: f32,
1195+}
1196+
1197+#[derive(Debug)]
1198+struct ClusterAnalyzer<'t> {
1199+ utf16_idx: usize,
1200+ glyph_idx: usize,
1201+ glyph_count: usize,
1202+ cluster_map: &'t [u16],
1203+}
1204+
1205+impl<'t> ClusterAnalyzer<'t> {
1206+ fn new(cluster_map: &'t [u16], glyph_count: usize) -> Self {
1207+ ClusterAnalyzer {
1208+ utf16_idx: 0,
1209+ glyph_idx: 0,
1210+ glyph_count,
1211+ cluster_map,
1212+ }
1213+ }
1214+}
1215+
1216+impl Iterator for ClusterAnalyzer<'_> {
1217+ type Item = (usize, usize);
1218+
1219+ fn next(&mut self) -> Option<(usize, usize)> {
1220+ if self.utf16_idx >= self.cluster_map.len() {
1221+ return None; // No more clusters
1222+ }
1223+ let start_utf16_idx = self.utf16_idx;
1224+ let current_glyph = self.cluster_map[start_utf16_idx] as usize;
1225+
1226+ // Find the end of current cluster (where glyph index changes)
1227+ let mut end_utf16_idx = start_utf16_idx + 1;
1228+ while end_utf16_idx < self.cluster_map.len()
1229+ && self.cluster_map[end_utf16_idx] as usize == current_glyph
1230+ {
1231+ end_utf16_idx += 1;
1232+ }
1233+
1234+ let utf16_len = end_utf16_idx - start_utf16_idx;
1235+
1236+ // Calculate glyph count for this cluster
1237+ let next_glyph = if end_utf16_idx < self.cluster_map.len() {
1238+ self.cluster_map[end_utf16_idx] as usize
1239+ } else {
1240+ self.glyph_count
1241+ };
1242+
1243+ let glyph_count = next_glyph - current_glyph;
1244+
1245+ // Update state for next call
1246+ self.utf16_idx = end_utf16_idx;
1247+ self.glyph_idx = next_glyph;
1248+
1249+ Some((utf16_len, glyph_count))
1250+ }
1251+}
1252+
1253+#[allow(non_snake_case)]
1254+impl IDWritePixelSnapping_Impl for TextRenderer_Impl {
1255+ fn IsPixelSnappingDisabled(
1256+ &self,
1257+ _clientdrawingcontext: *const ::core::ffi::c_void,
1258+ ) -> windows::core::Result<BOOL> {
1259+ Ok(BOOL(0))
1260+ }
1261+
1262+ fn GetCurrentTransform(
1263+ &self,
1264+ _clientdrawingcontext: *const ::core::ffi::c_void,
1265+ transform: *mut DWRITE_MATRIX,
1266+ ) -> windows::core::Result<()> {
1267+ unsafe {
1268+ *transform = DWRITE_MATRIX {
1269+ m11: 1.0,
1270+ m12: 0.0,
1271+ m21: 0.0,
1272+ m22: 1.0,
1273+ dx: 0.0,
1274+ dy: 0.0,
1275+ };
1276+ }
1277+ Ok(())
1278+ }
1279+
1280+ fn GetPixelsPerDip(
1281+ &self,
1282+ _clientdrawingcontext: *const ::core::ffi::c_void,
1283+ ) -> windows::core::Result<f32> {
1284+ Ok(1.0)
1285+ }
1286+}
1287+
1288+#[allow(non_snake_case)]
1289+impl IDWriteTextRenderer_Impl for TextRenderer_Impl {
1290+ fn DrawGlyphRun(
1291+ &self,
1292+ clientdrawingcontext: *const ::core::ffi::c_void,
1293+ _baselineoriginx: f32,
1294+ _baselineoriginy: f32,
1295+ _measuringmode: DWRITE_MEASURING_MODE,
1296+ glyphrun: *const DWRITE_GLYPH_RUN,
1297+ glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,
1298+ _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1299+ ) -> windows::core::Result<()> {
1300+ let glyphrun = unsafe { &*glyphrun };
1301+ let glyph_count = glyphrun.glyphCount as usize;
1302+ let desc = unsafe { &*glyphrundescription };
1303+ let text = match glyph_count {
1304+ 0 => Some(unsafe {
1305+ slice_from_nullable(
1306+ desc.string.as_ptr(),
1307+ desc.stringLength as usize,
1308+ "DirectWrite returned a null run string",
1309+ )?
1310+ }),
1311+ _ => None,
1312+ };
1313+ let context = unsafe { &mut *(clientdrawingcontext.cast::<RendererContext>().cast_mut()) };
1314+ let Some(font_face) = glyphrun.fontFace.as_ref() else {
1315+ return Ok(());
1316+ };
1317+ // This `cast()` action here should never fail since we are running on Win10+, and
1318+ // `IDWriteFontFace3` requires Win10
1319+ let Ok(font_face) = &font_face.cast::<IDWriteFontFace3>() else {
1320+ return Err(Error::new(
1321+ DWRITE_E_UNSUPPORTEDOPERATION,
1322+ "Failed to cast font face",
1323+ ));
1324+ };
1325+
1326+ let font_face_key = font_face.cast::<IUnknown>().unwrap().as_raw().addr();
1327+ let font_id = context
1328+ .text_system
1329+ .font_info_cache
1330+ .get(&font_face_key)
1331+ .copied()
1332+ // in some circumstances, we might be getting served a FontFace that we did not create ourselves
1333+ // so create a new font from it and cache it accordingly. The usual culprit here seems to be Segoe UI Symbol
1334+ .map_or_else(
1335+ || {
1336+ let font = font_face_to_font(font_face, &self.locale)
1337+ .ok_or_else(|| Error::new(DWRITE_E_NOFONT, "Failed to create font"))?;
1338+ let font_id = match context.text_system.font_to_font_id.get(&font) {
1339+ Some(&font_id) => font_id,
1340+ None => context
1341+ .text_system
1342+ .select_and_cache_font(context.components, &font)
1343+ .ok_or_else(|| Error::new(DWRITE_E_NOFONT, "Failed to create font"))?,
1344+ };
1345+ context
1346+ .text_system
1347+ .font_info_cache
1348+ .insert(font_face_key, font_id);
1349+ windows::core::Result::Ok(font_id)
1350+ },
1351+ Ok,
1352+ )?;
1353+
1354+ if let Some(text) = text {
1355+ // Tabs have layout advances but no glyph advances. Keep invisible
1356+ // glyphs so LineLayout can map their byte indices to caret positions.
1357+ let mut glyphs = Vec::new();
1358+ for (offset, &character) in text.iter().enumerate() {
1359+ if character != u16::from(b'\t') {
1360+ continue;
1361+ }
1362+ let position = desc.textPosition + offset as u32;
1363+ let mut x = 0.0;
1364+ let mut y = 0.0;
1365+ let mut metrics = DWRITE_HIT_TEST_METRICS::default();
1366+ let mut space = 0;
1367+ unsafe {
1368+ context.layout.HitTestTextPosition(
1369+ position,
1370+ false,
1371+ &mut x,
1372+ &mut y,
1373+ &mut metrics,
1374+ )?;
1375+ font_face.GetGlyphIndices(&u32::from(b' '), 1, &mut space)?;
1376+ }
1377+ context
1378+ .index_converter
1379+ .advance_to_utf16_ix(position as usize);
1380+ glyphs.push(ShapedGlyph {
1381+ id: GlyphId(u32::from(space)),
1382+ position: point(px(context.width), px(0.0)),
1383+ index: context.index_converter.utf8_ix,
1384+ is_emoji: false,
1385+ });
1386+ context.width += metrics.width;
1387+ }
1388+ if !glyphs.is_empty() {
1389+ context.runs.push(ShapedRun { font_id, glyphs });
1390+ }
1391+ } else {
1392+ let color_font = unsafe { font_face.IsColorFont().as_bool() };
1393+
1394+ let glyph_ids = unsafe {
1395+ slice_from_nullable(
1396+ glyphrun.glyphIndices,
1397+ glyph_count,
1398+ "DirectWrite returned a null glyph indices array",
1399+ )?
1400+ };
1401+ let glyph_advances = unsafe {
1402+ slice_from_nullable(
1403+ glyphrun.glyphAdvances,
1404+ glyph_count,
1405+ "DirectWrite returned a null glyph advances array",
1406+ )?
1407+ };
1408+ let glyph_offsets = unsafe {
1409+ slice_from_nullable(
1410+ glyphrun.glyphOffsets,
1411+ glyph_count,
1412+ "DirectWrite returned a null glyph offsets array",
1413+ )?
1414+ };
1415+ let cluster_map = unsafe {
1416+ slice_from_nullable(
1417+ desc.clusterMap,
1418+ desc.stringLength as usize,
1419+ "DirectWrite returned a null cluster map",
1420+ )?
1421+ };
1422+
1423+ let cluster_analyzer = ClusterAnalyzer::new(cluster_map, glyph_count);
1424+ let mut utf16_idx = desc.textPosition as usize;
1425+ let mut glyph_idx = 0;
1426+ let mut glyphs = Vec::with_capacity(glyph_count);
1427+ for (cluster_utf16_len, cluster_glyph_count) in cluster_analyzer {
1428+ context.index_converter.advance_to_utf16_ix(utf16_idx);
1429+ utf16_idx += cluster_utf16_len;
1430+ for (cluster_glyph_idx, glyph_id) in glyph_ids
1431+ [glyph_idx..(glyph_idx + cluster_glyph_count)]
1432+ .iter()
1433+ .enumerate()
1434+ {
1435+ let id = GlyphId(*glyph_id as u32);
1436+ let is_emoji =
1437+ color_font && is_color_glyph(font_face, id, &context.components.factory);
1438+ let this_glyph_idx = glyph_idx + cluster_glyph_idx;
1439+ glyphs.push(ShapedGlyph {
1440+ id,
1441+ position: point(
1442+ px(context.width + glyph_offsets[this_glyph_idx].advanceOffset),
1443+ px(-glyph_offsets[this_glyph_idx].ascenderOffset),
1444+ ),
1445+ index: context.index_converter.utf8_ix,
1446+ is_emoji,
1447+ });
1448+ context.width += glyph_advances[this_glyph_idx];
1449+ }
1450+ glyph_idx += cluster_glyph_count;
1451+ }
1452+ context.runs.push(ShapedRun { font_id, glyphs });
1453+ }
1454+ Ok(())
1455+ }
1456+
1457+ fn DrawUnderline(
1458+ &self,
1459+ _clientdrawingcontext: *const ::core::ffi::c_void,
1460+ _baselineoriginx: f32,
1461+ _baselineoriginy: f32,
1462+ _underline: *const DWRITE_UNDERLINE,
1463+ _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1464+ ) -> windows::core::Result<()> {
1465+ Err(windows::core::Error::new(
1466+ E_NOTIMPL,
1467+ "DrawUnderline unimplemented",
1468+ ))
1469+ }
1470+
1471+ fn DrawStrikethrough(
1472+ &self,
1473+ _clientdrawingcontext: *const ::core::ffi::c_void,
1474+ _baselineoriginx: f32,
1475+ _baselineoriginy: f32,
1476+ _strikethrough: *const DWRITE_STRIKETHROUGH,
1477+ _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1478+ ) -> windows::core::Result<()> {
1479+ Err(windows::core::Error::new(
1480+ E_NOTIMPL,
1481+ "DrawStrikethrough unimplemented",
1482+ ))
1483+ }
1484+
1485+ fn DrawInlineObject(
1486+ &self,
1487+ _clientdrawingcontext: *const ::core::ffi::c_void,
1488+ _originx: f32,
1489+ _originy: f32,
1490+ _inlineobject: windows::core::Ref<IDWriteInlineObject>,
1491+ _issideways: BOOL,
1492+ _isrighttoleft: BOOL,
1493+ _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,
1494+ ) -> windows::core::Result<()> {
1495+ Err(windows::core::Error::new(
1496+ E_NOTIMPL,
1497+ "DrawInlineObject unimplemented",
1498+ ))
1499+ }
1500+}
1501+
1502+/// Interprets an optional DirectWrite array pointer as a slice, treating a
1503+/// null pointer with a zero length as an empty slice. A null pointer with a
1504+/// nonzero length fails with `null_error_message`.
1505+///
1506+/// # Safety
1507+///
1508+/// When `ptr` is non-null, the caller must guarantee that it points to a valid
1509+/// array of at least `len` elements that outlives the returned slice.
1510+unsafe fn slice_from_nullable<'a, T>(
1511+ ptr: *const T,
1512+ len: usize,
1513+ null_error_message: &str,
1514+) -> windows::core::Result<&'a [T]> {
1515+ if ptr.is_null() {
1516+ if len != 0 {
1517+ return Err(Error::new(E_INVALIDARG, null_error_message));
1518+ }
1519+ Ok(&[])
1520+ } else {
1521+ Ok(unsafe { std::slice::from_raw_parts(ptr, len) })
1522+ }
1523+}
1524+
1525+struct StringIndexConverter<'a> {
1526+ text: &'a str,
1527+ utf8_ix: usize,
1528+ utf16_ix: usize,
1529+}
1530+
1531+impl<'a> StringIndexConverter<'a> {
1532+ fn new(text: &'a str) -> Self {
1533+ Self {
1534+ text,
1535+ utf8_ix: 0,
1536+ utf16_ix: 0,
1537+ }
1538+ }
1539+
1540+ #[allow(dead_code)]
1541+ fn advance_to_utf8_ix(&mut self, utf8_target: usize) {
1542+ for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1543+ if self.utf8_ix + ix >= utf8_target {
1544+ self.utf8_ix += ix;
1545+ return;
1546+ }
1547+ self.utf16_ix += c.len_utf16();
1548+ }
1549+ self.utf8_ix = self.text.len();
1550+ }
1551+
1552+ fn advance_to_utf16_ix(&mut self, utf16_target: usize) {
1553+ for (ix, c) in self.text[self.utf8_ix..].char_indices() {
1554+ if self.utf16_ix >= utf16_target {
1555+ self.utf8_ix += ix;
1556+ return;
1557+ }
1558+ self.utf16_ix += c.len_utf16();
1559+ }
1560+ self.utf8_ix = self.text.len();
1561+ }
1562+}
1563+
1564+fn font_style_to_dwrite(style: FontStyle) -> DWRITE_FONT_STYLE {
1565+ match style {
1566+ FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,
1567+ FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,
1568+ FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,
1569+ }
1570+}
1571+
1572+fn font_style_from_dwrite(value: DWRITE_FONT_STYLE) -> FontStyle {
1573+ match value.0 {
1574+ 0 => FontStyle::Normal,
1575+ 1 => FontStyle::Italic,
1576+ 2 => FontStyle::Oblique,
1577+ _ => unreachable!(),
1578+ }
1579+}
1580+
1581+fn font_weight_to_dwrite(weight: FontWeight) -> DWRITE_FONT_WEIGHT {
1582+ DWRITE_FONT_WEIGHT(weight.0 as i32)
1583+}
1584+
1585+fn font_weight_from_dwrite(value: DWRITE_FONT_WEIGHT) -> FontWeight {
1586+ FontWeight(value.0 as f32)
1587+}
1588+
1589+fn get_font_names_from_collection(
1590+ collection: &IDWriteFontCollection1,
1591+ locale: &HSTRING,
1592+) -> Vec<String> {
1593+ unsafe {
1594+ let mut result = Vec::new();
1595+ let family_count = collection.GetFontFamilyCount();
1596+ for index in 0..family_count {
1597+ let Some(font_family) = collection.GetFontFamily(index).log_err() else {
1598+ continue;
1599+ };
1600+ let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {
1601+ continue;
1602+ };
1603+ let Some(family_name) = get_name(localized_family_name, locale).log_err() else {
1604+ continue;
1605+ };
1606+ result.push(family_name);
1607+ }
1608+
1609+ result
1610+ }
1611+}
1612+
1613+fn font_face_to_font(font_face: &IDWriteFontFace3, locale: &HSTRING) -> Option<Font> {
1614+ let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;
1615+ let family_name = get_name(localized_family_name, locale).log_err()?;
1616+ let weight = unsafe { font_face.GetWeight() };
1617+ let style = unsafe { font_face.GetStyle() };
1618+ Some(Font {
1619+ family: family_name.into(),
1620+ features: FontFeatures::default(),
1621+ weight: font_weight_from_dwrite(weight),
1622+ style: font_style_from_dwrite(style),
1623+ fallbacks: None,
1624+ })
1625+}
1626+
1627+// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag
1628+fn apply_font_features(
1629+ direct_write_features: &IDWriteTypography,
1630+ features: &FontFeatures,
1631+) -> Result<()> {
1632+ let tag_values = features.tag_value_list();
1633+
1634+ // All of these features are enabled by default by DirectWrite.
1635+ // If you want to (and can) peek into the source of DirectWrite
1636+ let mut feature_liga = make_direct_write_feature("liga", 1);
1637+ let mut feature_clig = make_direct_write_feature("clig", 1);
1638+ let mut feature_calt = make_direct_write_feature("calt", 1);
1639+
1640+ for (tag, value) in tag_values {
1641+ if tag.as_str() == "liga" && *value == 0 {
1642+ feature_liga.parameter = 0;
1643+ continue;
1644+ }
1645+ if tag.as_str() == "clig" && *value == 0 {
1646+ feature_clig.parameter = 0;
1647+ continue;
1648+ }
1649+ if tag.as_str() == "calt" && *value == 0 {
1650+ feature_calt.parameter = 0;
1651+ continue;
1652+ }
1653+
1654+ unsafe {
1655+ direct_write_features.AddFontFeature(make_direct_write_feature(tag, *value))?;
1656+ }
1657+ }
1658+ unsafe {
1659+ direct_write_features.AddFontFeature(feature_liga)?;
1660+ direct_write_features.AddFontFeature(feature_clig)?;
1661+ direct_write_features.AddFontFeature(feature_calt)?;
1662+ }
1663+
1664+ Ok(())
1665+}
1666+
1667+#[inline]
1668+const fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {
1669+ let tag = make_direct_write_tag(feature_name);
1670+ DWRITE_FONT_FEATURE {
1671+ nameTag: tag,
1672+ parameter,
1673+ }
1674+}
1675+
1676+#[inline]
1677+const fn make_open_type_tag(tag_name: &str) -> u32 {
1678+ let bytes = tag_name.as_bytes();
1679+ debug_assert!(bytes.len() == 4);
1680+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
1681+}
1682+
1683+#[inline]
1684+const fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {
1685+ DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))
1686+}
1687+
1688+#[inline]
1689+fn get_name(string: IDWriteLocalizedStrings, locale: &HSTRING) -> Result<String> {
1690+ let mut locale_name_index = 0u32;
1691+ let mut exists = BOOL(0);
1692+ unsafe { string.FindLocaleName(locale, &mut locale_name_index, &mut exists as _)? };
1693+ if !exists.as_bool() {
1694+ unsafe {
1695+ string.FindLocaleName(
1696+ DEFAULT_LOCALE_NAME,
1697+ &mut locale_name_index as _,
1698+ &mut exists as _,
1699+ )?
1700+ };
1701+ anyhow::ensure!(exists.as_bool(), "No localised string for {locale}");
1702+ }
1703+
1704+ let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;
1705+ let mut name_vec = vec![0u16; name_length + 1];
1706+ unsafe {
1707+ string.GetString(locale_name_index, &mut name_vec)?;
1708+ }
1709+
1710+ Ok(String::from_utf16_lossy(&name_vec[..name_length]))
1711+}
1712+
1713+fn get_system_subpixel_rendering() -> bool {
1714+ let mut value = c_uint::default();
1715+ let result = unsafe {
1716+ SystemParametersInfoW(
1717+ SPI_GETFONTSMOOTHINGTYPE,
1718+ 0,
1719+ Some((&mut value) as *mut c_uint as *mut c_void),
1720+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
1721+ )
1722+ };
1723+ if result.log_err().is_some() {
1724+ value == FE_FONTSMOOTHINGCLEARTYPE
1725+ } else {
1726+ true
1727+ }
1728+}
1729+
1730+fn get_system_ui_font_name() -> SharedString {
1731+ unsafe {
1732+ let mut info: LOGFONTW = std::mem::zeroed();
1733+ let font_family = if SystemParametersInfoW(
1734+ SPI_GETICONTITLELOGFONT,
1735+ std::mem::size_of::<LOGFONTW>() as u32,
1736+ Some(&mut info as *mut _ as _),
1737+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
1738+ )
1739+ .log_err()
1740+ .is_none()
1741+ {
1742+ // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts
1743+ // Segoe UI is the Windows font intended for user interface text strings.
1744+ "Segoe UI".into()
1745+ } else {
1746+ let font_name = String::from_utf16_lossy(&info.lfFaceName);
1747+ font_name.trim_matches(char::from(0)).to_owned().into()
1748+ };
1749+ log::info!("Use {} as UI font.", font_family);
1750+ font_family
1751+ }
1752+}
1753+
1754+// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats
1755+// but that doesn't seem to work for some glyphs, say ❤
1756+fn is_color_glyph(
1757+ font_face: &IDWriteFontFace3,
1758+ glyph_id: GlyphId,
1759+ factory: &IDWriteFactory5,
1760+) -> bool {
1761+ let glyph_run = DWRITE_GLYPH_RUN {
1762+ fontFace: ManuallyDrop::new(Some(unsafe { std::ptr::read(&****font_face) })),
1763+ fontEmSize: 14.0,
1764+ glyphCount: 1,
1765+ glyphIndices: &(glyph_id.0 as u16),
1766+ glyphAdvances: &0.0,
1767+ glyphOffsets: &DWRITE_GLYPH_OFFSET {
1768+ advanceOffset: 0.0,
1769+ ascenderOffset: 0.0,
1770+ },
1771+ isSideways: BOOL(0),
1772+ bidiLevel: 0,
1773+ };
1774+ unsafe {
1775+ factory.TranslateColorGlyphRun(
1776+ Vector2::default(),
1777+ &glyph_run as _,
1778+ None,
1779+ DWRITE_GLYPH_IMAGE_FORMATS_COLR
1780+ | DWRITE_GLYPH_IMAGE_FORMATS_SVG
1781+ | DWRITE_GLYPH_IMAGE_FORMATS_PNG
1782+ | DWRITE_GLYPH_IMAGE_FORMATS_JPEG
1783+ | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,
1784+ DWRITE_MEASURING_MODE_NATURAL,
1785+ None,
1786+ 0,
1787+ )
1788+ }
1789+ .is_ok()
1790+}
1791+
1792+const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");
1793+
1794+fn is_line_separator(character: char) -> bool {
1795+ matches!(character, '\u{2028}' | '\u{2029}')
1796+}
1797+
1798+#[cfg(test)]
1799+mod tests {
1800+ use super::DirectWriteTextSystem;
1801+ use crate::direct_write::ClusterAnalyzer;
1802+ use anyhow::Result;
1803+ use gpui::{Font, FontWeight, PlatformTextSystem, TextRun, TextSystem, WindowTextSystem, px};
1804+ use std::sync::Arc;
1805+ use windows::Win32::Graphics::DirectWrite::{DWRITE_FONT_STRETCH_NORMAL, DWRITE_TEXT_METRICS};
1806+
1807+ #[test]
1808+ fn tabs_preserve_native_advances_and_cursor() -> Result<()> {
1809+ let platform_text_system = Arc::new(DirectWriteTextSystem::new()?);
1810+ let text_system =
1811+ WindowTextSystem::new(Arc::new(TextSystem::new(platform_text_system.clone())));
1812+ for family in ["Consolas", "Segoe UI"] {
1813+ let font = Font {
1814+ family: family.into(),
1815+ ..Default::default()
1816+ };
1817+ let font_id = platform_text_system.font_id(&font)?;
1818+ for font_size in [px(12.0), px(16.0)] {
1819+ let format = {
1820+ let state = platform_text_system.state.read();
1821+ let font = &state.fonts[font_id.0];
1822+ unsafe {
1823+ platform_text_system.components.factory.CreateTextFormat(
1824+ &font.font_family_h,
1825+ &font.font_collection,
1826+ font.font_face.GetWeight(),
1827+ font.font_face.GetStyle(),
1828+ DWRITE_FONT_STRETCH_NORMAL,
1829+ font_size.as_f32(),
1830+ &platform_text_system.components.locale,
1831+ )?
1832+ }
1833+ };
1834+ let tab_interval = px(unsafe { format.GetIncrementalTabStop() });
1835+ for text in [
1836+ "ab",
1837+ "\t",
1838+ "\t\t",
1839+ "\t\tab",
1840+ "a\tb",
1841+ "abcd\te",
1842+ "ab\t",
1843+ "ab\t\t",
1844+ "a\tb\tc",
1845+ "é\t𐐀\tz",
1846+ "a \tb ",
1847+ "אב",
1848+ "aאבb",
1849+ "a\tאב\tb",
1850+ ] {
1851+ let mut native_metrics = DWRITE_TEXT_METRICS::default();
1852+ unsafe {
1853+ let layout = platform_text_system.components.factory.CreateTextLayout(
1854+ &text.encode_utf16().collect::<Vec<_>>(),
1855+ &format,
1856+ f32::INFINITY,
1857+ f32::INFINITY,
1858+ )?;
1859+ layout.GetMetrics(&mut native_metrics)?;
1860+ }
1861+ for split_runs in [false, true] {
1862+ let runs = if split_runs {
1863+ text.chars()
1864+ .map(|character| TextRun {
1865+ len: character.len_utf8(),
1866+ font: font.clone(),
1867+ ..Default::default()
1868+ })
1869+ .collect::<Vec<_>>()
1870+ } else {
1871+ vec![TextRun {
1872+ len: text.len(),
1873+ font: font.clone(),
1874+ ..Default::default()
1875+ }]
1876+ };
1877+ let shaped = text_system.shape_line(text.into(), font_size, &runs, None);
1878+ let mut cursor = shaped.cursor();
1879+ let mut expected_x = px(0.0);
1880+ for (index, character) in text.char_indices() {
1881+ let end = index + character.len_utf8();
1882+ let expected_end = if character == '\t' {
1883+ tab_interval * ((expected_x / tab_interval).floor() + 1.0)
1884+ } else {
1885+ let character_run = TextRun {
1886+ len: character.len_utf8(),
1887+ font: font.clone(),
1888+ ..Default::default()
1889+ };
1890+ expected_x
1891+ + text_system
1892+ .shape_line(
1893+ character.to_string().into(),
1894+ font_size,
1895+ &[character_run],
1896+ None,
1897+ )
1898+ .width
1899+ };
1900+ assert!(
1901+ (shaped.x_for_index(index) - expected_x).abs() < px(0.001),
1902+ "{family}, {font_size:?}, {text:?}, {split_runs}, index={index}: \
1903+ expected {expected_x:?}, got {:?}",
1904+ shaped.x_for_index(index)
1905+ );
1906+ assert_eq!(
1907+ shaped.index_for_x(expected_x + px(0.01)),
1908+ Some(index),
1909+ "{family}, {text:?}, index={index}"
1910+ );
1911+ let piece = cursor.take_until(end);
1912+ assert_eq!(piece.text.as_ref(), character.to_string());
1913+ assert!(
1914+ (piece.width - (expected_end - expected_x)).abs() < px(0.001),
1915+ "{family}, {text:?}, index={index}"
1916+ );
1917+ expected_x = expected_end;
1918+ }
1919+ assert!((shaped.width - expected_x).abs() < px(0.001));
1920+ assert!(
1921+ (shaped.width - px(native_metrics.widthIncludingTrailingWhitespace))
1922+ .abs()
1923+ < px(0.001)
1924+ );
1925+ assert_eq!(shaped.x_for_index(text.len()), shaped.width);
1926+ }
1927+ }
1928+ }
1929+ }
1930+ Ok(())
1931+ }
1932+
1933+ #[test]
1934+ fn unicode_line_separators_preserve_shaped_line_cursor() -> Result<()> {
1935+ check_unicode_separator_cursor('\u{2028}')
1936+ }
1937+
1938+ #[test]
1939+ fn unicode_paragraph_separators_preserve_shaped_line_cursor() -> Result<()> {
1940+ check_unicode_separator_cursor('\u{2029}')
1941+ }
1942+
1943+ fn check_unicode_separator_cursor(separator: char) -> Result<()> {
1944+ let platform_text_system = Arc::new(DirectWriteTextSystem::new()?);
1945+ let font = Font {
1946+ family: "Segoe UI".into(),
1947+ ..Default::default()
1948+ };
1949+ platform_text_system.font_id(&font)?;
1950+ let text_system = WindowTextSystem::new(Arc::new(TextSystem::new(platform_text_system)));
1951+
1952+ let separated_letters = ["a", "b", "c", "d", "e", "f"].join(&separator.to_string());
1953+ for text in [
1954+ separated_letters,
1955+ format!("{separator}ab{separator}{separator}cd{separator}"),
1956+ format!("{separator}{separator}{separator}{separator}{separator}"),
1957+ format!("é{separator}𐐀{separator}z"),
1958+ ] {
1959+ for multiple_fonts in [false, true] {
1960+ let mut runs = vec![TextRun {
1961+ len: text.len(),
1962+ font: font.clone(),
1963+ ..Default::default()
1964+ }];
1965+ if multiple_fonts {
1966+ let first_len = text.chars().next().map_or(0, char::len_utf8);
1967+ runs[0].len = first_len;
1968+ let mut bold_font = font.clone();
1969+ bold_font.weight = FontWeight::BOLD;
1970+ runs.push(TextRun {
1971+ len: text.len() - first_len,
1972+ font: bold_font,
1973+ ..Default::default()
1974+ });
1975+ }
1976+ let shaped = text_system.shape_line(text.clone().into(), px(14.0), &runs, None);
1977+ let mut reference_runs = runs.clone();
1978+ let mut offset = 0;
1979+ for run in &mut reference_runs {
1980+ let end = offset + run.len;
1981+ run.len = text[offset..end]
1982+ .chars()
1983+ .filter(|character| *character != separator)
1984+ .map(char::len_utf8)
1985+ .sum();
1986+ offset = end;
1987+ }
1988+ let reference_text: String = text
1989+ .chars()
1990+ .filter(|character| *character != separator)
1991+ .collect();
1992+ let reference =
1993+ text_system.shape_line(reference_text.into(), px(14.0), &reference_runs, None);
1994+ assert!(
1995+ (shaped.width - reference.width).abs() < px(0.001),
1996+ "{text:?}, multiple_fonts={multiple_fonts}"
1997+ );
1998+
1999+ let visible_glyphs: Vec<_> = shaped
2000+ .runs
vendor/gpui-pre-windows/src/directx_atlas.rsadded+420 -0
@@ -0,0 +1,420 @@
1+use etagere::BucketedAtlasAllocator;
2+use parking_lot::Mutex;
3+use windows::Win32::Graphics::{
4+ Direct3D11::{
5+ D3D11_BIND_SHADER_RESOURCE, D3D11_BOX, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT,
6+ ID3D11Device, ID3D11DeviceContext, ID3D11ShaderResourceView, ID3D11Texture2D,
7+ },
8+ Dxgi::Common::*,
9+};
10+
11+use gpui::{
12+ AtlasBackend, AtlasKey, AtlasState, AtlasTextureId, AtlasTextureKind, AtlasTextureList,
13+ AtlasTile, Bounds, DevicePixels, PlatformAtlas, Point, Size,
14+};
15+
16+pub(crate) struct DirectXAtlas(Mutex<AtlasState<DirectXAtlasTextures>>);
17+
18+struct DirectXAtlasTextures {
19+ device: ID3D11Device,
20+ device_context: ID3D11DeviceContext,
21+ monochrome_textures: AtlasTextureList<DirectXAtlasTexture>,
22+ polychrome_textures: AtlasTextureList<DirectXAtlasTexture>,
23+ subpixel_textures: AtlasTextureList<DirectXAtlasTexture>,
24+}
25+
26+struct DirectXAtlasTexture {
27+ id: AtlasTextureId,
28+ bytes_per_pixel: u32,
29+ allocator: BucketedAtlasAllocator,
30+ texture: ID3D11Texture2D,
31+ view: [Option<ID3D11ShaderResourceView>; 1],
32+ live_atlas_keys: u32,
33+}
34+
35+impl DirectXAtlas {
36+ pub(crate) fn new(device: &ID3D11Device, device_context: &ID3D11DeviceContext) -> Self {
37+ DirectXAtlas(Mutex::new(AtlasState::new(DirectXAtlasTextures {
38+ device: device.clone(),
39+ device_context: device_context.clone(),
40+ monochrome_textures: Default::default(),
41+ polychrome_textures: Default::default(),
42+ subpixel_textures: Default::default(),
43+ })))
44+ }
45+
46+ /// Returns the view backing `id`, or `None` once every tile in it has been
47+ /// removed. A scene can still reference such a texture when a cached view
48+ /// replays a paint from before the image was dropped, so callers must skip
49+ /// those sprites rather than assume the texture exists.
50+ pub(crate) fn get_texture_view(
51+ &self,
52+ id: AtlasTextureId,
53+ ) -> Option<[Option<ID3D11ShaderResourceView>; 1]> {
54+ let lock = self.0.lock();
55+ let texture = lock.backend.texture(id)?;
56+ Some(texture.view.clone())
57+ }
58+
59+ pub(crate) fn handle_device_lost(
60+ &self,
61+ device: &ID3D11Device,
62+ device_context: &ID3D11DeviceContext,
63+ ) {
64+ let mut lock = self.0.lock();
65+ lock.clear(|textures| {
66+ textures.device = device.clone();
67+ textures.device_context = device_context.clone();
68+ textures.monochrome_textures = AtlasTextureList::default();
69+ textures.polychrome_textures = AtlasTextureList::default();
70+ textures.subpixel_textures = AtlasTextureList::default();
71+ });
72+ }
73+}
74+
75+impl PlatformAtlas for DirectXAtlas {
76+ fn get_or_insert_with<'a>(
77+ &self,
78+ key: AtlasKey,
79+ build: &mut dyn FnMut() -> anyhow::Result<
80+ Option<(Size<DevicePixels>, std::borrow::Cow<'a, [u8]>)>,
81+ >,
82+ ) -> anyhow::Result<Option<AtlasTile>> {
83+ self.0.lock().get_or_insert_with(key, build)
84+ }
85+
86+ fn remove(&self, key: &AtlasKey) {
87+ self.0.lock().remove(key);
88+ }
89+}
90+
91+impl AtlasBackend for DirectXAtlasTextures {
92+ fn insert(
93+ &mut self,
94+ kind: AtlasTextureKind,
95+ size: Size<DevicePixels>,
96+ bytes: &[u8],
97+ ) -> anyhow::Result<AtlasTile> {
98+ let tile = self
99+ .allocate(size, kind)
100+ .ok_or_else(|| anyhow::anyhow!("failed to allocate"))?;
101+ let texture = self
102+ .texture(tile.texture_id)
103+ .ok_or_else(|| anyhow::anyhow!("allocated tile refers to a missing texture"))?;
104+ texture.upload(&self.device_context, tile.bounds, bytes);
105+ Ok(tile)
106+ }
107+
108+ fn remove(&mut self, tile: AtlasTile) {
109+ let id = tile.texture_id;
110+
111+ let textures = match id.kind {
112+ AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
113+ AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
114+ AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
115+ };
116+
117+ let Some(texture_slot) = textures.textures.get_mut(id.index as usize) else {
118+ return;
119+ };
120+
121+ if let Some(mut texture) = texture_slot.take() {
122+ texture.allocator.deallocate(tile.tile_id.into());
123+ texture.decrement_ref_count();
124+ if texture.is_unreferenced() {
125+ textures.free_list.push(texture.id.index as usize);
126+ } else {
127+ *texture_slot = Some(texture);
128+ }
129+ }
130+ }
131+}
132+
133+impl DirectXAtlasTextures {
134+ fn allocate(
135+ &mut self,
136+ size: Size<DevicePixels>,
137+ texture_kind: AtlasTextureKind,
138+ ) -> Option<AtlasTile> {
139+ {
140+ let textures = match texture_kind {
141+ AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
142+ AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
143+ AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
144+ };
145+
146+ if let Some(tile) = textures
147+ .iter_mut()
148+ .rev()
149+ .find_map(|texture| texture.allocate(size))
150+ {
151+ return Some(tile);
152+ }
153+ }
154+
155+ let texture = self.push_texture(size, texture_kind)?;
156+ texture.allocate(size)
157+ }
158+
159+ fn push_texture(
160+ &mut self,
161+ min_size: Size<DevicePixels>,
162+ kind: AtlasTextureKind,
163+ ) -> Option<&mut DirectXAtlasTexture> {
164+ const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
165+ width: DevicePixels(1024),
166+ height: DevicePixels(1024),
167+ };
168+ // Max texture size for DirectX. See:
169+ // https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-limits
170+ const MAX_ATLAS_SIZE: Size<DevicePixels> = Size {
171+ width: DevicePixels(16384),
172+ height: DevicePixels(16384),
173+ };
174+ let size = min_size.min(&MAX_ATLAS_SIZE).max(&DEFAULT_ATLAS_SIZE);
175+ let pixel_format;
176+ let bind_flag;
177+ let bytes_per_pixel;
178+ match kind {
179+ AtlasTextureKind::Monochrome => {
180+ pixel_format = DXGI_FORMAT_R8_UNORM;
181+ bind_flag = D3D11_BIND_SHADER_RESOURCE;
182+ bytes_per_pixel = 1;
183+ }
184+ AtlasTextureKind::Polychrome => {
185+ pixel_format = DXGI_FORMAT_B8G8R8A8_UNORM;
186+ bind_flag = D3D11_BIND_SHADER_RESOURCE;
187+ bytes_per_pixel = 4;
188+ }
189+ AtlasTextureKind::Subpixel => {
190+ pixel_format = DXGI_FORMAT_R8G8B8A8_UNORM;
191+ bind_flag = D3D11_BIND_SHADER_RESOURCE;
192+ bytes_per_pixel = 4;
193+ }
194+ }
195+ let texture_desc = D3D11_TEXTURE2D_DESC {
196+ Width: size.width.0 as u32,
197+ Height: size.height.0 as u32,
198+ MipLevels: 1,
199+ ArraySize: 1,
200+ Format: pixel_format,
201+ SampleDesc: DXGI_SAMPLE_DESC {
202+ Count: 1,
203+ Quality: 0,
204+ },
205+ Usage: D3D11_USAGE_DEFAULT,
206+ BindFlags: bind_flag.0 as u32,
207+ CPUAccessFlags: 0,
208+ MiscFlags: 0,
209+ };
210+ let mut texture: Option<ID3D11Texture2D> = None;
211+ unsafe {
212+ // This only returns None if the device is lost, which we will recreate later.
213+ // So it's ok to return None here.
214+ self.device
215+ .CreateTexture2D(&texture_desc, None, Some(&mut texture))
216+ .ok()?;
217+ }
218+ let texture = texture.unwrap();
219+
220+ let texture_list = match kind {
221+ AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
222+ AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
223+ AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
224+ };
225+ let index = texture_list.free_list.pop();
226+ let view = unsafe {
227+ let mut view = None;
228+ self.device
229+ .CreateShaderResourceView(&texture, None, Some(&mut view))
230+ .ok()?;
231+ [view]
232+ };
233+ let atlas_texture = DirectXAtlasTexture {
234+ id: AtlasTextureId {
235+ index: index.unwrap_or(texture_list.textures.len()) as u32,
236+ kind,
237+ },
238+ bytes_per_pixel,
239+ allocator: etagere::BucketedAtlasAllocator::new(device_size_to_etagere(size)),
240+ texture,
241+ view,
242+ live_atlas_keys: 0,
243+ };
244+ if let Some(ix) = index {
245+ texture_list.textures[ix] = Some(atlas_texture);
246+ texture_list.textures.get_mut(ix).unwrap().as_mut()
247+ } else {
248+ texture_list.textures.push(Some(atlas_texture));
249+ texture_list.textures.last_mut().unwrap().as_mut()
250+ }
251+ }
252+
253+ fn texture(&self, id: AtlasTextureId) -> Option<&DirectXAtlasTexture> {
254+ let textures = match id.kind {
255+ AtlasTextureKind::Monochrome => &self.monochrome_textures,
256+ AtlasTextureKind::Polychrome => &self.polychrome_textures,
257+ AtlasTextureKind::Subpixel => &self.subpixel_textures,
258+ };
259+ textures.textures.get(id.index as usize)?.as_ref()
260+ }
261+}
262+
263+impl DirectXAtlasTexture {
264+ fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
265+ let allocation = self.allocator.allocate(device_size_to_etagere(size))?;
266+ let tile = AtlasTile {
267+ texture_id: self.id,
268+ tile_id: allocation.id.into(),
269+ bounds: Bounds {
270+ origin: etagere_point_to_device(allocation.rectangle.min),
271+ size,
272+ },
273+ padding: 0,
274+ };
275+ self.live_atlas_keys += 1;
276+ Some(tile)
277+ }
278+
279+ fn upload(
280+ &self,
281+ device_context: &ID3D11DeviceContext,
282+ bounds: Bounds<DevicePixels>,
283+ bytes: &[u8],
284+ ) {
285+ // `UpdateSubresource` reads `row_pitch * height` bytes from `bytes` based on the
286+ // `D3D11_BOX` below. If the caller hands us a slice shorter than that, the driver would
287+ // over-read past the end of the source buffer (potentially by multiple megabytes), so bail
288+ // out instead. This is a first-insert path rather than a per-frame one, so the check is
289+ // effectively free.
290+ let row_bytes = bounds.size.width.to_bytes(self.bytes_per_pixel as u8) as usize;
291+ let expected = row_bytes * bounds.size.height.0.max(0) as usize;
292+ if bytes.len() < expected {
293+ log::error!(
294+ "DirectXAtlasTexture::upload: source slice is {} bytes but the {}x{} region \
295+ requires {} bytes; skipping upload to avoid a driver over-read",
296+ bytes.len(),
297+ bounds.size.width.0,
298+ bounds.size.height.0,
299+ expected,
300+ );
301+ return;
302+ }
303+ unsafe {
304+ device_context.UpdateSubresource(
305+ &self.texture,
306+ 0,
307+ Some(&D3D11_BOX {
308+ left: bounds.left().0 as u32,
309+ top: bounds.top().0 as u32,
310+ front: 0,
311+ right: bounds.right().0 as u32,
312+ bottom: bounds.bottom().0 as u32,
313+ back: 1,
314+ }),
315+ bytes.as_ptr() as _,
316+ bounds.size.width.to_bytes(self.bytes_per_pixel as u8),
317+ 0,
318+ );
319+ }
320+ }
321+
322+ fn decrement_ref_count(&mut self) {
323+ self.live_atlas_keys -= 1;
324+ }
325+
326+ fn is_unreferenced(&mut self) -> bool {
327+ self.live_atlas_keys == 0
328+ }
329+}
330+
331+fn device_size_to_etagere(size: Size<DevicePixels>) -> etagere::Size {
332+ etagere::Size::new(size.width.into(), size.height.into())
333+}
334+
335+fn etagere_point_to_device(value: etagere::Point) -> Point<DevicePixels> {
336+ Point {
337+ x: DevicePixels::from(value.x),
338+ y: DevicePixels::from(value.y),
339+ }
340+}
341+
342+#[cfg(test)]
343+mod tests {
344+ use super::*;
345+ use gpui::{ImageId, RenderImageParams};
346+ use std::borrow::Cow;
347+ use windows::Win32::{
348+ Foundation::HMODULE,
349+ Graphics::{
350+ Direct3D::D3D_DRIVER_TYPE_WARP,
351+ Direct3D11::{D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_SDK_VERSION, D3D11CreateDevice},
352+ },
353+ };
354+
355+ fn create_atlas() -> Option<DirectXAtlas> {
356+ let mut device: Option<ID3D11Device> = None;
357+ let mut device_context: Option<ID3D11DeviceContext> = None;
358+ unsafe {
359+ D3D11CreateDevice(
360+ None,
361+ D3D_DRIVER_TYPE_WARP,
362+ HMODULE::default(),
363+ D3D11_CREATE_DEVICE_BGRA_SUPPORT,
364+ None,
365+ D3D11_SDK_VERSION,
366+ Some(&mut device),
367+ None,
368+ Some(&mut device_context),
369+ )
370+ }
371+ .ok()?;
372+ Some(DirectXAtlas::new(&device?, &device_context?))
373+ }
374+
375+ fn make_image_key(image_id: usize) -> AtlasKey {
376+ AtlasKey::Image(RenderImageParams {
377+ image_id: ImageId(image_id),
378+ frame_index: 0,
379+ })
380+ }
381+
382+ fn insert_tile(atlas: &DirectXAtlas, key: AtlasKey, size: Size<DevicePixels>) -> AtlasTile {
383+ atlas
384+ .get_or_insert_with(key, &mut || {
385+ let byte_count = (size.width.0 as usize) * (size.height.0 as usize) * 4;
386+ Ok(Some((size, Cow::Owned(vec![0u8; byte_count]))))
387+ })
388+ .expect("allocation should succeed")
389+ .expect("callback returns Some")
390+ }
391+
392+ #[test]
393+ fn test_remove_deallocates_tile_space_for_reuse() {
394+ let Some(atlas) = create_atlas() else {
395+ return;
396+ };
397+
398+ let small = Size {
399+ width: DevicePixels(64),
400+ height: DevicePixels(64),
401+ };
402+ let big = Size {
403+ width: DevicePixels(700),
404+ height: DevicePixels(700),
405+ };
406+
407+ let keeper_key = make_image_key(1);
408+ let big_key_a = make_image_key(2);
409+ let big_key_b = make_image_key(3);
410+
411+ let keeper_tile = insert_tile(&atlas, keeper_key, small);
412+ let tile_a = insert_tile(&atlas, big_key_a.clone(), big);
413+ assert_eq!(keeper_tile.texture_id, tile_a.texture_id);
414+
415+ atlas.remove(&big_key_a);
416+
417+ let tile_b = insert_tile(&atlas, big_key_b, big);
418+ assert_eq!(tile_b.texture_id, keeper_tile.texture_id);
419+ }
420+}
vendor/gpui-pre-windows/src/directx_devices.rsadded+194 -0
@@ -0,0 +1,194 @@
1+use anyhow::{Context, Result};
2+use gpui_util::ResultExt;
3+use itertools::Itertools;
4+use windows::Win32::{
5+ Foundation::HMODULE,
6+ Graphics::{
7+ Direct3D::{
8+ D3D_DRIVER_TYPE_UNKNOWN, D3D_FEATURE_LEVEL, D3D_FEATURE_LEVEL_10_1,
9+ D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1,
10+ },
11+ Direct3D11::{
12+ D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_DEBUG,
13+ D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS,
14+ D3D11_SDK_VERSION, D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext,
15+ },
16+ Dxgi::{
17+ CreateDXGIFactory2, DXGI_CREATE_FACTORY_DEBUG, DXGI_CREATE_FACTORY_FLAGS,
18+ IDXGIAdapter1, IDXGIFactory6,
19+ },
20+ },
21+};
22+use windows::core::Interface;
23+
24+pub(crate) fn try_to_recover_from_device_lost<T>(mut f: impl FnMut() -> Result<T>) -> Result<T> {
25+ (0..5)
26+ .map(|i| {
27+ if i > 0 {
28+ // Add a small delay before retrying
29+ std::thread::sleep(std::time::Duration::from_millis(100 + i * 10));
30+ }
31+ f()
32+ })
33+ .find_or_last(Result::is_ok)
34+ .unwrap()
35+ .context("DirectXRenderer failed to recover from lost device after multiple attempts")
36+}
37+
38+#[derive(Clone)]
39+pub(crate) struct DirectXDevices {
40+ pub(crate) adapter: IDXGIAdapter1,
41+ pub(crate) dxgi_factory: IDXGIFactory6,
42+ pub(crate) device: ID3D11Device,
43+ pub(crate) device_context: ID3D11DeviceContext,
44+}
45+
46+impl DirectXDevices {
47+ pub(crate) fn new() -> Result<Self> {
48+ let debug_layer_available = check_debug_layer_available();
49+ let dxgi_factory =
50+ get_dxgi_factory(debug_layer_available).context("Creating DXGI factory")?;
51+ let (adapter, device, device_context, feature_level) =
52+ get_adapter(&dxgi_factory, debug_layer_available).context("Getting DXGI adapter")?;
53+ match feature_level {
54+ D3D_FEATURE_LEVEL_11_1 => {
55+ log::info!("Created device with Direct3D 11.1 feature level.")
56+ }
57+ D3D_FEATURE_LEVEL_11_0 => {
58+ log::info!("Created device with Direct3D 11.0 feature level.")
59+ }
60+ D3D_FEATURE_LEVEL_10_1 => {
61+ log::info!("Created device with Direct3D 10.1 feature level.")
62+ }
63+ _ => unreachable!(),
64+ }
65+
66+ Ok(Self {
67+ adapter,
68+ dxgi_factory,
69+ device,
70+ device_context,
71+ })
72+ }
73+}
74+
75+#[inline]
76+fn check_debug_layer_available() -> bool {
77+ #[cfg(debug_assertions)]
78+ {
79+ use windows::Win32::Graphics::Dxgi::{DXGIGetDebugInterface1, IDXGIInfoQueue};
80+
81+ unsafe { DXGIGetDebugInterface1::<IDXGIInfoQueue>(0) }
82+ .log_err()
83+ .is_some()
84+ }
85+ #[cfg(not(debug_assertions))]
86+ {
87+ false
88+ }
89+}
90+
91+#[inline]
92+fn get_dxgi_factory(debug_layer_available: bool) -> Result<IDXGIFactory6> {
93+ let factory_flag = if debug_layer_available {
94+ DXGI_CREATE_FACTORY_DEBUG
95+ } else {
96+ #[cfg(debug_assertions)]
97+ log::warn!(
98+ "Failed to get DXGI debug interface. DirectX debugging features will be disabled."
99+ );
100+ DXGI_CREATE_FACTORY_FLAGS::default()
101+ };
102+ unsafe { Ok(CreateDXGIFactory2(factory_flag)?) }
103+}
104+
105+#[inline]
106+fn get_adapter(
107+ dxgi_factory: &IDXGIFactory6,
108+ debug_layer_available: bool,
109+) -> Result<(
110+ IDXGIAdapter1,
111+ ID3D11Device,
112+ ID3D11DeviceContext,
113+ D3D_FEATURE_LEVEL,
114+)> {
115+ for adapter_index in 0.. {
116+ let adapter: IDXGIAdapter1 = unsafe { dxgi_factory.EnumAdapters(adapter_index)?.cast()? };
117+ if let Ok(desc) = unsafe { adapter.GetDesc1() } {
118+ let gpu_name = String::from_utf16_lossy(&desc.Description)
119+ .trim_matches(char::from(0))
120+ .to_string();
121+ log::info!("Using GPU: {}", gpu_name);
122+ }
123+ // Check to see whether the adapter supports Direct3D 11 and create
124+ // the device if it does.
125+ let mut context: Option<ID3D11DeviceContext> = None;
126+ let mut feature_level = D3D_FEATURE_LEVEL::default();
127+ if let Some(device) = get_device(
128+ &adapter,
129+ Some(&mut context),
130+ Some(&mut feature_level),
131+ debug_layer_available,
132+ )
133+ .log_err()
134+ {
135+ return Ok((adapter, device, context.unwrap(), feature_level));
136+ }
137+ }
138+
139+ unreachable!()
140+}
141+
142+#[inline]
143+fn get_device(
144+ adapter: &IDXGIAdapter1,
145+ context: Option<*mut Option<ID3D11DeviceContext>>,
146+ feature_level: Option<*mut D3D_FEATURE_LEVEL>,
147+ debug_layer_available: bool,
148+) -> Result<ID3D11Device> {
149+ let mut device: Option<ID3D11Device> = None;
150+ let device_flags = if debug_layer_available {
151+ D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG
152+ } else {
153+ D3D11_CREATE_DEVICE_BGRA_SUPPORT
154+ };
155+ unsafe {
156+ D3D11CreateDevice(
157+ adapter,
158+ D3D_DRIVER_TYPE_UNKNOWN,
159+ HMODULE::default(),
160+ device_flags,
161+ // 4x MSAA is required for Direct3D Feature Level 10.1 or better
162+ Some(&[
163+ D3D_FEATURE_LEVEL_11_1,
164+ D3D_FEATURE_LEVEL_11_0,
165+ D3D_FEATURE_LEVEL_10_1,
166+ ]),
167+ D3D11_SDK_VERSION,
168+ Some(&mut device),
169+ feature_level,
170+ context,
171+ )?;
172+ }
173+ let device = device.unwrap();
174+ let mut data = D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS::default();
175+ unsafe {
176+ device
177+ .CheckFeatureSupport(
178+ D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS,
179+ &mut data as *mut _ as _,
180+ std::mem::size_of::<D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS>() as u32,
181+ )
182+ .context("Checking GPU device feature support")?;
183+ }
184+ if data
185+ .ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x
186+ .as_bool()
187+ {
188+ Ok(device)
189+ } else {
190+ Err(anyhow::anyhow!(
191+ "Required feature StructuredBuffer is not supported by GPU/driver"
192+ ))
193+ }
194+}
vendor/gpui-pre-windows/src/directx_renderer.rsadded+2083 -0

Diff too large; view file

@@ -0,0 +1,2083 @@
1+use std::{
2+ ops::Range,
3+ slice,
4+ sync::{Arc, OnceLock},
5+};
6+
7+use anyhow::{Context, Result};
8+use gpui_util::ResultExt;
9+use windows::{
10+ Win32::{
11+ Foundation::HWND,
12+ Graphics::{
13+ Direct3D::*,
14+ Direct3D11::*,
15+ DirectComposition::*,
16+ DirectWrite::*,
17+ Dxgi::{Common::*, *},
18+ },
19+ },
20+ core::{HSTRING, Interface},
21+};
22+
23+use crate::directx_renderer::shader_resources::{RawShaderBytes, ShaderModule, ShaderTarget};
24+use crate::*;
25+use gpui::*;
26+
27+pub(crate) const DISABLE_DIRECT_COMPOSITION: &str = "GPUI_DISABLE_DIRECT_COMPOSITION";
28+const RENDER_TARGET_FORMAT: DXGI_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM;
29+const MAX_INSTANCE_BUFFER_SIZE: usize = 256 * 1024 * 1024;
30+
31+pub(crate) struct FontInfo {
32+ pub gamma_ratios: [f32; 4],
33+ pub grayscale_enhanced_contrast: f32,
34+ pub subpixel_enhanced_contrast: f32,
35+ pub is_bgr: bool,
36+}
37+
38+pub(crate) struct DirectXRenderer {
39+ hwnd: HWND,
40+ atlas: Arc<DirectXAtlas>,
41+ devices: Option<DirectXRendererDevices>,
42+ resources: Option<DirectXResources>,
43+ globals: DirectXGlobalElements,
44+ pipelines: DirectXRenderPipelines,
45+ direct_composition: Option<DirectComposition>,
46+ font_info: &'static FontInfo,
47+
48+ width: u32,
49+ height: u32,
50+
51+ /// Whether we want to skip drwaing due to device lost events.
52+ ///
53+ /// In that case we want to discard the first frame that we draw as we got reset in the middle of a frame
54+ /// meaning we lost all the allocated gpu textures and scene resources.
55+ skip_draws: bool,
56+}
57+
58+/// Direct3D objects
59+#[derive(Clone)]
60+pub(crate) struct DirectXRendererDevices {
61+ pub(crate) adapter: IDXGIAdapter1,
62+ pub(crate) dxgi_factory: IDXGIFactory6,
63+ pub(crate) device: ID3D11Device,
64+ pub(crate) device_context: ID3D11DeviceContext,
65+ device_context1: Option<ID3D11DeviceContext1>,
66+ dxgi_device: Option<IDXGIDevice>,
67+ annotation: Option<ID3DUserDefinedAnnotation>,
68+}
69+
70+struct DirectXResources {
71+ // Direct3D rendering objects
72+ swap_chain: IDXGISwapChain1,
73+ render_target: Option<ID3D11Texture2D>,
74+ render_target_view: Option<ID3D11RenderTargetView>,
75+ depth_stencil_texture: ID3D11Texture2D,
76+ depth_stencil_view: Option<ID3D11DepthStencilView>,
77+
78+ // Cached viewport
79+ viewport: D3D11_VIEWPORT,
80+}
81+
82+struct DirectXRenderPipelines {
83+ shadow_pipeline: PipelineState<Shadow>,
84+ quad_pipeline: PipelineState<Quad>,
85+ opaque_quad_pipeline: OpaqueQuadPipeline,
86+ path_tile_pipeline: PipelineState<PathTile>,
87+ path_curves: StructuredBuffer<PathCurve>,
88+ path_paints: StructuredBuffer<PathPaint>,
89+ underline_pipeline: PipelineState<Underline>,
90+ mono_sprites: PipelineState<MonochromeSprite>,
91+ subpixel_sprites: PipelineState<SubpixelSprite>,
92+ poly_sprites: PipelineState<PolychromeSprite>,
93+}
94+
95+struct DirectXGlobalElements {
96+ global_params_buffer: Option<ID3D11Buffer>,
97+ batch_params_buffer: Option<ID3D11Buffer>,
98+ sampler: Option<ID3D11SamplerState>,
99+}
100+
101+struct Annotation<'a>(&'a ID3DUserDefinedAnnotation);
102+
103+impl<'a> Annotation<'a> {
104+ fn new(annotation: &'a ID3DUserDefinedAnnotation, label: HSTRING) -> Self {
105+ unsafe { annotation.BeginEvent(&label) };
106+ Self(annotation)
107+ }
108+}
109+
110+impl Drop for Annotation<'_> {
111+ fn drop(&mut self) {
112+ unsafe { self.0.EndEvent() };
113+ }
114+}
115+
116+struct DirectComposition {
117+ comp_device: IDCompositionDevice,
118+ comp_target: IDCompositionTarget,
119+ comp_visual: IDCompositionVisual,
120+}
121+
122+impl DirectXRendererDevices {
123+ pub(crate) fn new(
124+ directx_devices: &DirectXDevices,
125+ disable_direct_composition: bool,
126+ ) -> Result<Self> {
127+ let DirectXDevices {
128+ adapter,
129+ dxgi_factory,
130+ device,
131+ device_context,
132+ } = directx_devices;
133+ let dxgi_device = if disable_direct_composition {
134+ None
135+ } else {
136+ Some(device.cast().context("Creating DXGI device")?)
137+ };
138+ let annotation = device_context.cast().ok();
139+ let device_context1 = device_context.cast().ok();
140+
141+ Ok(Self {
142+ adapter: adapter.clone(),
143+ dxgi_factory: dxgi_factory.clone(),
144+ device: device.clone(),
145+ device_context: device_context.clone(),
146+ device_context1,
147+ dxgi_device,
148+ annotation,
149+ })
150+ }
151+}
152+
153+impl DirectXRenderer {
154+ pub(crate) fn new(
155+ hwnd: HWND,
156+ directx_devices: &DirectXDevices,
157+ disable_direct_composition: bool,
158+ ) -> Result<Self> {
159+ if disable_direct_composition {
160+ log::info!("Direct Composition is disabled.");
161+ }
162+
163+ let devices = DirectXRendererDevices::new(directx_devices, disable_direct_composition)
164+ .context("Creating DirectX devices")?;
165+ let atlas = Arc::new(DirectXAtlas::new(&devices.device, &devices.device_context));
166+
167+ let resources = DirectXResources::new(&devices, 1, 1, hwnd, disable_direct_composition)
168+ .context("Creating DirectX resources")?;
169+ let globals = DirectXGlobalElements::new(&devices.device)
170+ .context("Creating DirectX global elements")?;
171+ let pipelines = DirectXRenderPipelines::new(&devices.device)
172+ .context("Creating DirectX render pipelines")?;
173+
174+ let direct_composition = if disable_direct_composition {
175+ None
176+ } else {
177+ let composition = DirectComposition::new(devices.dxgi_device.as_ref().unwrap(), hwnd)
178+ .context("Creating DirectComposition")?;
179+ composition
180+ .set_swap_chain(&resources.swap_chain)
181+ .context("Setting swap chain for DirectComposition")?;
182+ Some(composition)
183+ };
184+
185+ Ok(DirectXRenderer {
186+ hwnd,
187+ atlas,
188+ devices: Some(devices),
189+ resources: Some(resources),
190+ globals,
191+ pipelines,
192+ direct_composition,
193+ font_info: Self::get_font_info(),
194+ width: 1,
195+ height: 1,
196+ skip_draws: false,
197+ })
198+ }
199+
200+ pub(crate) fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
201+ self.atlas.clone()
202+ }
203+
204+ fn pre_draw(&self, clear_color: &[f32; 4], depth_scale: f32) -> Result<()> {
205+ let resources = self.resources.as_ref().expect("resources missing");
206+ let device_context = &self
207+ .devices
208+ .as_ref()
209+ .expect("devices missing")
210+ .device_context;
211+ update_buffer(
212+ device_context,
213+ self.globals.global_params_buffer.as_ref().unwrap(),
214+ &[GlobalParams {
215+ gamma_ratios: self.font_info.gamma_ratios,
216+ viewport_size: [resources.viewport.Width, resources.viewport.Height],
217+ grayscale_enhanced_contrast: self.font_info.grayscale_enhanced_contrast,
218+ subpixel_enhanced_contrast: self.font_info.subpixel_enhanced_contrast,
219+ is_bgr: self.font_info.is_bgr as u32,
220+ depth_scale,
221+ _pad: [0; 2],
222+ }],
223+ )?;
224+ unsafe {
225+ device_context.ClearRenderTargetView(
226+ resources
227+ .render_target_view
228+ .as_ref()
229+ .context("missing render target view")?,
230+ clear_color,
231+ );
232+ device_context.ClearDepthStencilView(
233+ resources
234+ .depth_stencil_view
235+ .as_ref()
236+ .context("missing depth stencil view")?,
237+ D3D11_CLEAR_DEPTH.0,
238+ 0.0,
239+ 0,
240+ );
241+ device_context.OMSetRenderTargets(
242+ Some(slice::from_ref(&resources.render_target_view)),
243+ resources.depth_stencil_view.as_ref(),
244+ );
245+ device_context.RSSetViewports(Some(slice::from_ref(&resources.viewport)));
246+ device_context
247+ .VSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer)));
248+ device_context
249+ .VSSetConstantBuffers(1, Some(slice::from_ref(&self.globals.batch_params_buffer)));
250+ device_context
251+ .PSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer)));
252+ }
253+ Ok(())
254+ }
255+
256+ fn discard_depth_buffer(&self) -> Option<()> {
257+ let context1 = self.devices.as_ref()?.device_context1.as_ref()?;
258+ let depth_stencil_view = self.resources.as_ref()?.depth_stencil_view.as_ref()?;
259+ unsafe { context1.DiscardView(depth_stencil_view) };
260+ Some(())
261+ }
262+
263+ #[inline]
264+ fn present(&mut self) -> Result<()> {
265+ let result = unsafe {
266+ self.resources
267+ .as_ref()
268+ .expect("resources missing")
269+ .swap_chain
270+ .Present(0, DXGI_PRESENT(0))
271+ };
272+ result.ok().context("Presenting swap chain failed")
273+ }
274+
275+ pub(crate) fn handle_device_lost(&mut self, directx_devices: &DirectXDevices) -> Result<()> {
276+ try_to_recover_from_device_lost(|| {
277+ self.handle_device_lost_impl(directx_devices)
278+ .context("DirectXRenderer handling device lost")
279+ })
280+ }
281+
282+ fn handle_device_lost_impl(&mut self, directx_devices: &DirectXDevices) -> Result<()> {
283+ let disable_direct_composition = self.direct_composition.is_none();
284+
285+ unsafe {
286+ #[cfg(debug_assertions)]
287+ if let Some(devices) = &self.devices {
288+ report_live_objects(&devices.device)
289+ .context("Failed to report live objects after device lost")
290+ .log_err();
291+ }
292+
293+ self.resources.take();
294+ if let Some(devices) = &self.devices {
295+ devices.device_context.OMSetRenderTargets(None, None);
296+ devices.device_context.ClearState();
297+ devices.device_context.Flush();
298+ #[cfg(debug_assertions)]
299+ report_live_objects(&devices.device)
300+ .context("Failed to report live objects after device lost")
301+ .log_err();
302+ }
303+
304+ self.direct_composition.take();
305+ self.devices.take();
306+ }
307+
308+ let devices = DirectXRendererDevices::new(directx_devices, disable_direct_composition)
309+ .context("Recreating DirectX devices")?;
310+ let resources = DirectXResources::new(
311+ &devices,
312+ self.width,
313+ self.height,
314+ self.hwnd,
315+ disable_direct_composition,
316+ )
317+ .context("Creating DirectX resources")?;
318+ let globals = DirectXGlobalElements::new(&devices.device)
319+ .context("Creating DirectXGlobalElements")?;
320+ let pipelines = DirectXRenderPipelines::new(&devices.device)
321+ .context("Creating DirectXRenderPipelines")?;
322+
323+ let direct_composition = if disable_direct_composition {
324+ None
325+ } else {
326+ let composition =
327+ DirectComposition::new(devices.dxgi_device.as_ref().unwrap(), self.hwnd)?;
328+ composition.set_swap_chain(&resources.swap_chain)?;
329+ Some(composition)
330+ };
331+
332+ self.atlas
333+ .handle_device_lost(&devices.device, &devices.device_context);
334+
335+ unsafe {
336+ devices.device_context.OMSetRenderTargets(
337+ Some(slice::from_ref(&resources.render_target_view)),
338+ resources.depth_stencil_view.as_ref(),
339+ );
340+ }
341+ self.devices = Some(devices);
342+ self.resources = Some(resources);
343+ self.globals = globals;
344+ self.pipelines = pipelines;
345+ self.direct_composition = direct_composition;
346+ self.skip_draws = true;
347+ Ok(())
348+ }
349+
350+ pub(crate) fn draw(
351+ &mut self,
352+ scene: &Scene,
353+ background_appearance: WindowBackgroundAppearance,
354+ ) -> Result<()> {
355+ if self.skip_draws {
356+ // skip drawing this frame, we just recovered from a device lost event
357+ // and so likely do not have the textures anymore that are required for drawing
358+ return Ok(());
359+ }
360+ self.render(scene, background_appearance)?;
361+ self.present()
362+ }
363+
364+ /// Clear the render target for `background_appearance` and encode every
365+ /// primitive batch of `scene` into it, without presenting. Shared by
366+ /// [`draw`](Self::draw) (which then presents) and
367+ /// [`render_to_image`](Self::render_to_image) (which reads the target back
368+ /// instead), so the two cannot drift.
369+ fn render(
370+ &mut self,
371+ scene: &Scene,
372+ background_appearance: WindowBackgroundAppearance,
373+ ) -> Result<()> {
374+ let depth_scale = quad_depth_scale(scene.quads.len());
375+ self.pre_draw(
376+ &match background_appearance {
377+ WindowBackgroundAppearance::Opaque => [1.0f32; 4],
378+ _ => [0.0f32; 4],
379+ },
380+ depth_scale,
381+ )?;
382+ self.upload_scene_buffers(scene)?;
383+
384+ let annotation = self
385+ .devices
386+ .as_ref()
387+ .and_then(|devices| devices.annotation.clone())
388+ .filter(|annotation| unsafe { annotation.GetStatus().as_bool() });
389+
390+ if !scene.quads.is_empty() {
391+ let _annotation = annotation.as_ref().map(|annotation| {
392+ Annotation::new(
393+ annotation,
394+ HSTRING::from(format!("opaque quads ({})", scene.quads.len())),
395+ )
396+ });
397+ self.draw_opaque_quads(scene.quads.len())?;
398+ }
399+
400+ let mut quad_cursor: u32 = 0;
401+ let mut path_tile_cursor = 0;
402+ for batch in scene.batches() {
403+ let _annotation = annotation
404+ .as_ref()
405+ .map(|annotation| Annotation::new(annotation, HSTRING::from(batch.label())));
406+
407+ // Quad shaders assign each quad its own depth.
408+ // In every other batch type, the depth is fixed to the position of the quad cursor.
409+ if matches!(&batch, PrimitiveBatch::Quads(_)) {
410+ self.set_viewport_depth_range(0.0, 1.0)?;
411+ } else {
412+ let depth = quad_depth(quad_cursor, depth_scale);
413+ self.set_viewport_depth_range(depth, depth)?;
414+ }
415+
416+ match batch {
417+ PrimitiveBatch::Shadows(range) => self.draw_shadows(range.start, range.len()),
418+ PrimitiveBatch::Quads(range) => {
419+ quad_cursor += range.len() as u32;
420+ self.draw_quads(range.start, range.len())
421+ }
422+ PrimitiveBatch::Paths(range) => {
423+ let tiles_start = path_tile_cursor;
424+ path_tile_cursor += scene.paths[range]
425+ .iter()
426+ .map(PaintedPath::tile_count)
427+ .sum::<usize>();
428+ self.draw_paths(tiles_start..path_tile_cursor)
429+ }
430+ PrimitiveBatch::Underlines(range) => self.draw_underlines(range.start, range.len()),
431+ PrimitiveBatch::MonochromeSprites { texture_id, range } => {
432+ self.draw_monochrome_sprites(texture_id, range.start, range.len())
433+ }
434+ PrimitiveBatch::SubpixelSprites { texture_id, range } => {
435+ self.draw_subpixel_sprites(texture_id, range.start, range.len())
436+ }
437+ PrimitiveBatch::PolychromeSprites { texture_id, range } => {
438+ self.draw_polychrome_sprites(texture_id, range.start, range.len())
439+ }
440+ PrimitiveBatch::Surfaces(range) => self.draw_surfaces(&scene.surfaces[range]),
441+ // Native views are only composited on macOS.
442+ PrimitiveBatch::NativeViews(_) => Ok(()),
443+ }
444+ .with_context(|| {
445+ format!(
446+ "scene too large:\
447+ {} paths, {} shadows, {} quads, {} underlines, {} mono, {} subpixel, {} poly, {} surfaces",
448+ scene.paths.len(),
449+ scene.shadows.len(),
450+ scene.quads.len(),
451+ scene.underlines.len(),
452+ scene.monochrome_sprites.len(),
453+ scene.subpixel_sprites.len(),
454+ scene.polychrome_sprites.len(),
455+ scene.surfaces.len(),
456+ )
457+ })?;
458+ }
459+ self.discard_depth_buffer();
460+ Ok(())
461+ }
462+
463+ /// Render `scene` to an offscreen CPU image **without presenting** so
464+ /// the window need never be shown or visible (the macOS headless path
465+ /// goes through MetalRenderer; this is the Windows analogue). Draws into
466+ /// the existing render target, copies it into a `D3D11_USAGE_STAGING`
467+ /// texture, maps it, and converts BGRA to RGBA.
468+ #[cfg(feature = "test-support")]
469+ pub(crate) fn render_to_image(
470+ &mut self,
471+ scene: &Scene,
472+ background_appearance: WindowBackgroundAppearance,
473+ ) -> Result<image::RgbaImage> {
474+ // A pending device-lost recovery (`skip_draws`) leaves the atlas holding
475+ // tile references from the previous device; drawing before the forced
476+ // re-render rebuilds them panics in `DirectXAtlasTextures::texture`.
477+ anyhow::ensure!(
478+ !self.skip_draws,
479+ "render_to_image unavailable while recovering from a lost device"
480+ );
481+ self.render(scene, background_appearance)?;
482+
483+ let devices = self.devices.as_ref().context("devices missing")?;
484+ let device = &devices.device;
485+ let context = &devices.device_context;
486+ let resources = self.resources.as_ref().context("resources missing")?;
487+ let render_target = resources
488+ .render_target
489+ .as_ref()
490+ .context("render target missing")?;
491+
492+ // A CPU-readable copy of the render target.
493+ let mut desc = D3D11_TEXTURE2D_DESC::default();
494+ unsafe { render_target.GetDesc(&mut desc) };
495+ let width = desc.Width;
496+ let height = desc.Height;
497+ let staging_desc = D3D11_TEXTURE2D_DESC {
498+ Usage: D3D11_USAGE_STAGING,
499+ BindFlags: 0,
500+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
501+ MiscFlags: 0,
502+ MipLevels: 1,
503+ ArraySize: 1,
504+ SampleDesc: DXGI_SAMPLE_DESC {
505+ Count: 1,
506+ Quality: 0,
507+ },
508+ ..desc
509+ };
510+ let mut staging: Option<ID3D11Texture2D> = None;
511+ unsafe { device.CreateTexture2D(&staging_desc, None, Some(&mut staging))? };
512+ let staging = staging.context("creating staging texture")?;
513+ unsafe { context.CopyResource(&staging, render_target) };
514+
515+ let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
516+ unsafe { context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))? };
517+ let row_bytes = (width as usize) * 4;
518+ let mut pixels = vec![0u8; row_bytes * height as usize];
519+ // SAFETY: `Map` succeeded, so `pData` points at `RowPitch * height`
520+ // readable bytes for as long as the mapping is held, and `RowPitch >=
521+ // row_bytes` (it only ever adds trailing padding). `pixels` is sized
522+ // `row_bytes * height`, so every copy stays in bounds on both sides,
523+ // and the regions cannot overlap (`pixels` is a fresh allocation).
524+ unsafe {
525+ let src = mapped.pData as *const u8;
526+ for row in 0..height as usize {
527+ let s = src.add(row * mapped.RowPitch as usize);
528+ let d = pixels.as_mut_ptr().add(row * row_bytes);
529+ std::ptr::copy_nonoverlapping(s, d, row_bytes);
530+ }
531+ context.Unmap(&staging, 0);
532+ }
533+ // The render target is BGRA; image::RgbaImage expects RGBA.
534+ for px in pixels.chunks_exact_mut(4) {
535+ px.swap(0, 2);
536+ }
537+ image::RgbaImage::from_raw(width, height, pixels)
538+ .context("Failed to build RgbaImage from staging readback")
539+ }
540+
541+ fn set_viewport_depth_range(&self, minimum_depth: f32, maximum_depth: f32) -> Result<()> {
542+ let devices = self.devices.as_ref().context("devices missing")?;
543+ let resources = self.resources.as_ref().context("resources missing")?;
544+ // Equal endpoints collapse every shader depth to the same value.
545+ let viewport = D3D11_VIEWPORT {
546+ MinDepth: minimum_depth,
547+ MaxDepth: maximum_depth,
548+ ..resources.viewport
549+ };
550+ unsafe {
551+ devices
552+ .device_context
553+ .RSSetViewports(Some(slice::from_ref(&viewport)))
554+ };
555+ Ok(())
556+ }
557+
558+ fn draw_opaque_quads(&self, quad_count: usize) -> Result<()> {
559+ let devices = self.devices.as_ref().context("devices missing")?;
560+ self.pipelines.opaque_quad_pipeline.draw(
561+ &devices.device_context,
562+ &self.pipelines.quad_pipeline,
563+ self.globals
564+ .batch_params_buffer
565+ .as_ref()
566+ .context("batch params buffer missing")?,
567+ quad_count as u32,
568+ )
569+ }
570+
571+ pub(crate) fn resize(&mut self, new_size: Size<DevicePixels>) -> Result<()> {
572+ let width = new_size.width.0.max(1) as u32;
573+ let height = new_size.height.0.max(1) as u32;
574+ if self.width == width && self.height == height {
575+ return Ok(());
576+ }
577+ self.width = width;
578+ self.height = height;
579+
580+ // Clear the render target before resizing
581+ let devices = self.devices.as_ref().context("devices missing")?;
582+ unsafe { devices.device_context.OMSetRenderTargets(None, None) };
583+ let resources = self.resources.as_mut().context("resources missing")?;
584+ resources.render_target.take();
585+ resources.render_target_view.take();
586+
587+ // Resizing the swap chain requires a call to the underlying DXGI adapter, which can return the device removed error.
588+ // The app might have moved to a monitor that's attached to a different graphics device.
589+ // When a graphics device is removed or reset, the desktop resolution often changes, resulting in a window size change.
590+ // But here we just return the error, because we are handling device lost scenarios elsewhere.
591+ unsafe {
592+ resources
593+ .swap_chain
594+ .ResizeBuffers(
595+ BUFFER_COUNT as u32,
596+ width,
597+ height,
598+ RENDER_TARGET_FORMAT,
599+ DXGI_SWAP_CHAIN_FLAG(0),
600+ )
601+ .context("Failed to resize swap chain")?;
602+ }
603+
604+ resources.recreate_resources(devices, width, height)?;
605+
606+ unsafe {
607+ devices.device_context.OMSetRenderTargets(
608+ Some(slice::from_ref(&resources.render_target_view)),
609+ resources.depth_stencil_view.as_ref(),
610+ );
611+ }
612+
613+ Ok(())
614+ }
615+
616+ fn upload_scene_buffers(&mut self, scene: &Scene) -> Result<()> {
617+ let devices = self.devices.as_ref().context("devices missing")?;
618+
619+ if !scene.shadows.is_empty() {
620+ self.pipelines.shadow_pipeline.update_buffer(
621+ &devices.device,
622+ &devices.device_context,
623+ &scene.shadows,
624+ )?;
625+ }
626+
627+ if !scene.quads.is_empty() {
628+ self.pipelines.quad_pipeline.update_buffer(
629+ &devices.device,
630+ &devices.device_context,
631+ &scene.quads,
632+ )?;
633+ }
634+
635+ if !scene.paths.is_empty() {
636+ let mut paints = Vec::with_capacity(scene.paths.len());
637+ let mut curves = Vec::new();
638+ let mut tiles = Vec::new();
639+ for path in &scene.paths {
640+ path.append_to(&mut paints, &mut curves, &mut tiles);
641+ }
642+
643+ self.pipelines.path_tile_pipeline.update_buffer(
644+ &devices.device,
645+ &devices.device_context,
646+ &tiles,
647+ )?;
648+ self.pipelines
649+ .path_curves
650+ .write(&devices.device, &devices.device_context, &curves)?;
651+ self.pipelines
652+ .path_paints
653+ .write(&devices.device, &devices.device_context, &paints)?;
654+ let buffers = [
655+ self.pipelines.path_curves.view.clone(),
656+ self.pipelines.path_paints.view.clone(),
657+ ];
658+ unsafe {
659+ devices
660+ .device_context
661+ .VSSetShaderResources(2, Some(&buffers));
662+ devices
663+ .device_context
664+ .PSSetShaderResources(2, Some(&buffers));
665+ }
666+ }
667+
668+ if !scene.underlines.is_empty() {
669+ self.pipelines.underline_pipeline.update_buffer(
670+ &devices.device,
671+ &devices.device_context,
672+ &scene.underlines,
673+ )?;
674+ }
675+
676+ if !scene.monochrome_sprites.is_empty() {
677+ self.pipelines.mono_sprites.update_buffer(
678+ &devices.device,
679+ &devices.device_context,
680+ &scene.monochrome_sprites,
681+ )?;
682+ }
683+
684+ if !scene.subpixel_sprites.is_empty() {
685+ self.pipelines.subpixel_sprites.update_buffer(
686+ &devices.device,
687+ &devices.device_context,
688+ &scene.subpixel_sprites,
689+ )?;
690+ }
691+
692+ if !scene.polychrome_sprites.is_empty() {
693+ self.pipelines.poly_sprites.update_buffer(
694+ &devices.device,
695+ &devices.device_context,
696+ &scene.polychrome_sprites,
697+ )?;
698+ }
699+
700+ Ok(())
701+ }
702+
703+ fn draw_shadows(&mut self, start: usize, len: usize) -> Result<()> {
704+ if len == 0 {
705+ return Ok(());
706+ }
707+ let devices = self.devices.as_ref().context("devices missing")?;
708+ self.pipelines.shadow_pipeline.draw_range(
709+ &devices.device_context,
710+ self.globals
711+ .batch_params_buffer
712+ .as_ref()
713+ .context("batch params buffer missing")?,
714+ start as u32,
715+ len as u32,
716+ )
717+ }
718+
719+ fn draw_quads(&mut self, start: usize, len: usize) -> Result<()> {
720+ if len == 0 {
721+ return Ok(());
722+ }
723+ let devices = self.devices.as_ref().context("devices missing")?;
724+ self.pipelines.quad_pipeline.draw_range(
725+ &devices.device_context,
726+ self.globals
727+ .batch_params_buffer
728+ .as_ref()
729+ .context("batch params buffer missing")?,
730+ start as u32,
731+ len as u32,
732+ )
733+ }
734+
735+ fn draw_paths(&mut self, tile_range: Range<usize>) -> Result<()> {
736+ if tile_range.is_empty() {
737+ return Ok(());
738+ }
739+ let devices = self.devices.as_ref().context("devices missing")?;
740+ self.pipelines.path_tile_pipeline.draw_range(
741+ &devices.device_context,
742+ self.globals
743+ .batch_params_buffer
744+ .as_ref()
745+ .context("batch params buffer missing")?,
746+ tile_range.start as u32,
747+ tile_range.len() as u32,
748+ )
749+ }
750+
751+ fn draw_underlines(&mut self, start: usize, len: usize) -> Result<()> {
752+ if len == 0 {
753+ return Ok(());
754+ }
755+ let devices = self.devices.as_ref().context("devices missing")?;
756+ self.pipelines.underline_pipeline.draw_range(
757+ &devices.device_context,
758+ self.globals
759+ .batch_params_buffer
760+ .as_ref()
761+ .context("batch params buffer missing")?,
762+ start as u32,
763+ len as u32,
764+ )
765+ }
766+
767+ fn draw_monochrome_sprites(
768+ &mut self,
769+ texture_id: AtlasTextureId,
770+ start: usize,
771+ len: usize,
772+ ) -> Result<()> {
773+ if len == 0 {
774+ return Ok(());
775+ }
776+ let devices = self.devices.as_ref().context("devices missing")?;
777+ let Some(texture_view) = self.atlas.get_texture_view(texture_id) else {
778+ return Ok(());
779+ };
780+ self.pipelines.mono_sprites.draw_range_with_texture(
781+ &devices.device_context,
782+ &texture_view,
783+ self.globals
784+ .batch_params_buffer
785+ .as_ref()
786+ .context("batch params buffer missing")?,
787+ slice::from_ref(&self.globals.sampler),
788+ start as u32,
789+ len as u32,
790+ )
791+ }
792+
793+ fn draw_subpixel_sprites(
794+ &mut self,
795+ texture_id: AtlasTextureId,
796+ start: usize,
797+ len: usize,
798+ ) -> Result<()> {
799+ if len == 0 {
800+ return Ok(());
801+ }
802+ let devices = self.devices.as_ref().context("devices missing")?;
803+ let Some(texture_view) = self.atlas.get_texture_view(texture_id) else {
804+ return Ok(());
805+ };
806+ self.pipelines.subpixel_sprites.draw_range_with_texture(
807+ &devices.device_context,
808+ &texture_view,
809+ self.globals
810+ .batch_params_buffer
811+ .as_ref()
812+ .context("batch params buffer missing")?,
813+ slice::from_ref(&self.globals.sampler),
814+ start as u32,
815+ len as u32,
816+ )
817+ }
818+
819+ fn draw_polychrome_sprites(
820+ &mut self,
821+ texture_id: AtlasTextureId,
822+ start: usize,
823+ len: usize,
824+ ) -> Result<()> {
825+ if len == 0 {
826+ return Ok(());
827+ }
828+ let devices = self.devices.as_ref().context("devices missing")?;
829+ let Some(texture_view) = self.atlas.get_texture_view(texture_id) else {
830+ return Ok(());
831+ };
832+ self.pipelines.poly_sprites.draw_range_with_texture(
833+ &devices.device_context,
834+ &texture_view,
835+ self.globals
836+ .batch_params_buffer
837+ .as_ref()
838+ .context("batch params buffer missing")?,
839+ slice::from_ref(&self.globals.sampler),
840+ start as u32,
841+ len as u32,
842+ )
843+ }
844+
845+ fn draw_surfaces(&mut self, surfaces: &[PaintSurface]) -> Result<()> {
846+ if surfaces.is_empty() {
847+ return Ok(());
848+ }
849+ Ok(())
850+ }
851+
852+ pub(crate) fn gpu_specs(&self) -> Result<GpuSpecs> {
853+ let devices = self.devices.as_ref().context("devices missing")?;
854+ let desc = unsafe { devices.adapter.GetDesc1() }?;
855+ let is_software_emulated = (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32) != 0;
856+ let device_name = String::from_utf16_lossy(&desc.Description)
857+ .trim_matches(char::from(0))
858+ .to_string();
859+ let driver_name = match desc.VendorId {
860+ 0x10DE => "NVIDIA Corporation".to_string(),
861+ 0x1002 => "AMD Corporation".to_string(),
862+ 0x8086 => "Intel Corporation".to_string(),
863+ id => format!("Unknown Vendor (ID: {:#X})", id),
864+ };
865+ let driver_version = match desc.VendorId {
866+ 0x10DE => nvidia::get_driver_version(),
867+ 0x1002 => amd::get_driver_version(),
868+ // For Intel and other vendors, we use the DXGI API to get the driver version.
869+ _ => dxgi::get_driver_version(&devices.adapter),
870+ }
871+ .context("Failed to get gpu driver info")
872+ .log_err()
873+ .unwrap_or("Unknown Driver".to_string());
874+ Ok(GpuSpecs {
875+ is_software_emulated,
876+ device_name,
877+ driver_name,
878+ driver_info: driver_version,
879+ })
880+ }
881+
882+ pub(crate) fn get_font_info() -> &'static FontInfo {
883+ static CACHED_FONT_INFO: OnceLock<FontInfo> = OnceLock::new();
884+ CACHED_FONT_INFO.get_or_init(|| unsafe {
885+ let factory: IDWriteFactory5 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED).unwrap();
886+ let render_params: IDWriteRenderingParams1 =
887+ factory.CreateRenderingParams().unwrap().cast().unwrap();
888+ FontInfo {
889+ gamma_ratios: gpui::get_gamma_correction_ratios(render_params.GetGamma()),
890+ grayscale_enhanced_contrast: render_params.GetGrayscaleEnhancedContrast(),
891+ subpixel_enhanced_contrast: render_params.GetEnhancedContrast(),
892+ is_bgr: render_params.GetPixelGeometry() == DWRITE_PIXEL_GEOMETRY_BGR,
893+ }
894+ })
895+ }
896+
897+ pub(crate) fn mark_drawable(&mut self) {
898+ self.skip_draws = false;
899+ }
900+}
901+
902+impl DirectXResources {
903+ pub fn new(
904+ devices: &DirectXRendererDevices,
905+ width: u32,
906+ height: u32,
907+ hwnd: HWND,
908+ disable_direct_composition: bool,
909+ ) -> Result<Self> {
910+ let swap_chain = if disable_direct_composition {
911+ create_swap_chain(&devices.dxgi_factory, &devices.device, hwnd, width, height)?
912+ } else {
913+ create_swap_chain_for_composition(
914+ &devices.dxgi_factory,
915+ &devices.device,
916+ width,
917+ height,
918+ )?
919+ };
920+
921+ let (
922+ render_target,
923+ render_target_view,
924+ depth_stencil_texture,
925+ depth_stencil_view,
926+ viewport,
927+ ) = create_resources(devices, &swap_chain, width, height)?;
928+ set_rasterizer_state(&devices.device, &devices.device_context)?;
929+
930+ Ok(Self {
931+ swap_chain,
932+ render_target: Some(render_target),
933+ render_target_view,
934+ depth_stencil_texture,
935+ depth_stencil_view,
936+ viewport,
937+ })
938+ }
939+
940+ #[inline]
941+ fn recreate_resources(
942+ &mut self,
943+ devices: &DirectXRendererDevices,
944+ width: u32,
945+ height: u32,
946+ ) -> Result<()> {
947+ let (
948+ render_target,
949+ render_target_view,
950+ depth_stencil_texture,
951+ depth_stencil_view,
952+ viewport,
953+ ) = create_resources(devices, &self.swap_chain, width, height)?;
954+ self.render_target = Some(render_target);
955+ self.render_target_view = render_target_view;
956+ self.depth_stencil_texture = depth_stencil_texture;
957+ self.depth_stencil_view = depth_stencil_view;
958+ self.viewport = viewport;
959+ Ok(())
960+ }
961+}
962+
963+impl DirectXRenderPipelines {
964+ pub fn new(device: &ID3D11Device) -> Result<Self> {
965+ let shadow_pipeline = PipelineState::new(
966+ device,
967+ "shadow_pipeline",
968+ ShaderModule::Shadow,
969+ 4,
970+ create_blend_state(device)?,
971+ )?;
972+ let quad_pipeline = PipelineState::new(
973+ device,
974+ "quad_pipeline",
975+ ShaderModule::Quad,
976+ 64,
977+ create_blend_state(device)?,
978+ )?;
979+ let path_tile_pipeline = PipelineState::new(
980+ device,
981+ "path_tile_pipeline",
982+ ShaderModule::PathTile,
983+ 64,
984+ create_blend_state(device)?,
985+ )?;
986+ let path_curves = StructuredBuffer::new(device, "path_curves", 256)?;
987+ let path_paints = StructuredBuffer::new(device, "path_paints", 64)?;
988+ let underline_pipeline = PipelineState::new(
989+ device,
990+ "underline_pipeline",
991+ ShaderModule::Underline,
992+ 4,
993+ create_blend_state(device)?,
994+ )?;
995+ let mono_sprites = PipelineState::new(
996+ device,
997+ "monochrome_sprite_pipeline",
998+ ShaderModule::MonochromeSprite,
999+ 512,
1000+ create_blend_state(device)?,
1001+ )?;
1002+ let subpixel_sprites = PipelineState::new(
1003+ device,
1004+ "subpixel_sprite_pipeline",
1005+ ShaderModule::SubpixelSprite,
1006+ 512,
1007+ create_blend_state_for_subpixel_rendering(device)?,
1008+ )?;
1009+ let poly_sprites = PipelineState::new(
1010+ device,
1011+ "polychrome_sprite_pipeline",
1012+ ShaderModule::PolychromeSprite,
1013+ 16,
1014+ create_blend_state(device)?,
1015+ )?;
1016+ let opaque_quad_pipeline = OpaqueQuadPipeline::new(device)?;
1017+
1018+ Ok(Self {
1019+ shadow_pipeline,
1020+ quad_pipeline,
1021+ opaque_quad_pipeline,
1022+ path_tile_pipeline,
1023+ path_curves,
1024+ path_paints,
1025+ underline_pipeline,
1026+ mono_sprites,
1027+ subpixel_sprites,
1028+ poly_sprites,
1029+ })
1030+ }
1031+}
1032+
1033+impl DirectComposition {
1034+ pub fn new(dxgi_device: &IDXGIDevice, hwnd: HWND) -> Result<Self> {
1035+ let comp_device = get_comp_device(dxgi_device)?;
1036+ let comp_target = unsafe { comp_device.CreateTargetForHwnd(hwnd, false) }?;
1037+ let comp_visual = unsafe { comp_device.CreateVisual() }?;
1038+
1039+ Ok(Self {
1040+ comp_device,
1041+ comp_target,
1042+ comp_visual,
1043+ })
1044+ }
1045+
1046+ pub fn set_swap_chain(&self, swap_chain: &IDXGISwapChain1) -> Result<()> {
1047+ unsafe {
1048+ self.comp_visual.SetContent(swap_chain)?;
1049+ self.comp_target.SetRoot(&self.comp_visual)?;
1050+ self.comp_device.Commit()?;
1051+ }
1052+ Ok(())
1053+ }
1054+}
1055+
1056+impl DirectXGlobalElements {
1057+ pub fn new(device: &ID3D11Device) -> Result<Self> {
1058+ let global_params_buffer = create_constant_buffer::<GlobalParams>(device)?;
1059+ let batch_params_buffer = create_constant_buffer::<BatchParams>(device)?;
1060+
1061+ let sampler = unsafe {
1062+ let desc = D3D11_SAMPLER_DESC {
1063+ Filter: D3D11_FILTER_MIN_MAG_MIP_LINEAR,
1064+ AddressU: D3D11_TEXTURE_ADDRESS_WRAP,
1065+ AddressV: D3D11_TEXTURE_ADDRESS_WRAP,
1066+ AddressW: D3D11_TEXTURE_ADDRESS_WRAP,
1067+ MipLODBias: 0.0,
1068+ MaxAnisotropy: 1,
1069+ ComparisonFunc: D3D11_COMPARISON_ALWAYS,
1070+ BorderColor: [0.0; 4],
1071+ MinLOD: 0.0,
1072+ MaxLOD: D3D11_FLOAT32_MAX,
1073+ };
1074+ let mut output = None;
1075+ device.CreateSamplerState(&desc, Some(&mut output))?;
1076+ output
1077+ };
1078+
1079+ Ok(Self {
1080+ global_params_buffer,
1081+ batch_params_buffer,
1082+ sampler,
1083+ })
1084+ }
1085+}
1086+
1087+#[derive(Debug, Default)]
1088+#[repr(C)]
1089+struct GlobalParams {
1090+ gamma_ratios: [f32; 4],
1091+ viewport_size: [f32; 2],
1092+ grayscale_enhanced_contrast: f32,
1093+ subpixel_enhanced_contrast: f32,
1094+ is_bgr: u32,
1095+ depth_scale: f32,
1096+ _pad: [u32; 2],
1097+}
1098+
1099+#[derive(Clone, Copy, Debug, Default)]
1100+#[repr(C, align(16))]
1101+struct BatchParams {
1102+ start_index: u32,
1103+ _padding: [u32; 3],
1104+}
1105+
1106+struct StructuredBuffer<T> {
1107+ label: &'static str,
1108+ buffer: ID3D11Buffer,
1109+ capacity: usize,
1110+ view: Option<ID3D11ShaderResourceView>,
1111+ _marker: std::marker::PhantomData<T>,
1112+}
1113+
1114+impl<T> StructuredBuffer<T> {
1115+ fn new(device: &ID3D11Device, label: &'static str, capacity: usize) -> Result<Self> {
1116+ let buffer = create_buffer(device, std::mem::size_of::<T>(), capacity)?;
1117+ let view = create_buffer_view(device, &buffer)?;
1118+ Ok(StructuredBuffer {
1119+ label,
1120+ buffer,
1121+ capacity,
1122+ view,
1123+ _marker: std::marker::PhantomData,
1124+ })
1125+ }
1126+
1127+ fn write(
1128+ &mut self,
1129+ device: &ID3D11Device,
1130+ device_context: &ID3D11DeviceContext,
1131+ data: &[T],
1132+ ) -> Result<()> {
1133+ self.ensure_capacity(device, data.len())?;
1134+ update_buffer(device_context, &self.buffer, data)
1135+ }
1136+
1137+ fn ensure_capacity(&mut self, device: &ID3D11Device, len: usize) -> Result<()> {
1138+ if self.capacity < len {
1139+ let element_size = std::mem::size_of::<T>().max(1);
1140+ let required_size = len.checked_mul(element_size);
1141+ anyhow::ensure!(
1142+ required_size.is_some_and(|size| size <= MAX_INSTANCE_BUFFER_SIZE),
1143+ "{} buffer needs {len} elements of {element_size} bytes, above the maximum of {MAX_INSTANCE_BUFFER_SIZE} bytes",
1144+ self.label
1145+ );
1146+ let new_capacity = len
1147+ .next_power_of_two()
1148+ .min(MAX_INSTANCE_BUFFER_SIZE / element_size);
1149+ log::debug!(
1150+ "Updating {} buffer size from {} to {}",
1151+ self.label,
1152+ self.capacity,
1153+ new_capacity
1154+ );
1155+ let buffer = create_buffer(device, std::mem::size_of::<T>(), new_capacity)?;
1156+ let view = create_buffer_view(device, &buffer)?;
1157+ self.buffer = buffer;
1158+ self.view = view;
1159+ self.capacity = new_capacity;
1160+ }
1161+ Ok(())
1162+ }
1163+}
1164+
1165+struct PipelineState<T> {
1166+ vertex: ID3D11VertexShader,
1167+ fragment: ID3D11PixelShader,
1168+ instances: StructuredBuffer<T>,
1169+ blend_state: ID3D11BlendState,
1170+ depth_stencil_state: ID3D11DepthStencilState,
1171+}
1172+
1173+impl<T> PipelineState<T> {
1174+ fn new(
1175+ device: &ID3D11Device,
1176+ label: &'static str,
1177+ shader_module: ShaderModule,
1178+ buffer_size: usize,
1179+ blend_state: ID3D11BlendState,
1180+ ) -> Result<Self> {
1181+ let vertex = {
1182+ let raw_shader = RawShaderBytes::new(shader_module, ShaderTarget::Vertex)?;
1183+ create_vertex_shader(device, raw_shader.as_bytes())?
1184+ };
1185+ let fragment = {
1186+ let raw_shader = RawShaderBytes::new(shader_module, ShaderTarget::Fragment)?;
1187+ create_fragment_shader(device, raw_shader.as_bytes())?
1188+ };
1189+
1190+ Ok(PipelineState {
1191+ vertex,
1192+ fragment,
1193+ instances: StructuredBuffer::new(device, label, buffer_size)?,
1194+ blend_state,
1195+ depth_stencil_state: create_depth_stencil_state(device, D3D11_DEPTH_WRITE_MASK_ZERO)?,
1196+ })
1197+ }
1198+
1199+ fn update_buffer(
1200+ &mut self,
1201+ device: &ID3D11Device,
1202+ device_context: &ID3D11DeviceContext,
1203+ data: &[T],
1204+ ) -> Result<()> {
1205+ self.instances.write(device, device_context, data)
1206+ }
1207+
1208+ fn draw_range(
1209+ &self,
1210+ device_context: &ID3D11DeviceContext,
1211+ batch_params_buffer: &ID3D11Buffer,
1212+ first_instance: u32,
1213+ instance_count: u32,
1214+ ) -> Result<()> {
1215+ self.ensure_range(first_instance, instance_count)?;
1216+ update_batch_start(device_context, batch_params_buffer, first_instance)?;
1217+ set_pipeline_state(
1218+ device_context,
1219+ slice::from_ref(&self.instances.view),
1220+ D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
1221+ &self.vertex,
1222+ &self.fragment,
1223+ &self.blend_state,
1224+ &self.depth_stencil_state,
1225+ );
1226+ unsafe {
1227+ device_context.DrawInstanced(4, instance_count, 0, 0);
1228+ }
1229+ Ok(())
1230+ }
1231+
1232+ fn draw_range_with_texture(
1233+ &self,
1234+ device_context: &ID3D11DeviceContext,
1235+ texture: &[Option<ID3D11ShaderResourceView>],
1236+ batch_params_buffer: &ID3D11Buffer,
1237+ sampler: &[Option<ID3D11SamplerState>],
1238+ first_instance: u32,
1239+ instance_count: u32,
1240+ ) -> Result<()> {
1241+ self.ensure_range(first_instance, instance_count)?;
1242+ update_batch_start(device_context, batch_params_buffer, first_instance)?;
1243+ set_pipeline_state(
1244+ device_context,
1245+ slice::from_ref(&self.instances.view),
1246+ D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
1247+ &self.vertex,
1248+ &self.fragment,
1249+ &self.blend_state,
1250+ &self.depth_stencil_state,
1251+ );
1252+ unsafe {
1253+ device_context.PSSetSamplers(0, Some(sampler));
1254+ device_context.VSSetShaderResources(0, Some(texture));
1255+ device_context.PSSetShaderResources(0, Some(texture));
1256+ device_context.DrawInstanced(4, instance_count, 0, 0);
1257+ }
1258+ Ok(())
1259+ }
1260+
1261+ fn ensure_range(&self, first_instance: u32, instance_count: u32) -> Result<()> {
1262+ anyhow::ensure!(
1263+ first_instance as usize + instance_count as usize <= self.instances.capacity,
1264+ "DirectX instance range exceeds the {} buffer",
1265+ self.instances.label
1266+ );
1267+ Ok(())
1268+ }
1269+}
1270+
1271+/// Draws opaque rectangles ahead of everything else, writing depth so that
1272+/// later passes skip the pixels they cover.
1273+struct OpaqueQuadPipeline {
1274+ vertex: ID3D11VertexShader,
1275+ fragment: ID3D11PixelShader,
1276+ blend_state: ID3D11BlendState,
1277+ depth_stencil_state: ID3D11DepthStencilState,
1278+}
1279+
1280+impl OpaqueQuadPipeline {
1281+ fn new(device: &ID3D11Device) -> Result<Self> {
1282+ let vertex = {
1283+ let raw_shader = RawShaderBytes::new(ShaderModule::OpaqueQuad, ShaderTarget::Vertex)?;
1284+ create_vertex_shader(device, raw_shader.as_bytes())?
1285+ };
1286+ let fragment = {
1287+ let raw_shader = RawShaderBytes::new(ShaderModule::OpaqueQuad, ShaderTarget::Fragment)?;
1288+ create_fragment_shader(device, raw_shader.as_bytes())?
1289+ };
1290+ Ok(OpaqueQuadPipeline {
1291+ vertex,
1292+ fragment,
1293+ blend_state: create_opaque_blend_state(device)?,
1294+ depth_stencil_state: create_depth_stencil_state(device, D3D11_DEPTH_WRITE_MASK_ALL)?,
1295+ })
1296+ }
1297+
1298+ /// Draws every quad, last first. The vertex shader drops all but opaque
1299+ /// rectangles.
1300+ fn draw(
1301+ &self,
1302+ device_context: &ID3D11DeviceContext,
1303+ quad_pipeline: &PipelineState<Quad>,
1304+ batch_params_buffer: &ID3D11Buffer,
1305+ quad_count: u32,
1306+ ) -> Result<()> {
1307+ if quad_count == 0 {
1308+ return Ok(());
1309+ }
1310+ quad_pipeline.ensure_range(0, quad_count)?;
1311+ // Drawing front to back lets the depth test skip pixels that a later
1312+ // quad already covers.
1313+ update_batch_start(device_context, batch_params_buffer, quad_count - 1)?;
1314+ set_pipeline_state(
1315+ device_context,
1316+ slice::from_ref(&quad_pipeline.instances.view),
1317+ D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
1318+ &self.vertex,
1319+ &self.fragment,
1320+ &self.blend_state,
1321+ &self.depth_stencil_state,
1322+ );
1323+ unsafe { device_context.DrawInstanced(4, quad_count, 0, 0) };
1324+ Ok(())
1325+ }
1326+}
1327+
1328+impl Drop for DirectXRenderer {
1329+ fn drop(&mut self) {
1330+ #[cfg(debug_assertions)]
1331+ if let Some(devices) = &self.devices {
1332+ report_live_objects(&devices.device).ok();
1333+ }
1334+ }
1335+}
1336+
1337+#[inline]
1338+fn get_comp_device(dxgi_device: &IDXGIDevice) -> Result<IDCompositionDevice> {
1339+ Ok(unsafe { DCompositionCreateDevice(dxgi_device)? })
1340+}
1341+
1342+fn create_swap_chain_for_composition(
1343+ dxgi_factory: &IDXGIFactory6,
1344+ device: &ID3D11Device,
1345+ width: u32,
1346+ height: u32,
1347+) -> Result<IDXGISwapChain1> {
1348+ let desc = DXGI_SWAP_CHAIN_DESC1 {
1349+ Width: width,
1350+ Height: height,
1351+ Format: RENDER_TARGET_FORMAT,
1352+ Stereo: false.into(),
1353+ SampleDesc: DXGI_SAMPLE_DESC {
1354+ Count: 1,
1355+ Quality: 0,
1356+ },
1357+ BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
1358+ BufferCount: BUFFER_COUNT as u32,
1359+ // Composition SwapChains only support the DXGI_SCALING_STRETCH Scaling.
1360+ Scaling: DXGI_SCALING_STRETCH,
1361+ SwapEffect: DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,
1362+ AlphaMode: DXGI_ALPHA_MODE_PREMULTIPLIED,
1363+ Flags: 0,
1364+ };
1365+ Ok(unsafe { dxgi_factory.CreateSwapChainForComposition(device, &desc, None)? })
1366+}
1367+
1368+fn create_swap_chain(
1369+ dxgi_factory: &IDXGIFactory6,
1370+ device: &ID3D11Device,
1371+ hwnd: HWND,
1372+ width: u32,
1373+ height: u32,
1374+) -> Result<IDXGISwapChain1> {
1375+ use windows::Win32::Graphics::Dxgi::DXGI_MWA_NO_ALT_ENTER;
1376+
1377+ let desc = DXGI_SWAP_CHAIN_DESC1 {
1378+ Width: width,
1379+ Height: height,
1380+ Format: RENDER_TARGET_FORMAT,
1381+ Stereo: false.into(),
1382+ SampleDesc: DXGI_SAMPLE_DESC {
1383+ Count: 1,
1384+ Quality: 0,
1385+ },
1386+ BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
1387+ BufferCount: BUFFER_COUNT as u32,
1388+ Scaling: DXGI_SCALING_NONE,
1389+ SwapEffect: DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,
1390+ AlphaMode: DXGI_ALPHA_MODE_IGNORE,
1391+ Flags: 0,
1392+ };
1393+ let swap_chain =
1394+ unsafe { dxgi_factory.CreateSwapChainForHwnd(device, hwnd, &desc, None, None) }?;
1395+ unsafe { dxgi_factory.MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER) }?;
1396+ Ok(swap_chain)
1397+}
1398+
1399+#[inline]
1400+fn create_resources(
1401+ devices: &DirectXRendererDevices,
1402+ swap_chain: &IDXGISwapChain1,
1403+ width: u32,
1404+ height: u32,
1405+) -> Result<(
1406+ ID3D11Texture2D,
1407+ Option<ID3D11RenderTargetView>,
1408+ ID3D11Texture2D,
1409+ Option<ID3D11DepthStencilView>,
1410+ D3D11_VIEWPORT,
1411+)> {
1412+ let (render_target, render_target_view) =
1413+ create_render_target_and_its_view(swap_chain, &devices.device)?;
1414+ let (depth_stencil_texture, depth_stencil_view) =
1415+ create_depth_stencil_texture_and_view(&devices.device, width, height)?;
1416+ let viewport = set_viewport(&devices.device_context, width as f32, height as f32);
1417+ Ok((
1418+ render_target,
1419+ render_target_view,
1420+ depth_stencil_texture,
1421+ depth_stencil_view,
1422+ viewport,
1423+ ))
1424+}
1425+
1426+#[inline]
1427+fn create_render_target_and_its_view(
1428+ swap_chain: &IDXGISwapChain1,
1429+ device: &ID3D11Device,
1430+) -> Result<(ID3D11Texture2D, Option<ID3D11RenderTargetView>)> {
1431+ let render_target: ID3D11Texture2D = unsafe { swap_chain.GetBuffer(0) }?;
1432+ let mut render_target_view = None;
1433+ unsafe { device.CreateRenderTargetView(&render_target, None, Some(&mut render_target_view))? };
1434+ Ok((render_target, render_target_view))
1435+}
1436+
1437+#[inline]
1438+fn set_viewport(device_context: &ID3D11DeviceContext, width: f32, height: f32) -> D3D11_VIEWPORT {
1439+ let viewport = [D3D11_VIEWPORT {
1440+ TopLeftX: 0.0,
1441+ TopLeftY: 0.0,
1442+ Width: width,
1443+ Height: height,
1444+ MinDepth: 0.0,
1445+ MaxDepth: 1.0,
1446+ }];
1447+ unsafe { device_context.RSSetViewports(Some(&viewport)) };
1448+ viewport[0]
1449+}
1450+
1451+#[inline]
1452+fn create_depth_stencil_texture_and_view(
1453+ device: &ID3D11Device,
1454+ width: u32,
1455+ height: u32,
1456+) -> Result<(ID3D11Texture2D, Option<ID3D11DepthStencilView>)> {
1457+ let texture = unsafe {
1458+ let mut output = None;
1459+ let desc = D3D11_TEXTURE2D_DESC {
1460+ Width: width,
1461+ Height: height,
1462+ MipLevels: 1,
1463+ ArraySize: 1,
1464+ Format: DXGI_FORMAT_D32_FLOAT,
1465+ SampleDesc: DXGI_SAMPLE_DESC {
1466+ Count: 1,
1467+ Quality: 0,
1468+ },
1469+ Usage: D3D11_USAGE_DEFAULT,
1470+ BindFlags: D3D11_BIND_DEPTH_STENCIL.0 as u32,
1471+ CPUAccessFlags: 0,
1472+ MiscFlags: 0,
1473+ };
1474+ device.CreateTexture2D(&desc, None, Some(&mut output))?;
1475+ output.unwrap()
1476+ };
1477+ let mut view = None;
1478+ unsafe { device.CreateDepthStencilView(&texture, None, Some(&mut view))? };
1479+ Ok((texture, view))
1480+}
1481+
1482+#[inline]
1483+fn set_rasterizer_state(device: &ID3D11Device, device_context: &ID3D11DeviceContext) -> Result<()> {
1484+ let desc = D3D11_RASTERIZER_DESC {
1485+ FillMode: D3D11_FILL_SOLID,
1486+ CullMode: D3D11_CULL_NONE,
1487+ FrontCounterClockwise: false.into(),
1488+ DepthBias: 0,
1489+ DepthBiasClamp: 0.0,
1490+ SlopeScaledDepthBias: 0.0,
1491+ DepthClipEnable: true.into(),
1492+ ScissorEnable: false.into(),
1493+ MultisampleEnable: true.into(),
1494+ AntialiasedLineEnable: false.into(),
1495+ };
1496+ let rasterizer_state = unsafe {
1497+ let mut state = None;
1498+ device.CreateRasterizerState(&desc, Some(&mut state))?;
1499+ state.unwrap()
1500+ };
1501+ unsafe { device_context.RSSetState(&rasterizer_state) };
1502+ Ok(())
1503+}
1504+
1505+// https://learn.microsoft.com/en-us/windows/win32/api/d3d11/ns-d3d11-d3d11_blend_desc
1506+#[inline]
1507+fn create_blend_state(device: &ID3D11Device) -> Result<ID3D11BlendState> {
1508+ let mut desc = D3D11_BLEND_DESC::default();
1509+ desc.RenderTarget[0].BlendEnable = true.into();
1510+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
1511+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
1512+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
1513+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
1514+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
1515+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
1516+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8;
1517+ unsafe {
1518+ let mut state = None;
1519+ device.CreateBlendState(&desc, Some(&mut state))?;
1520+ Ok(state.unwrap())
1521+ }
1522+}
1523+
1524+#[inline]
1525+fn create_opaque_blend_state(device: &ID3D11Device) -> Result<ID3D11BlendState> {
1526+ let mut desc = D3D11_BLEND_DESC::default();
1527+ desc.RenderTarget[0].BlendEnable = false.into();
1528+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
1529+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
1530+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
1531+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
1532+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO;
1533+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
1534+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8;
1535+ unsafe {
1536+ let mut state = None;
1537+ device.CreateBlendState(&desc, Some(&mut state))?;
1538+ Ok(state.unwrap())
1539+ }
1540+}
1541+
1542+#[inline]
1543+fn create_depth_stencil_state(
1544+ device: &ID3D11Device,
1545+ write_mask: D3D11_DEPTH_WRITE_MASK,
1546+) -> Result<ID3D11DepthStencilState> {
1547+ let stencil_op = D3D11_DEPTH_STENCILOP_DESC {
1548+ StencilFailOp: D3D11_STENCIL_OP_KEEP,
1549+ StencilDepthFailOp: D3D11_STENCIL_OP_KEEP,
1550+ StencilPassOp: D3D11_STENCIL_OP_KEEP,
1551+ StencilFunc: D3D11_COMPARISON_ALWAYS,
1552+ };
1553+ let desc = D3D11_DEPTH_STENCIL_DESC {
1554+ DepthEnable: true.into(),
1555+ DepthWriteMask: write_mask,
1556+ DepthFunc: D3D11_COMPARISON_GREATER,
1557+ StencilEnable: false.into(),
1558+ StencilReadMask: D3D11_DEFAULT_STENCIL_READ_MASK as u8,
1559+ StencilWriteMask: D3D11_DEFAULT_STENCIL_WRITE_MASK as u8,
1560+ FrontFace: stencil_op,
1561+ BackFace: stencil_op,
1562+ };
1563+ unsafe {
1564+ let mut state = None;
1565+ device.CreateDepthStencilState(&desc, Some(&mut state))?;
1566+ Ok(state.unwrap())
1567+ }
1568+}
1569+
1570+#[inline]
1571+fn create_blend_state_for_subpixel_rendering(device: &ID3D11Device) -> Result<ID3D11BlendState> {
1572+ let mut desc = D3D11_BLEND_DESC::default();
1573+ desc.RenderTarget[0].BlendEnable = true.into();
1574+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
1575+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
1576+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC1_COLOR;
1577+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC1_COLOR;
1578+ // It does not make sense to draw transparent subpixel-rendered text, since it cannot be meaningfully alpha-blended onto anything else.
1579+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
1580+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
1581+ desc.RenderTarget[0].RenderTargetWriteMask =
1582+ D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8 & !D3D11_COLOR_WRITE_ENABLE_ALPHA.0 as u8;
1583+
1584+ unsafe {
1585+ let mut state = None;
1586+ device.CreateBlendState(&desc, Some(&mut state))?;
1587+ Ok(state.unwrap())
1588+ }
1589+}
1590+
1591+#[inline]
1592+fn create_vertex_shader(device: &ID3D11Device, bytes: &[u8]) -> Result<ID3D11VertexShader> {
1593+ unsafe {
1594+ let mut shader = None;
1595+ device.CreateVertexShader(bytes, None, Some(&mut shader))?;
1596+ Ok(shader.unwrap())
1597+ }
1598+}
1599+
1600+#[inline]
1601+fn create_fragment_shader(device: &ID3D11Device, bytes: &[u8]) -> Result<ID3D11PixelShader> {
1602+ unsafe {
1603+ let mut shader = None;
1604+ device.CreatePixelShader(bytes, None, Some(&mut shader))?;
1605+ Ok(shader.unwrap())
1606+ }
1607+}
1608+
1609+#[inline]
1610+fn create_constant_buffer<T>(device: &ID3D11Device) -> Result<Option<ID3D11Buffer>> {
1611+ const { assert!(std::mem::size_of::<T>() != 0 && std::mem::size_of::<T>().is_multiple_of(16)) };
1612+ let desc = D3D11_BUFFER_DESC {
1613+ ByteWidth: std::mem::size_of::<T>() as u32,
1614+ Usage: D3D11_USAGE_DYNAMIC,
1615+ BindFlags: D3D11_BIND_CONSTANT_BUFFER.0 as u32,
1616+ CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,
1617+ MiscFlags: 0,
1618+ StructureByteStride: 0,
1619+ };
1620+ let mut buffer = None;
1621+ unsafe { device.CreateBuffer(&desc, None, Some(&mut buffer)) }?;
1622+ Ok(buffer)
1623+}
1624+
1625+#[inline]
1626+fn create_buffer(
1627+ device: &ID3D11Device,
1628+ element_size: usize,
1629+ buffer_size: usize,
1630+) -> Result<ID3D11Buffer> {
1631+ let byte_width = element_size
1632+ .checked_mul(buffer_size)
1633+ .and_then(|size| u32::try_from(size).ok())
1634+ .context("structured buffer size overflows u32")?;
1635+ let desc = D3D11_BUFFER_DESC {
1636+ ByteWidth: byte_width,
1637+ Usage: D3D11_USAGE_DYNAMIC,
1638+ BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
1639+ CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,
1640+ MiscFlags: D3D11_RESOURCE_MISC_BUFFER_STRUCTURED.0 as u32,
1641+ StructureByteStride: u32::try_from(element_size)
1642+ .context("structured buffer stride overflows u32")?,
1643+ };
1644+ let mut buffer = None;
1645+ unsafe { device.CreateBuffer(&desc, None, Some(&mut buffer)) }?;
1646+ Ok(buffer.unwrap())
1647+}
1648+
1649+#[inline]
1650+fn create_buffer_view(
1651+ device: &ID3D11Device,
1652+ buffer: &ID3D11Buffer,
1653+) -> Result<Option<ID3D11ShaderResourceView>> {
1654+ let mut view = None;
1655+ unsafe { device.CreateShaderResourceView(buffer, None, Some(&mut view)) }?;
1656+ Ok(view)
1657+}
1658+
1659+#[inline]
1660+fn update_buffer<T>(
1661+ device_context: &ID3D11DeviceContext,
1662+ buffer: &ID3D11Buffer,
1663+ data: &[T],
1664+) -> Result<()> {
1665+ unsafe {
1666+ let mut dest = std::mem::zeroed();
1667+ device_context.Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, Some(&mut dest))?;
1668+ std::ptr::copy_nonoverlapping(data.as_ptr(), dest.pData as _, data.len());
1669+ device_context.Unmap(buffer, 0);
1670+ }
1671+ Ok(())
1672+}
1673+
1674+#[inline]
1675+fn update_batch_start(
1676+ device_context: &ID3D11DeviceContext,
1677+ buffer: &ID3D11Buffer,
1678+ first_instance: u32,
1679+) -> Result<()> {
1680+ update_buffer(
1681+ device_context,
1682+ buffer,
1683+ &[BatchParams {
1684+ start_index: first_instance,
1685+ _padding: [0; 3],
1686+ }],
1687+ )
1688+}
1689+
1690+#[inline]
1691+fn set_pipeline_state(
1692+ device_context: &ID3D11DeviceContext,
1693+ buffer_view: &[Option<ID3D11ShaderResourceView>],
1694+ topology: D3D_PRIMITIVE_TOPOLOGY,
1695+ vertex_shader: &ID3D11VertexShader,
1696+ fragment_shader: &ID3D11PixelShader,
1697+ blend_state: &ID3D11BlendState,
1698+ depth_stencil_state: &ID3D11DepthStencilState,
1699+) {
1700+ unsafe {
1701+ device_context.VSSetShaderResources(1, Some(buffer_view));
1702+ device_context.PSSetShaderResources(1, Some(buffer_view));
1703+ device_context.IASetPrimitiveTopology(topology);
1704+ device_context.VSSetShader(vertex_shader, None);
1705+ device_context.PSSetShader(fragment_shader, None);
1706+ device_context.OMSetBlendState(blend_state, None, 0xFFFFFFFF);
1707+ device_context.OMSetDepthStencilState(depth_stencil_state, 0);
1708+ }
1709+}
1710+
1711+#[cfg(debug_assertions)]
1712+fn report_live_objects(device: &ID3D11Device) -> Result<()> {
1713+ let debug_device: ID3D11Debug = device.cast()?;
1714+ unsafe {
1715+ debug_device.ReportLiveDeviceObjects(D3D11_RLDO_DETAIL)?;
1716+ }
1717+ Ok(())
1718+}
1719+
1720+const BUFFER_COUNT: usize = 3;
1721+
1722+pub(crate) mod shader_resources {
1723+ use anyhow::Result;
1724+
1725+ #[cfg(debug_assertions)]
1726+ use windows::{
1727+ Win32::Graphics::Direct3D::{
1728+ Fxc::{D3DCOMPILE_DEBUG, D3DCOMPILE_SKIP_OPTIMIZATION, D3DCompileFromFile},
1729+ ID3DBlob,
1730+ },
1731+ core::{HSTRING, PCSTR},
1732+ };
1733+
1734+ #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1735+ pub(crate) enum ShaderModule {
1736+ Quad,
1737+ OpaqueQuad,
1738+ Shadow,
1739+ Underline,
1740+ PathTile,
1741+ MonochromeSprite,
1742+ SubpixelSprite,
1743+ PolychromeSprite,
1744+ }
1745+
1746+ #[derive(Copy, Clone, Debug, Eq, PartialEq)]
1747+ pub(crate) enum ShaderTarget {
1748+ Vertex,
1749+ Fragment,
1750+ }
1751+
1752+ pub(crate) struct RawShaderBytes<'t> {
1753+ inner: &'t [u8],
1754+
1755+ #[cfg(debug_assertions)]
1756+ _blob: ID3DBlob,
1757+ }
1758+
1759+ impl<'t> RawShaderBytes<'t> {
1760+ pub(crate) fn new(module: ShaderModule, target: ShaderTarget) -> Result<Self> {
1761+ #[cfg(not(debug_assertions))]
1762+ {
1763+ Ok(Self::from_bytes(module, target))
1764+ }
1765+ #[cfg(debug_assertions)]
1766+ {
1767+ let blob = build_shader_blob(module, target)?;
1768+ let inner = unsafe {
1769+ std::slice::from_raw_parts(
1770+ blob.GetBufferPointer() as *const u8,
1771+ blob.GetBufferSize(),
1772+ )
1773+ };
1774+ Ok(Self { inner, _blob: blob })
1775+ }
1776+ }
1777+
1778+ pub(crate) fn as_bytes(&'t self) -> &'t [u8] {
1779+ self.inner
1780+ }
1781+
1782+ #[cfg(not(debug_assertions))]
1783+ fn from_bytes(module: ShaderModule, target: ShaderTarget) -> Self {
1784+ let bytes = match module {
1785+ ShaderModule::Quad => match target {
1786+ ShaderTarget::Vertex => QUAD_VERTEX_BYTES,
1787+ ShaderTarget::Fragment => QUAD_FRAGMENT_BYTES,
1788+ },
1789+ ShaderModule::OpaqueQuad => match target {
1790+ ShaderTarget::Vertex => OPAQUE_QUAD_VERTEX_BYTES,
1791+ ShaderTarget::Fragment => OPAQUE_QUAD_FRAGMENT_BYTES,
1792+ },
1793+ ShaderModule::Shadow => match target {
1794+ ShaderTarget::Vertex => SHADOW_VERTEX_BYTES,
1795+ ShaderTarget::Fragment => SHADOW_FRAGMENT_BYTES,
1796+ },
1797+ ShaderModule::Underline => match target {
1798+ ShaderTarget::Vertex => UNDERLINE_VERTEX_BYTES,
1799+ ShaderTarget::Fragment => UNDERLINE_FRAGMENT_BYTES,
1800+ },
1801+ ShaderModule::PathTile => match target {
1802+ ShaderTarget::Vertex => PATH_TILE_VERTEX_BYTES,
1803+ ShaderTarget::Fragment => PATH_TILE_FRAGMENT_BYTES,
1804+ },
1805+ ShaderModule::MonochromeSprite => match target {
1806+ ShaderTarget::Vertex => MONOCHROME_SPRITE_VERTEX_BYTES,
1807+ ShaderTarget::Fragment => MONOCHROME_SPRITE_FRAGMENT_BYTES,
1808+ },
1809+ ShaderModule::SubpixelSprite => match target {
1810+ ShaderTarget::Vertex => SUBPIXEL_SPRITE_VERTEX_BYTES,
1811+ ShaderTarget::Fragment => SUBPIXEL_SPRITE_FRAGMENT_BYTES,
1812+ },
1813+ ShaderModule::PolychromeSprite => match target {
1814+ ShaderTarget::Vertex => POLYCHROME_SPRITE_VERTEX_BYTES,
1815+ ShaderTarget::Fragment => POLYCHROME_SPRITE_FRAGMENT_BYTES,
1816+ },
1817+ };
1818+ Self { inner: bytes }
1819+ }
1820+ }
1821+
1822+ #[cfg(debug_assertions)]
1823+ pub(super) fn build_shader_blob(entry: ShaderModule, target: ShaderTarget) -> Result<ID3DBlob> {
1824+ unsafe {
1825+ use windows::Win32::Graphics::{
1826+ Direct3D::ID3DInclude, Hlsl::D3D_COMPILE_STANDARD_FILE_INCLUDE,
1827+ };
1828+
1829+ let entry = format!(
1830+ "{}_{}\0",
1831+ entry.as_str(),
1832+ match target {
1833+ ShaderTarget::Vertex => "vertex",
1834+ ShaderTarget::Fragment => "fragment",
1835+ }
1836+ );
1837+ let target = match target {
1838+ ShaderTarget::Vertex => "vs_4_1\0",
1839+ ShaderTarget::Fragment => "ps_4_1\0",
1840+ };
1841+
1842+ let mut compile_blob = None;
1843+ let mut error_blob = None;
1844+ let shader_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1845+ .join("src/shaders.hlsl")
1846+ .canonicalize()?;
1847+
1848+ let entry_point = PCSTR::from_raw(entry.as_ptr());
1849+ let target_cstr = PCSTR::from_raw(target.as_ptr());
1850+
1851+ // really dirty trick because winapi bindings are unhappy otherwise
1852+ let include_handler = &std::mem::transmute::<usize, ID3DInclude>(
1853+ D3D_COMPILE_STANDARD_FILE_INCLUDE as usize,
1854+ );
1855+
1856+ let ret = D3DCompileFromFile(
1857+ &HSTRING::from(shader_path.to_str().unwrap()),
1858+ None,
1859+ include_handler,
1860+ entry_point,
1861+ target_cstr,
1862+ D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,
1863+ 0,
1864+ &mut compile_blob,
1865+ Some(&mut error_blob),
1866+ );
1867+ if ret.is_err() {
1868+ let Some(error_blob) = error_blob else {
1869+ return Err(anyhow::anyhow!("{ret:?}"));
1870+ };
1871+
1872+ let error_string =
1873+ std::ffi::CStr::from_ptr(error_blob.GetBufferPointer() as *const i8)
1874+ .to_string_lossy();
1875+ log::error!("Shader compile error: {}", error_string);
1876+ return Err(anyhow::anyhow!("Compile error: {}", error_string));
1877+ }
1878+ Ok(compile_blob.unwrap())
1879+ }
1880+ }
1881+
1882+ #[cfg(not(debug_assertions))]
1883+ include!(concat!(env!("OUT_DIR"), "/shaders_bytes.rs"));
1884+
1885+ #[cfg(debug_assertions)]
1886+ impl ShaderModule {
1887+ pub fn as_str(self) -> &'static str {
1888+ match self {
1889+ ShaderModule::Quad => "quad",
1890+ ShaderModule::OpaqueQuad => "opaque_quad",
1891+ ShaderModule::Shadow => "shadow",
1892+ ShaderModule::Underline => "underline",
1893+ ShaderModule::PathTile => "path_tile",
1894+ ShaderModule::MonochromeSprite => "monochrome_sprite",
1895+ ShaderModule::SubpixelSprite => "subpixel_sprite",
1896+ ShaderModule::PolychromeSprite => "polychrome_sprite",
1897+ }
1898+ }
1899+ }
1900+}
1901+
1902+mod nvidia {
1903+ use std::{
1904+ ffi::CStr,
1905+ os::raw::{c_char, c_int, c_uint},
1906+ };
1907+
1908+ use anyhow::Result;
1909+ use windows::{Win32::System::LibraryLoader::GetProcAddress, core::s};
1910+
1911+ use crate::with_dll_library;
1912+
1913+ // https://github.com/NVIDIA/nvapi/blob/7cb76fce2f52de818b3da497af646af1ec16ce27/nvapi_lite_common.h#L180
1914+ const NVAPI_SHORT_STRING_MAX: usize = 64;
1915+
1916+ // https://github.com/NVIDIA/nvapi/blob/7cb76fce2f52de818b3da497af646af1ec16ce27/nvapi_lite_common.h#L235
1917+ #[allow(non_camel_case_types)]
1918+ type NvAPI_ShortString = [c_char; NVAPI_SHORT_STRING_MAX];
1919+
1920+ // https://github.com/NVIDIA/nvapi/blob/7cb76fce2f52de818b3da497af646af1ec16ce27/nvapi_lite_common.h#L447
1921+ #[allow(non_camel_case_types)]
1922+ type NvAPI_SYS_GetDriverAndBranchVersion_t = unsafe extern "C" fn(
1923+ driver_version: *mut c_uint,
1924+ build_branch_string: *mut NvAPI_ShortString,
1925+ ) -> c_int;
1926+
1927+ pub(super) fn get_driver_version() -> Result<String> {
1928+ #[cfg(target_pointer_width = "64")]
1929+ let nvidia_dll_name = s!("nvapi64.dll");
1930+ #[cfg(target_pointer_width = "32")]
1931+ let nvidia_dll_name = s!("nvapi.dll");
1932+
1933+ with_dll_library(nvidia_dll_name, |nvidia_dll| unsafe {
1934+ let nvapi_query_addr = GetProcAddress(nvidia_dll, s!("nvapi_QueryInterface"))
1935+ .ok_or_else(|| anyhow::anyhow!("Failed to get nvapi_QueryInterface address"))?;
1936+ let nvapi_query: extern "C" fn(u32) -> *mut () = std::mem::transmute(nvapi_query_addr);
1937+
1938+ // https://github.com/NVIDIA/nvapi/blob/7cb76fce2f52de818b3da497af646af1ec16ce27/nvapi_interface.h#L41
1939+ let nvapi_get_driver_version_ptr = nvapi_query(0x2926aaad);
1940+ if nvapi_get_driver_version_ptr.is_null() {
1941+ anyhow::bail!("Failed to get NVIDIA driver version function pointer");
1942+ }
1943+ let nvapi_get_driver_version: NvAPI_SYS_GetDriverAndBranchVersion_t =
1944+ std::mem::transmute(nvapi_get_driver_version_ptr);
1945+
1946+ let mut driver_version: c_uint = 0;
1947+ let mut build_branch_string: NvAPI_ShortString = [0; NVAPI_SHORT_STRING_MAX];
1948+ let result = nvapi_get_driver_version(
1949+ &mut driver_version as *mut c_uint,
1950+ &mut build_branch_string as *mut NvAPI_ShortString,
1951+ );
1952+
1953+ if result != 0 {
1954+ anyhow::bail!(
1955+ "Failed to get NVIDIA driver version, error code: {}",
1956+ result
1957+ );
1958+ }
1959+ let major = driver_version / 100;
1960+ let minor = driver_version % 100;
1961+ let branch_string = CStr::from_ptr(build_branch_string.as_ptr());
1962+ Ok(format!(
1963+ "{}.{} {}",
1964+ major,
1965+ minor,
1966+ branch_string.to_string_lossy()
1967+ ))
1968+ })
1969+ }
1970+}
1971+
1972+mod amd {
1973+ use std::os::raw::{c_char, c_int, c_void};
1974+
1975+ use anyhow::Result;
1976+ use windows::{Win32::System::LibraryLoader::GetProcAddress, core::s};
1977+
1978+ use crate::with_dll_library;
1979+
1980+ // https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK/blob/5d8812d703d0335741b6f7ffc37838eeb8b967f7/ags_lib/inc/amd_ags.h#L145
1981+ const AGS_CURRENT_VERSION: i32 = (6 << 22) | (3 << 12);
1982+
1983+ // https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK/blob/5d8812d703d0335741b6f7ffc37838eeb8b967f7/ags_lib/inc/amd_ags.h#L204
1984+ // This is an opaque type, using struct to represent it properly for FFI
1985+ #[repr(C)]
1986+ struct AGSContext {
1987+ _private: [u8; 0],
1988+ }
1989+
1990+ #[repr(C)]
1991+ pub struct AGSGPUInfo {
1992+ pub driver_version: *const c_char,
1993+ pub radeon_software_version: *const c_char,
1994+ pub num_devices: c_int,
1995+ pub devices: *mut c_void,
1996+ }
1997+
1998+ // https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK/blob/5d8812d703d0335741b6f7ffc37838eeb8b967f7/ags_lib/inc/amd_ags.h#L429
1999+ #[allow(non_camel_case_types)]
2000+ type agsInitialize_t = unsafe extern "C" fn(
vendor/gpui-pre-windows/src/dispatcher.rsadded+191 -0
@@ -0,0 +1,191 @@
1+use std::{
2+ ffi::c_void,
3+ ptr::NonNull,
4+ sync::atomic::{AtomicBool, Ordering},
5+ thread::{ThreadId, current},
6+ time::Duration,
7+};
8+
9+use anyhow::Context;
10+use gpui_util::ResultExt;
11+use windows::Win32::{
12+ Foundation::{FILETIME, LPARAM, WPARAM},
13+ Media::{timeBeginPeriod, timeEndPeriod},
14+ System::Threading::{
15+ CloseThreadpoolTimer, CreateThreadpoolTimer, GetCurrentThread, PTP_CALLBACK_INSTANCE,
16+ PTP_TIMER, SetThreadPriority, SetThreadpoolTimer, THREAD_PRIORITY_TIME_CRITICAL,
17+ TP_CALLBACK_ENVIRON_V3, TP_CALLBACK_PRIORITY, TP_CALLBACK_PRIORITY_HIGH,
18+ TP_CALLBACK_PRIORITY_LOW, TP_CALLBACK_PRIORITY_NORMAL, TrySubmitThreadpoolCallback,
19+ },
20+ UI::WindowsAndMessaging::PostMessageW,
21+};
22+
23+use crate::{HWND, SafeHwnd, WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD};
24+use gpui::{
25+ PlatformDispatcher, Priority, PriorityQueueSender, RunnableVariant, TimerResolutionGuard,
26+};
27+
28+pub(crate) struct WindowsDispatcher {
29+ pub(crate) wake_posted: AtomicBool,
30+ main_sender: PriorityQueueSender<RunnableVariant>,
31+ main_thread_id: ThreadId,
32+ pub(crate) platform_window_handle: SafeHwnd,
33+ validation_number: usize,
34+}
35+
36+impl WindowsDispatcher {
37+ pub(crate) fn new(
38+ main_sender: PriorityQueueSender<RunnableVariant>,
39+ platform_window_handle: HWND,
40+ validation_number: usize,
41+ ) -> Self {
42+ let main_thread_id = current().id();
43+ let platform_window_handle = platform_window_handle.into();
44+
45+ WindowsDispatcher {
46+ main_sender,
47+ main_thread_id,
48+ platform_window_handle,
49+ validation_number,
50+ wake_posted: AtomicBool::new(false),
51+ }
52+ }
53+
54+ fn dispatch_on_threadpool(&self, priority: TP_CALLBACK_PRIORITY, runnable: RunnableVariant) {
55+ let environ = TP_CALLBACK_ENVIRON_V3 {
56+ Version: 3,
57+ CallbackPriority: priority,
58+ Size: size_of::<TP_CALLBACK_ENVIRON_V3>() as u32,
59+ ..Default::default()
60+ };
61+
62+ // If the thread pool never runs our callback, the matching `from_raw` is never called, which leaks the runnable.
63+ // Dropping the scheduled runnable would cancel its task and make the next poll of any awaiter panic. Since we expect
64+ // the scenario to usually happen during shutdown, this leak is acceptable.
65+ let context = runnable.into_raw().as_ptr() as *mut c_void;
66+
67+ unsafe {
68+ TrySubmitThreadpoolCallback(Some(run_work_callback), Some(context), Some(&environ))
69+ .log_err();
70+ }
71+ }
72+
73+ fn dispatch_on_threadpool_after(&self, runnable: RunnableVariant, duration: Duration) {
74+ let context = runnable.into_raw().as_ptr() as *mut c_void;
75+
76+ unsafe {
77+ if let Ok(timer) = CreateThreadpoolTimer(Some(run_timer_callback), Some(context), None)
78+ {
79+ // Negative FILETIME expresses a relative delay in 100ns ticks
80+ let ticks = (duration.as_nanos() / 100).min(i64::MAX as u128) as i64;
81+ let due = (-ticks) as u64;
82+ let due_time = FILETIME {
83+ dwLowDateTime: due as u32,
84+ dwHighDateTime: (due >> 32) as u32,
85+ };
86+ SetThreadpoolTimer(timer, Some(&due_time), 0, None);
87+ }
88+ }
89+ }
90+
91+ #[inline(always)]
92+ pub(crate) fn execute_runnable(runnable: RunnableVariant) {
93+ let location = runnable.metadata().location;
94+ let spawned = runnable.metadata().spawned;
95+ gpui::profiler::update_running_task(spawned, location);
96+ runnable.run();
97+ gpui::profiler::save_task_timing();
98+ }
99+}
100+
101+impl PlatformDispatcher for WindowsDispatcher {
102+ fn is_main_thread(&self) -> bool {
103+ current().id() == self.main_thread_id
104+ }
105+
106+ fn dispatch(&self, runnable: RunnableVariant, priority: Priority) {
107+ let priority = match priority {
108+ Priority::RealtimeAudio => {
109+ panic!("RealtimeAudio priority should use spawn_realtime, not dispatch")
110+ }
111+ Priority::High => TP_CALLBACK_PRIORITY_HIGH,
112+ Priority::Medium => TP_CALLBACK_PRIORITY_NORMAL,
113+ Priority::Low => TP_CALLBACK_PRIORITY_LOW,
114+ };
115+ self.dispatch_on_threadpool(priority, runnable);
116+ }
117+
118+ fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority) {
119+ match self.main_sender.send(priority, runnable) {
120+ Ok(_) => {
121+ if !self.wake_posted.swap(true, Ordering::AcqRel) {
122+ unsafe {
123+ PostMessageW(
124+ Some(self.platform_window_handle.as_raw()),
125+ WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
126+ WPARAM(self.validation_number),
127+ LPARAM(0),
128+ )
129+ .log_err();
130+ }
131+ }
132+ }
133+ Err(runnable) => {
134+ // NOTE: Runnable may wrap a Future that is !Send.
135+ //
136+ // This is usually safe because we only poll it on the main thread.
137+ // However if the send fails, we know that:
138+ // 1. main_receiver has been dropped (which implies the app is shutting down)
139+ // 2. we are on a background thread.
140+ // It is not safe to drop something !Send on the wrong thread, and
141+ // the app will exit soon anyway, so we must forget the runnable.
142+ std::mem::forget(runnable);
143+ }
144+ }
145+ }
146+
147+ fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) {
148+ self.dispatch_on_threadpool_after(runnable, duration);
149+ }
150+
151+ fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) {
152+ std::thread::spawn(move || {
153+ // SAFETY: always safe to call
154+ let thread_handle = unsafe { GetCurrentThread() };
155+
156+ // SAFETY: thread_handle is a valid handle to the current thread
157+ unsafe { SetThreadPriority(thread_handle, THREAD_PRIORITY_TIME_CRITICAL) }
158+ .context("thread priority")
159+ .log_err();
160+
161+ f();
162+ });
163+ }
164+
165+ fn increase_timer_resolution(&self) -> TimerResolutionGuard {
166+ unsafe {
167+ timeBeginPeriod(1);
168+ }
169+ gpui_util::defer(Box::new(|| unsafe {
170+ timeEndPeriod(1);
171+ }))
172+ }
173+}
174+
175+unsafe extern "system" fn run_work_callback(
176+ _instance: PTP_CALLBACK_INSTANCE,
177+ context: *mut c_void,
178+) {
179+ let runnable = unsafe { RunnableVariant::from_raw(NonNull::new_unchecked(context as *mut ())) };
180+ WindowsDispatcher::execute_runnable(runnable);
181+}
182+
183+unsafe extern "system" fn run_timer_callback(
184+ _instance: PTP_CALLBACK_INSTANCE,
185+ context: *mut c_void,
186+ timer: PTP_TIMER,
187+) {
188+ let runnable = unsafe { RunnableVariant::from_raw(NonNull::new_unchecked(context as *mut ())) };
189+ WindowsDispatcher::execute_runnable(runnable);
190+ unsafe { CloseThreadpoolTimer(timer) };
191+}
vendor/gpui-pre-windows/src/display.rsadded+244 -0
@@ -0,0 +1,244 @@
1+use gpui_util::ResultExt;
2+use itertools::Itertools;
3+use smallvec::SmallVec;
4+use std::rc::Rc;
5+use uuid::Uuid;
6+use windows::{
7+ Win32::{
8+ Foundation::*,
9+ Graphics::Gdi::*,
10+ UI::{
11+ HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},
12+ WindowsAndMessaging::USER_DEFAULT_SCREEN_DPI,
13+ },
14+ },
15+ core::*,
16+};
17+
18+use crate::logical_point;
19+use gpui::{
20+ Bounds, DevicePixels, DisplayId, Pixels, PlatformDisplay, point, refresh_interval_from_hz, size,
21+};
22+
23+#[derive(Debug, Clone, Copy)]
24+pub(crate) struct WindowsDisplay {
25+ pub handle: HMONITOR,
26+ pub display_id: DisplayId,
27+ scale_factor: f32,
28+ bounds: Bounds<Pixels>,
29+ visible_bounds: Bounds<Pixels>,
30+ physical_bounds: Bounds<DevicePixels>,
31+ uuid: Uuid,
32+}
33+
34+// The `HMONITOR` is thread-safe.
35+unsafe impl Send for WindowsDisplay {}
36+unsafe impl Sync for WindowsDisplay {}
37+
38+impl WindowsDisplay {
39+ pub(crate) fn new(display_id: DisplayId) -> Option<Self> {
40+ let handle = HMONITOR(u64::from(display_id) as _);
41+ let info = get_monitor_info(handle).log_err()?;
42+ let monitor_size = info.monitorInfo.rcMonitor;
43+ let work_area = info.monitorInfo.rcWork;
44+ let uuid = generate_uuid(&info.szDevice);
45+ let scale_factor = get_scale_factor_for_monitor(handle).log_err()?;
46+ let physical_size = size(
47+ (monitor_size.right - monitor_size.left).into(),
48+ (monitor_size.bottom - monitor_size.top).into(),
49+ );
50+
51+ Some(WindowsDisplay {
52+ handle,
53+ display_id,
54+ scale_factor,
55+ bounds: Bounds {
56+ origin: logical_point(
57+ monitor_size.left as f32,
58+ monitor_size.top as f32,
59+ scale_factor,
60+ ),
61+ size: physical_size.to_pixels(scale_factor),
62+ },
63+ visible_bounds: Bounds {
64+ origin: logical_point(work_area.left as f32, work_area.top as f32, scale_factor),
65+ size: size(
66+ (work_area.right - work_area.left) as f32 / scale_factor,
67+ (work_area.bottom - work_area.top) as f32 / scale_factor,
68+ )
69+ .map(gpui::px),
70+ },
71+ physical_bounds: Bounds {
72+ origin: point(monitor_size.left.into(), monitor_size.top.into()),
73+ size: physical_size,
74+ },
75+ uuid,
76+ })
77+ }
78+
79+ pub(crate) fn display_id_for_monitor(monitor: HMONITOR) -> DisplayId {
80+ DisplayId::new(monitor.0 as u64)
81+ }
82+
83+ pub fn primary_monitor() -> Option<Self> {
84+ // https://devblogs.microsoft.com/oldnewthing/20070809-00/?p=25643
85+ const POINT_ZERO: POINT = POINT { x: 0, y: 0 };
86+ let monitor = unsafe { MonitorFromPoint(POINT_ZERO, MONITOR_DEFAULTTOPRIMARY) };
87+ if monitor.is_invalid() {
88+ log::error!(
89+ "can not find the primary monitor: {}",
90+ std::io::Error::last_os_error()
91+ );
92+ return None;
93+ }
94+ WindowsDisplay::new(Self::display_id_for_monitor(monitor))
95+ }
96+
97+ /// The DPI scale factor of this monitor, independent of whatever monitor
98+ /// a not-yet-positioned window currently happens to be on.
99+ pub(crate) fn scale_factor(&self) -> f32 {
100+ self.scale_factor
101+ }
102+
103+ /// Check if the center point of given bounds is inside this monitor
104+ pub fn check_given_bounds(&self, bounds: Bounds<Pixels>) -> bool {
105+ let center = bounds.center();
106+ let center = POINT {
107+ x: (center.x.as_f32() * self.scale_factor) as i32,
108+ y: (center.y.as_f32() * self.scale_factor) as i32,
109+ };
110+ let monitor = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) };
111+ if monitor.is_invalid() {
112+ false
113+ } else {
114+ let Some(display) = WindowsDisplay::new(Self::display_id_for_monitor(monitor)) else {
115+ return false;
116+ };
117+ display.uuid == self.uuid
118+ }
119+ }
120+
121+ pub fn displays() -> Vec<Rc<dyn PlatformDisplay>> {
122+ available_monitors()
123+ .into_iter()
124+ .filter_map(|handle| {
125+ Some(
126+ Rc::new(WindowsDisplay::new(Self::display_id_for_monitor(handle))?)
127+ as Rc<dyn PlatformDisplay>,
128+ )
129+ })
130+ .collect()
131+ }
132+
133+ pub fn physical_bounds(&self) -> Bounds<DevicePixels> {
134+ self.physical_bounds
135+ }
136+}
137+
138+impl PlatformDisplay for WindowsDisplay {
139+ fn id(&self) -> DisplayId {
140+ self.display_id
141+ }
142+
143+ fn uuid(&self) -> anyhow::Result<Uuid> {
144+ Ok(self.uuid)
145+ }
146+
147+ fn bounds(&self) -> Bounds<Pixels> {
148+ self.bounds
149+ }
150+
151+ fn visible_bounds(&self) -> Bounds<Pixels> {
152+ self.visible_bounds
153+ }
154+
155+ fn refresh_interval(&self) -> Option<std::time::Duration> {
156+ get_monitor_info(self.handle)
157+ .log_err()
158+ .and_then(|info| refresh_interval_for_device(&info.szDevice))
159+ }
160+}
161+
162+/// The refresh rate of the monitor's current mode. With variable refresh
163+/// rate, the mode's rate is the maximum.
164+fn refresh_interval_for_device(device_name: &[u16; 32]) -> Option<std::time::Duration> {
165+ let mut mode = DEVMODEW {
166+ dmSize: std::mem::size_of::<DEVMODEW>() as u16,
167+ ..Default::default()
168+ };
169+ // SAFETY: `device_name` is the null-terminated `szDevice` from
170+ // `GetMonitorInfoW`, and `mode.dmSize` is initialized.
171+ let found = unsafe {
172+ EnumDisplaySettingsW(
173+ PCWSTR(device_name.as_ptr()),
174+ ENUM_CURRENT_SETTINGS,
175+ &mut mode,
176+ )
177+ };
178+ if !found.as_bool() {
179+ return None;
180+ }
181+ // 0 and 1 mean the hardware's default rate, which isn't reported.
182+ if mode.dmDisplayFrequency <= 1 {
183+ return None;
184+ }
185+ refresh_interval_from_hz(f64::from(mode.dmDisplayFrequency))
186+}
187+
188+fn available_monitors() -> SmallVec<[HMONITOR; 4]> {
189+ let mut monitors: SmallVec<[HMONITOR; 4]> = SmallVec::new();
190+ unsafe {
191+ EnumDisplayMonitors(
192+ None,
193+ None,
194+ Some(monitor_enum_proc),
195+ LPARAM(&mut monitors as *mut _ as _),
196+ )
197+ .ok()
198+ .log_err();
199+ }
200+ monitors
201+}
202+
203+unsafe extern "system" fn monitor_enum_proc(
204+ hmonitor: HMONITOR,
205+ _hdc: HDC,
206+ _place: *mut RECT,
207+ data: LPARAM,
208+) -> BOOL {
209+ let monitors = data.0 as *mut SmallVec<[HMONITOR; 4]>;
210+ unsafe { (*monitors).push(hmonitor) };
211+ BOOL(1)
212+}
213+
214+fn get_monitor_info(hmonitor: HMONITOR) -> anyhow::Result<MONITORINFOEXW> {
215+ let mut monitor_info: MONITORINFOEXW = unsafe { std::mem::zeroed() };
216+ monitor_info.monitorInfo.cbSize = std::mem::size_of::<MONITORINFOEXW>() as u32;
217+ let status = unsafe {
218+ GetMonitorInfoW(
219+ hmonitor,
220+ &mut monitor_info as *mut MONITORINFOEXW as *mut MONITORINFO,
221+ )
222+ };
223+ if status.as_bool() {
224+ Ok(monitor_info)
225+ } else {
226+ Err(anyhow::anyhow!(std::io::Error::last_os_error()))
227+ }
228+}
229+
230+fn generate_uuid(device_name: &[u16]) -> Uuid {
231+ let name = device_name
232+ .iter()
233+ .flat_map(|&a| a.to_be_bytes())
234+ .collect_vec();
235+ Uuid::new_v5(&Uuid::NAMESPACE_DNS, &name)
236+}
237+
238+fn get_scale_factor_for_monitor(monitor: HMONITOR) -> Result<f32> {
239+ let mut dpi_x = 0;
240+ let mut dpi_y = 0;
241+ unsafe { GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) }?;
242+ assert_eq!(dpi_x, dpi_y);
243+ Ok(dpi_x as f32 / USER_DEFAULT_SCREEN_DPI as f32)
244+}
vendor/gpui-pre-windows/src/events.rsadded+1844 -0
@@ -0,0 +1,1844 @@
1+use std::{cell::Cell, rc::Rc, sync::atomic::Ordering};
2+
3+use anyhow::Context as _;
4+use gpui_util::ResultExt;
5+use windows::{
6+ Win32::{
7+ Foundation::*,
8+ Graphics::Gdi::*,
9+ System::SystemServices::*,
10+ UI::{
11+ Controls::*,
12+ HiDpi::*,
13+ Input::{Ime::*, KeyboardAndMouse::*},
14+ WindowsAndMessaging::*,
15+ },
16+ },
17+ core::PCWSTR,
18+};
19+
20+use crate::*;
21+use gpui::*;
22+
23+pub(crate) const WM_GPUI_CURSOR_STYLE_CHANGED: u32 = WM_USER + 1;
24+pub(crate) const WM_GPUI_CLOSE_ONE_WINDOW: u32 = WM_USER + 2;
25+pub(crate) const WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD: u32 = WM_USER + 3;
26+pub(crate) const WM_GPUI_DOCK_MENU_ACTION: u32 = WM_USER + 4;
27+pub(crate) const WM_GPUI_FORCE_UPDATE_WINDOW: u32 = WM_USER + 5;
28+pub(crate) const WM_GPUI_KEYBOARD_LAYOUT_CHANGED: u32 = WM_USER + 6;
29+pub(crate) const WM_GPUI_GPU_DEVICE_LOST: u32 = WM_USER + 7;
30+pub(crate) const WM_GPUI_DISPLAYS_CHANGED: u32 = WM_USER + 10;
31+
32+const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
33+
34+/// Coordinates window draws on the UI thread. Owned by the platform and
35+/// shared with every window (like `WindowsPlatformState::cursor_visible`),
36+/// because the coordination is inherently cross-window: while window A is
37+/// drawing, a re-entrant paint request for window B must be deferred.
38+pub(crate) struct DrawCoordinator {
39+ /// Whether some window is currently inside `draw_window`. Win32 can
40+ /// re-enter the window procedure while a draw is in progress (e.g.
41+ /// cross-thread `SendMessage` dispatch during message pumping, or modal
42+ /// message loops entered by COM calls), and drawing re-entrantly would
43+ /// nest GPUI draws. Nested draws are wasted work whose output is
44+ /// immediately redrawn, so we defer them instead.
45+ drawing: Cell<bool>,
46+}
47+
48+impl DrawCoordinator {
49+ pub(crate) fn new() -> Self {
50+ Self {
51+ drawing: Cell::new(false),
52+ }
53+ }
54+
55+ fn try_begin_draw(&self) -> Option<DrawWindowGuard<'_>> {
56+ // This only covers the `draw_window` span (which extends past the GPUI
57+ // draw, through presentation and IME updates). Requests that arrive
58+ // re-entrantly during GPUI-initiated draws (e.g. key dispatch or
59+ // opening a window draws synchronously) are deferred by GPUI's
60+ // `on_request_frame` callback itself, which no-ops in that case.
61+ if self.drawing.get() {
62+ None
63+ } else {
64+ self.drawing.set(true);
65+ Some(DrawWindowGuard { coordinator: self })
66+ }
67+ }
68+}
69+
70+struct DrawWindowGuard<'a> {
71+ coordinator: &'a DrawCoordinator,
72+}
73+
74+impl Drop for DrawWindowGuard<'_> {
75+ fn drop(&mut self) {
76+ self.coordinator.drawing.set(false);
77+ }
78+}
79+
80+impl WindowsWindowInner {
81+ pub(crate) fn handle_msg(
82+ self: &Rc<Self>,
83+ handle: HWND,
84+ msg: u32,
85+ wparam: WPARAM,
86+ lparam: LPARAM,
87+ ) -> LRESULT {
88+ let handled = match msg {
89+ // `DefWindowProc` answers `MA_NOACTIVATE` for a left click on `HTCAPTION`.
90+ // The activation is only triggered when `DefWindowProc` handles the following `WM_NCLBUTTONDOWN`.
91+ // The GPUI event is dispatched in between, so a click handler runs while `active_window` is still
92+ // whichever window was active before the click. If that handler consumes the
93+ // press, `DefWindowProc` never sees it, so the window is never activated at all.
94+ // So, let's eagerly activate the window.
95+ WM_MOUSEACTIVATE => Some(MA_ACTIVATE as isize),
96+ WM_ACTIVATE => self.handle_activate_msg(wparam),
97+ WM_CREATE => self.handle_create_msg(handle),
98+ WM_MOVE => self.handle_move_msg(handle, lparam),
99+ WM_SIZE => self.handle_size_msg(wparam, lparam),
100+ WM_GETMINMAXINFO => self.handle_get_min_max_info_msg(lparam),
101+ WM_ENTERSIZEMOVE | WM_ENTERMENULOOP => self.handle_size_move_loop(handle),
102+ WM_EXITSIZEMOVE | WM_EXITMENULOOP => self.handle_size_move_loop_exit(handle),
103+ WM_TIMER => self.handle_timer_msg(handle, wparam),
104+ WM_NCCALCSIZE => self.handle_calc_client_size(handle, wparam, lparam),
105+ WM_DPICHANGED => self.handle_dpi_changed_msg(handle, wparam, lparam),
106+ WM_DISPLAYCHANGE => self.handle_display_change_msg(handle),
107+ WM_NCHITTEST => self.handle_hit_test_msg(handle, lparam),
108+ WM_PAINT => self.handle_paint_msg(handle),
109+ WM_CLOSE => self.handle_close_msg(),
110+ WM_DESTROY => self.handle_destroy_msg(handle),
111+ WM_MOUSEMOVE => self.handle_mouse_move_msg(handle, lparam, wparam),
112+ WM_MOUSELEAVE | WM_NCMOUSELEAVE => self.handle_mouse_leave_msg(),
113+ WM_NCMOUSEMOVE => self.handle_nc_mouse_move_msg(handle, lparam),
114+ // Treat double click as a second single click, since we track the double clicks ourselves.
115+ // If you don't interact with any elements, this will fall through to the windows default
116+ // behavior of toggling whether the window is maximized.
117+ WM_NCLBUTTONDBLCLK | WM_NCLBUTTONDOWN => {
118+ self.handle_nc_mouse_down_msg(handle, MouseButton::Left, wparam, lparam)
119+ }
120+ WM_NCRBUTTONDOWN => {
121+ self.handle_nc_mouse_down_msg(handle, MouseButton::Right, wparam, lparam)
122+ }
123+ WM_NCMBUTTONDOWN => {
124+ self.handle_nc_mouse_down_msg(handle, MouseButton::Middle, wparam, lparam)
125+ }
126+ WM_NCLBUTTONUP => {
127+ self.handle_nc_mouse_up_msg(handle, MouseButton::Left, wparam, lparam)
128+ }
129+ WM_NCRBUTTONUP => {
130+ self.handle_nc_mouse_up_msg(handle, MouseButton::Right, wparam, lparam)
131+ }
132+ WM_NCMBUTTONUP => {
133+ self.handle_nc_mouse_up_msg(handle, MouseButton::Middle, wparam, lparam)
134+ }
135+ WM_LBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Left, lparam),
136+ WM_RBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Right, lparam),
137+ WM_MBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Middle, lparam),
138+ WM_XBUTTONDOWN => {
139+ self.handle_xbutton_msg(handle, wparam, lparam, Self::handle_mouse_down_msg)
140+ }
141+ WM_LBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Left, lparam),
142+ WM_RBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Right, lparam),
143+ WM_MBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Middle, lparam),
144+ WM_XBUTTONUP => {
145+ self.handle_xbutton_msg(handle, wparam, lparam, Self::handle_mouse_up_msg)
146+ }
147+ WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),
148+ WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),
149+ WM_SYSKEYUP => self.handle_syskeyup_msg(wparam, lparam),
150+ WM_KEYUP => self.handle_keyup_msg(wparam, lparam),
151+ WM_CHAR => self.handle_char_msg(wparam),
152+ WM_IME_STARTCOMPOSITION => self.handle_ime_position(handle),
153+ WM_IME_COMPOSITION => self.handle_ime_composition(handle, lparam),
154+ WM_SETCURSOR => self.handle_set_cursor(handle, lparam),
155+ WM_SETTINGCHANGE => self.handle_system_settings_changed(handle, wparam, lparam),
156+ WM_INPUTLANGCHANGE => self.handle_input_language_changed(),
157+ WM_SHOWWINDOW => self.handle_window_visibility_changed(handle, wparam),
158+ DM_POINTERHITTEST => self.handle_dm_pointer_hit_test(wparam),
159+ WM_GETOBJECT => self.handle_wm_getobject(wparam, lparam),
160+ WM_GPUI_CURSOR_STYLE_CHANGED
161+ | WM_GPUI_FORCE_UPDATE_WINDOW
162+ | WM_GPUI_GPU_DEVICE_LOST => self.handle_gpui_events(handle, msg, wparam, lparam),
163+ _ => None,
164+ };
165+ if let Some(n) = handled {
166+ LRESULT(n)
167+ } else {
168+ unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
169+ }
170+ }
171+
172+ fn handle_move_msg(self: &Rc<Self>, handle: HWND, lparam: LPARAM) -> Option<isize> {
173+ let origin = logical_point(
174+ lparam.signed_loword() as f32,
175+ lparam.signed_hiword() as f32,
176+ self.state.scale_factor.get(),
177+ );
178+ self.state.origin.set(origin);
179+ let size = self.state.logical_size.get();
180+ let center_x = origin.x.as_f32() + size.width.as_f32() / 2.;
181+ let center_y = origin.y.as_f32() + size.height.as_f32() / 2.;
182+ let monitor_bounds = self.state.display.get().bounds();
183+ if center_x < monitor_bounds.left().as_f32()
184+ || center_x > monitor_bounds.right().as_f32()
185+ || center_y < monitor_bounds.top().as_f32()
186+ || center_y > monitor_bounds.bottom().as_f32()
187+ {
188+ // center of the window may have moved to another monitor
189+ let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
190+ // minimize the window can trigger this event too, in this case,
191+ // monitor is invalid, we do nothing.
192+ if !monitor.is_invalid() && self.state.display.get().handle != monitor {
193+ // we will get the same monitor if we only have one
194+ self.set_display(WindowsDisplay::new(
195+ WindowsDisplay::display_id_for_monitor(monitor),
196+ )?);
197+ }
198+ }
199+ if let Some(mut callback) = self.state.callbacks.moved.take() {
200+ callback();
201+ self.state.callbacks.moved.set(Some(callback));
202+ }
203+ Some(0)
204+ }
205+
206+ fn handle_get_min_max_info_msg(&self, lparam: LPARAM) -> Option<isize> {
207+ let min_size = self.state.min_size?;
208+ let scale_factor = self.state.scale_factor.get();
209+ let boarder_offset = &self.state.border_offset;
210+
211+ unsafe {
212+ let minmax_info = &mut *(lparam.0 as *mut MINMAXINFO);
213+ minmax_info.ptMinTrackSize.x = min_size.width.scale(scale_factor).as_f32() as i32
214+ + boarder_offset.width_offset.get();
215+ minmax_info.ptMinTrackSize.y = min_size.height.scale(scale_factor).as_f32() as i32
216+ + boarder_offset.height_offset.get();
217+ }
218+ Some(0)
219+ }
220+
221+ fn handle_size_msg(self: &Rc<Self>, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
222+ // Minimizing and restoring both arrive as `WM_SIZE`; the deferred report
223+ // reads `IsIconic` at delivery, so one call covers both directions.
224+ self.report_visibility();
225+
226+ // Don't resize the renderer when the window is minimized, but record that it was minimized so
227+ // that on restore the swap chain can be recreated via `update_drawable_size_even_if_unchanged`.
228+ if wparam.0 == SIZE_MINIMIZED as usize {
229+ self.state
230+ .restore_from_minimized
231+ .set(self.state.callbacks.request_frame.take());
232+ return Some(0);
233+ }
234+
235+ let width = lparam.loword().max(1) as i32;
236+ let height = lparam.hiword().max(1) as i32;
237+ let new_size = size(DevicePixels(width), DevicePixels(height));
238+
239+ let scale_factor = self.state.scale_factor.get();
240+ let mut should_resize_renderer = false;
241+ if let Some(restore_from_minimized) = self.state.restore_from_minimized.take() {
242+ self.state
243+ .callbacks
244+ .request_frame
245+ .set(Some(restore_from_minimized));
246+ } else {
247+ should_resize_renderer = true;
248+ }
249+
250+ self.handle_size_change(new_size, scale_factor, should_resize_renderer);
251+ Some(0)
252+ }
253+
254+ fn handle_size_change(
255+ &self,
256+ device_size: Size<DevicePixels>,
257+ scale_factor: f32,
258+ should_resize_renderer: bool,
259+ ) {
260+ let new_logical_size = device_size.to_pixels(scale_factor);
261+
262+ self.state.logical_size.set(new_logical_size);
263+ if should_resize_renderer
264+ && let Err(e) = self.state.renderer.borrow_mut().resize(device_size)
265+ {
266+ log::error!("Failed to resize renderer, invalidating devices: {}", e);
267+ self.state
268+ .invalidate_devices
269+ .store(true, std::sync::atomic::Ordering::Release);
270+ }
271+ if let Some(mut callback) = self.state.callbacks.resize.take() {
272+ callback(new_logical_size, scale_factor);
273+ self.state.callbacks.resize.set(Some(callback));
274+ }
275+ }
276+
277+ fn handle_size_move_loop(&self, handle: HWND) -> Option<isize> {
278+ unsafe {
279+ let ret = SetTimer(
280+ Some(handle),
281+ SIZE_MOVE_LOOP_TIMER_ID,
282+ USER_TIMER_MINIMUM,
283+ None,
284+ );
285+ if ret == 0 {
286+ log::error!(
287+ "unable to create timer: {}",
288+ std::io::Error::last_os_error()
289+ );
290+ }
291+ }
292+ None
293+ }
294+
295+ fn handle_size_move_loop_exit(&self, handle: HWND) -> Option<isize> {
296+ unsafe {
297+ KillTimer(Some(handle), SIZE_MOVE_LOOP_TIMER_ID).log_err();
298+ }
299+ None
300+ }
301+
302+ fn handle_timer_msg(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {
303+ if wparam.0 == SIZE_MOVE_LOOP_TIMER_ID {
304+ let mut runnables = self.main_receiver.clone().try_iter();
305+ while let Some(Ok(runnable)) = runnables.next() {
306+ WindowsDispatcher::execute_runnable(runnable);
307+ }
308+ self.handle_paint_msg(handle)
309+ } else {
310+ None
311+ }
312+ }
313+
314+ fn handle_paint_msg(&self, handle: HWND) -> Option<isize> {
315+ self.draw_window(handle, false)
316+ }
317+
318+ fn handle_close_msg(&self) -> Option<isize> {
319+ let mut callback = self.state.callbacks.should_close.take()?;
320+ let should_close = callback();
321+ self.state.callbacks.should_close.set(Some(callback));
322+ if should_close { None } else { Some(0) }
323+ }
324+
325+ fn handle_destroy_msg(&self, handle: HWND) -> Option<isize> {
326+ let callback = { self.state.callbacks.close.take() };
327+ // Re-enable parent window if this was a modal dialog
328+ if let Some(parent_hwnd) = self.parent_hwnd {
329+ unsafe {
330+ let _ = EnableWindow(parent_hwnd, true);
331+ let _ = SetForegroundWindow(parent_hwnd);
332+ }
333+ }
334+
335+ if let Some(callback) = callback {
336+ callback();
337+ }
338+ unsafe {
339+ PostMessageW(
340+ Some(self.platform_window_handle),
341+ WM_GPUI_CLOSE_ONE_WINDOW,
342+ WPARAM(self.validation_number),
343+ LPARAM(handle.0 as isize),
344+ )
345+ .log_err();
346+ }
347+ Some(0)
348+ }
349+
350+ fn handle_mouse_move_msg(&self, handle: HWND, lparam: LPARAM, wparam: WPARAM) -> Option<isize> {
351+ self.start_tracking_mouse(handle, TME_LEAVE);
352+ self.restore_cursor_after_hide();
353+
354+ let x = lparam.signed_loword() as f32;
355+ let y = lparam.signed_hiword() as f32;
356+ let scale_factor = self.state.scale_factor.get();
357+ let new_position = logical_point(x, y, scale_factor);
358+
359+ let pressed_button = match MODIFIERKEYS_FLAGS(wparam.loword() as u32) {
360+ flags if flags.contains(MK_LBUTTON) => Some(MouseButton::Left),
361+ flags if flags.contains(MK_RBUTTON) => Some(MouseButton::Right),
362+ flags if flags.contains(MK_MBUTTON) => Some(MouseButton::Middle),
363+ flags if flags.contains(MK_XBUTTON1) => {
364+ Some(MouseButton::Navigate(NavigationDirection::Back))
365+ }
366+ flags if flags.contains(MK_XBUTTON2) => {
367+ Some(MouseButton::Navigate(NavigationDirection::Forward))
368+ }
369+ _ => None,
370+ };
371+
372+ // Suppress synthetic WM_MOUSEMOVE events that Windows fires when a window
373+ // repaints under the cursor (e.g. command palette opening). These are not
374+ // real mouse movements and should not move the editor cursor or clobber
375+ // selections. A real move always has a different position OR a button held.
376+ if pressed_button.is_none() && new_position == self.state.mouse_position.get() {
377+ return Some(1);
378+ }
379+ self.state.mouse_position.set(new_position);
380+
381+ let Some(mut func) = self.state.callbacks.input.take() else {
382+ return Some(1);
383+ };
384+
385+ let input = PlatformInput::MouseMove(MouseMoveEvent {
386+ position: new_position,
387+ pressed_button,
388+ modifiers: current_modifiers(),
389+ });
390+ let handled = !func(input).propagate;
391+ self.state.callbacks.input.set(Some(func));
392+ if handled { Some(0) } else { Some(1) }
393+ }
394+
395+ fn handle_mouse_leave_msg(&self) -> Option<isize> {
396+ self.state.hovered.set(false);
397+ // The next window's `WM_SETCURSOR` picks its own cursor, so we just clear
398+ // the flag for tight `is_cursor_visible()` semantics.
399+ self.state.cursor_visible.store(true, Ordering::Relaxed);
400+ if let Some(mut callback) = self.state.callbacks.hovered_status_change.take() {
401+ callback(false);
402+ self.state
403+ .callbacks
404+ .hovered_status_change
405+ .set(Some(callback));
406+ }
407+
408+ Some(0)
409+ }
410+
411+ fn handle_syskeyup_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
412+ let input = handle_key_event(wparam, lparam, &self.state, |keystroke, _| {
413+ PlatformInput::KeyUp(KeyUpEvent { keystroke })
414+ })?;
415+ let mut func = self.state.callbacks.input.take()?;
416+
417+ func(input);
418+ self.state.callbacks.input.set(Some(func));
419+
420+ // Always return 0 to indicate that the message was handled, so we could properly handle `ModifiersChanged` event.
421+ Some(0)
422+ }
423+
424+ // It's a known bug that you can't trigger `ctrl-shift-0`. See:
425+ // https://superuser.com/questions/1455762/ctrl-shift-number-key-combination-has-stopped-working-for-a-few-numbers
426+ pub(crate) fn handle_keydown_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
427+ let Some(input) = handle_key_event(
428+ wparam,
429+ lparam,
430+ &self.state,
431+ |keystroke, prefer_character_input| {
432+ PlatformInput::KeyDown(KeyDownEvent {
433+ keystroke,
434+ is_held: lparam.0 & (0x1 << 30) > 0,
435+ prefer_character_input,
436+ })
437+ },
438+ ) else {
439+ return Some(1);
440+ };
441+
442+ let Some(mut func) = self.state.callbacks.input.take() else {
443+ return Some(1);
444+ };
445+
446+ let handled = !func(input).propagate;
447+
448+ self.state.callbacks.input.set(Some(func));
449+
450+ if handled { Some(0) } else { Some(1) }
451+ }
452+
453+ fn handle_keyup_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
454+ let Some(input) = handle_key_event(wparam, lparam, &self.state, |keystroke, _| {
455+ PlatformInput::KeyUp(KeyUpEvent { keystroke })
456+ }) else {
457+ return Some(1);
458+ };
459+
460+ let Some(mut func) = self.state.callbacks.input.take() else {
461+ return Some(1);
462+ };
463+
464+ let handled = !func(input).propagate;
465+ self.state.callbacks.input.set(Some(func));
466+
467+ if handled { Some(0) } else { Some(1) }
468+ }
469+
470+ fn handle_char_msg(&self, wparam: WPARAM) -> Option<isize> {
471+ let input = self.parse_char_message(wparam)?;
472+ self.with_input_handler(|input_handler| {
473+ input_handler.replace_text_in_range(None, &input);
474+ });
475+
476+ Some(0)
477+ }
478+
479+ fn handle_mouse_down_msg(
480+ &self,
481+ handle: HWND,
482+ button: MouseButton,
483+ lparam: LPARAM,
484+ ) -> Option<isize> {
485+ unsafe { SetCapture(handle) };
486+
487+ let Some(mut func) = self.state.callbacks.input.take() else {
488+ return Some(1);
489+ };
490+ let x = lparam.signed_loword();
491+ let y = lparam.signed_hiword();
492+ let physical_point = point(DevicePixels(x as i32), DevicePixels(y as i32));
493+ let click_count = self.state.click_state.update(button, physical_point);
494+ let scale_factor = self.state.scale_factor.get();
495+
496+ let input = PlatformInput::MouseDown(MouseDownEvent {
497+ button,
498+ position: logical_point(x as f32, y as f32, scale_factor),
499+ modifiers: current_modifiers(),
500+ click_count,
501+ first_mouse: false,
502+ });
503+ let handled = !func(input).propagate;
504+ self.state.callbacks.input.set(Some(func));
505+
506+ if handled { Some(0) } else { Some(1) }
507+ }
508+
509+ fn handle_mouse_up_msg(
510+ &self,
511+ _handle: HWND,
512+ button: MouseButton,
513+ lparam: LPARAM,
514+ ) -> Option<isize> {
515+ unsafe { ReleaseCapture().log_err() };
516+
517+ let Some(mut func) = self.state.callbacks.input.take() else {
518+ return Some(1);
519+ };
520+ let x = lparam.signed_loword() as f32;
521+ let y = lparam.signed_hiword() as f32;
522+ let click_count = self.state.click_state.current_count.get();
523+ let scale_factor = self.state.scale_factor.get();
524+
525+ let input = PlatformInput::MouseUp(MouseUpEvent {
526+ button,
527+ position: logical_point(x, y, scale_factor),
528+ modifiers: current_modifiers(),
529+ click_count,
530+ });
531+ let handled = !func(input).propagate;
532+ self.state.callbacks.input.set(Some(func));
533+
534+ if handled { Some(0) } else { Some(1) }
535+ }
536+
537+ fn handle_xbutton_msg(
538+ &self,
539+ handle: HWND,
540+ wparam: WPARAM,
541+ lparam: LPARAM,
542+ handler: impl Fn(&Self, HWND, MouseButton, LPARAM) -> Option<isize>,
543+ ) -> Option<isize> {
544+ let nav_dir = match wparam.hiword() {
545+ XBUTTON1 => NavigationDirection::Back,
546+ XBUTTON2 => NavigationDirection::Forward,
547+ _ => return Some(1),
548+ };
549+ handler(self, handle, MouseButton::Navigate(nav_dir), lparam)
550+ }
551+
552+ fn handle_mouse_wheel_msg(
553+ &self,
554+ handle: HWND,
555+ wparam: WPARAM,
556+ lparam: LPARAM,
557+ ) -> Option<isize> {
558+ let modifiers = current_modifiers();
559+
560+ let Some(mut func) = self.state.callbacks.input.take() else {
561+ return Some(1);
562+ };
563+ let scale_factor = self.state.scale_factor.get();
564+ let wheel_scroll_amount = match modifiers.shift {
565+ true => self
566+ .system_settings()
567+ .mouse_wheel_settings
568+ .wheel_scroll_chars
569+ .get(),
570+ false => self
571+ .system_settings()
572+ .mouse_wheel_settings
573+ .wheel_scroll_lines
574+ .get(),
575+ };
576+
577+ let wheel_distance =
578+ (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_amount as f32;
579+ let mut cursor_point = POINT {
580+ x: lparam.signed_loword().into(),
581+ y: lparam.signed_hiword().into(),
582+ };
583+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
584+ let input = PlatformInput::Scroll(ScrollEvent {
585+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
586+ delta: ScrollDelta::Lines(match modifiers.shift {
587+ true => Point {
588+ x: wheel_distance,
589+ y: 0.0,
590+ },
591+ false => Point {
592+ y: wheel_distance,
593+ x: 0.0,
594+ },
595+ }),
596+ modifiers,
597+ touch_phase: TouchPhase::Moved,
598+ source: ScrollSource::Pointer,
599+ });
600+ let handled = !func(input).propagate;
601+ self.state.callbacks.input.set(Some(func));
602+
603+ if handled { Some(0) } else { Some(1) }
604+ }
605+
606+ fn handle_mouse_horizontal_wheel_msg(
607+ &self,
608+ handle: HWND,
609+ wparam: WPARAM,
610+ lparam: LPARAM,
611+ ) -> Option<isize> {
612+ let Some(mut func) = self.state.callbacks.input.take() else {
613+ return Some(1);
614+ };
615+ let scale_factor = self.state.scale_factor.get();
616+ let wheel_scroll_chars = self
617+ .system_settings()
618+ .mouse_wheel_settings
619+ .wheel_scroll_chars
620+ .get();
621+
622+ let wheel_distance =
623+ (-wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_chars as f32;
624+ let mut cursor_point = POINT {
625+ x: lparam.signed_loword().into(),
626+ y: lparam.signed_hiword().into(),
627+ };
628+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
629+ let event = PlatformInput::Scroll(ScrollEvent {
630+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
631+ delta: ScrollDelta::Lines(Point {
632+ x: wheel_distance,
633+ y: 0.0,
634+ }),
635+ modifiers: current_modifiers(),
636+ touch_phase: TouchPhase::Moved,
637+ source: ScrollSource::Pointer,
638+ });
639+ let handled = !func(event).propagate;
640+ self.state.callbacks.input.set(Some(func));
641+
642+ if handled { Some(0) } else { Some(1) }
643+ }
644+
645+ fn retrieve_caret_position(&self) -> Option<POINT> {
646+ self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
647+ let caret_range = input_handler.selected_text_range(false)?;
648+ let caret_position = input_handler.bounds_for_range(caret_range.range)?;
649+ Some(POINT {
650+ // logical to physical
651+ x: (caret_position.origin.x.as_f32() * scale_factor) as i32,
652+ y: (caret_position.origin.y.as_f32() * scale_factor) as i32
653+ + ((caret_position.size.height.as_f32() * scale_factor) as i32 / 2),
654+ })
655+ })
656+ }
657+
658+ fn handle_ime_position(&self, handle: HWND) -> Option<isize> {
659+ if let Some(caret_position) = self.retrieve_caret_position() {
660+ self.update_ime_position(handle, caret_position);
661+ }
662+ Some(0)
663+ }
664+
665+ pub(crate) fn update_ime_position(&self, handle: HWND, caret_position: POINT) {
666+ let Some(ctx) = ImeContext::get(handle) else {
667+ return;
668+ };
669+ unsafe {
670+ ImmSetCompositionWindow(
671+ *ctx,
672+ &COMPOSITIONFORM {
673+ dwStyle: CFS_POINT,
674+ ptCurrentPos: caret_position,
675+ ..Default::default()
676+ },
677+ )
678+ .ok()
679+ .log_err();
680+
681+ ImmSetCandidateWindow(
682+ *ctx,
683+ &CANDIDATEFORM {
684+ dwStyle: CFS_CANDIDATEPOS,
685+ ptCurrentPos: caret_position,
686+ ..Default::default()
687+ },
688+ )
689+ .ok()
690+ .log_err();
691+ }
692+ }
693+
694+ fn update_ime_enabled(&self, handle: HWND) {
695+ let ime_enabled = self
696+ .with_input_handler(|input_handler| input_handler.query_accepts_text_input())
697+ .unwrap_or(false);
698+ if ime_enabled == self.state.ime_enabled.get() {
699+ return;
700+ }
701+ self.state.ime_enabled.set(ime_enabled);
702+ unsafe {
703+ if ime_enabled {
704+ ImmAssociateContextEx(handle, HIMC::default(), IACE_DEFAULT)
705+ .ok()
706+ .log_err();
707+ } else {
708+ // The IME context is per-thread, so without this check a change in this
709+ // window's text input state could commit an IME composition happening in another window.
710+ if GetFocus() == handle
711+ && let Some(ctx) = ImeContext::get(handle)
712+ {
713+ ImmNotifyIME(*ctx, NI_COMPOSITIONSTR, CPS_COMPLETE, 0)
714+ .ok()
715+ .log_err();
716+ }
717+ ImmAssociateContextEx(handle, HIMC::default(), 0)
718+ .ok()
719+ .log_err();
720+ }
721+ }
722+ }
723+
724+ fn handle_ime_composition(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
725+ let ctx = ImeContext::get(handle)?;
726+ self.handle_ime_composition_inner(*ctx, lparam)
727+ }
728+
729+ fn handle_ime_composition_inner(&self, ctx: HIMC, lparam: LPARAM) -> Option<isize> {
730+ let lparam = lparam.0 as u32;
731+ if lparam == 0 {
732+ // Japanese IME may send this message with lparam = 0, which indicates that
733+ // there is no composition string.
734+ self.with_input_handler(|input_handler| {
735+ input_handler.replace_text_in_range(None, "");
736+ })?;
737+ Some(0)
738+ } else {
739+ if lparam & GCS_RESULTSTR.0 > 0 {
740+ let comp_result = parse_ime_composition_string(ctx, GCS_RESULTSTR)?;
741+ self.with_input_handler(|input_handler| {
742+ input_handler
743+ .replace_text_in_range(None, &String::from_utf16_lossy(&comp_result));
744+ })?;
745+ }
746+ if lparam & GCS_COMPSTR.0 > 0 {
747+ let comp_string = parse_ime_composition_string(ctx, GCS_COMPSTR)?;
748+ let caret_pos =
749+ (!comp_string.is_empty() && lparam & GCS_CURSORPOS.0 > 0).then(|| {
750+ let cursor_pos = retrieve_composition_cursor_position(ctx);
751+ let pos = if should_use_ime_cursor_position(ctx, cursor_pos) {
752+ cursor_pos
753+ } else {
754+ comp_string.len()
755+ };
756+ pos..pos
757+ });
758+ self.with_input_handler(|input_handler| {
759+ input_handler.replace_and_mark_text_in_range(
760+ None,
761+ &String::from_utf16_lossy(&comp_string),
762+ caret_pos,
763+ );
764+ })?;
765+ }
766+ if lparam & (GCS_RESULTSTR.0 | GCS_COMPSTR.0) > 0 {
767+ return Some(0);
768+ }
769+
770+ // currently, we don't care other stuff
771+ None
772+ }
773+ }
774+
775+ fn handle_calc_client_size(
776+ &self,
777+ handle: HWND,
778+ wparam: WPARAM,
779+ lparam: LPARAM,
780+ ) -> Option<isize> {
781+ if !self.hide_title_bar || self.state.is_fullscreen() || wparam.0 == 0 {
782+ return None;
783+ }
784+
785+ unsafe {
786+ let params = lparam.0 as *mut NCCALCSIZE_PARAMS;
787+ let saved_top = (*params).rgrc[0].top;
788+ let result = DefWindowProcW(handle, WM_NCCALCSIZE, wparam, lparam);
789+ (*params).rgrc[0].top = saved_top;
790+ if self.state.is_maximized() {
791+ let dpi = GetDpiForWindow(handle);
792+ (*params).rgrc[0].top += get_frame_thicknessx(dpi);
793+ }
794+ Some(result.0 as isize)
795+ }
796+ }
797+
798+ fn handle_activate_msg(self: &Rc<Self>, wparam: WPARAM) -> Option<isize> {
799+ let activated = wparam.loword() > 0;
800+
801+ let events = self
802+ .state
803+ .a11y
804+ .try_borrow_mut()
805+ .ok()
806+ .and_then(|mut a11y| a11y.as_mut()?.adapter.update_window_focus_state(activated));
807+ if let Some(events) = events {
808+ events.raise();
809+ }
810+
811+ let this = self.clone();
812+
813+ if !activated {
814+ this.state.cursor_visible.store(true, Ordering::Relaxed);
815+ }
816+
817+ // When the window is activated (gains focus), reset the modifier tracking state.
818+ // This fixes the issue where Alt-Tab away and back leaves stale modifier state
819+ // (especially the Alt key) because Windows doesn't always send key-up events to
820+ // windows that have lost focus.
821+ if activated {
822+ this.state.last_reported_modifiers.set(None);
823+ this.state.last_reported_capslock.set(None);
824+
825+ if let Some(mut func) = this.state.callbacks.input.take() {
826+ let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {
827+ modifiers: current_modifiers(),
828+ capslock: current_capslock(),
829+ });
830+ func(input);
831+ this.state.callbacks.input.set(Some(func));
832+ }
833+ }
834+
835+ self.executor
836+ .spawn(async move {
837+ if let Some(mut func) = this.state.callbacks.active_status_change.take() {
838+ func(activated);
839+ this.state.callbacks.active_status_change.set(Some(func));
840+ }
841+ })
842+ .detach();
843+
844+ None
845+ }
846+
847+ fn handle_wm_getobject(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
848+ let result = {
849+ let mut a11y = self.state.a11y.borrow_mut();
850+ let a11y = a11y.as_mut()?;
851+ a11y.adapter.handle_wm_getobject(
852+ accesskit_windows::WPARAM(wparam.0),
853+ accesskit_windows::LPARAM(lparam.0),
854+ &mut a11y.activation_handler,
855+ )?
856+ };
857+ // The borrow above must be dropped before calling `.into()`, because
858+ // it calls `UiaReturnRawElementProvider` which may send a nested
859+ // `WM_GETOBJECT` back into this window procedure.
860+ let lresult: accesskit_windows::LRESULT = result.into();
861+ Some(lresult.0)
862+ }
863+
864+ fn handle_create_msg(&self, handle: HWND) -> Option<isize> {
865+ if self.hide_title_bar {
866+ notify_frame_changed(handle);
867+ Some(0)
868+ } else {
869+ None
870+ }
871+ }
872+
873+ fn handle_dpi_changed_msg(
874+ &self,
875+ handle: HWND,
876+ wparam: WPARAM,
877+ lparam: LPARAM,
878+ ) -> Option<isize> {
879+ let new_dpi = wparam.loword() as f32;
880+
881+ let is_maximized = self.state.is_maximized();
882+ let new_scale_factor = new_dpi / USER_DEFAULT_SCREEN_DPI as f32;
883+ self.state.scale_factor.set(new_scale_factor);
884+ self.state.border_offset.update(handle).log_err();
885+
886+ self.state
887+ .direct_manipulation
888+ .set_scale_factor(new_scale_factor);
889+
890+ if is_maximized {
891+ // Get the monitor and its work area at the new DPI
892+ let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONEAREST) };
893+ let mut monitor_info: MONITORINFO = unsafe { std::mem::zeroed() };
894+ monitor_info.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
895+ if unsafe { GetMonitorInfoW(monitor, &mut monitor_info) }.as_bool() {
896+ let work_area = monitor_info.rcWork;
897+ let width = work_area.right - work_area.left;
898+ let height = work_area.bottom - work_area.top;
899+
900+ // Update the window size to match the new monitor work area
901+ // This will trigger WM_SIZE which will handle the size change
902+ unsafe {
903+ SetWindowPos(
904+ handle,
905+ None,
906+ work_area.left,
907+ work_area.top,
908+ width,
909+ height,
910+ SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,
911+ )
912+ .context("unable to set maximized window position after dpi has changed")
913+ .log_err();
914+ }
915+
916+ // SetWindowPos may not send WM_SIZE for maximized windows in some cases,
917+ // so we manually update the size to ensure proper rendering
918+ let device_size = size(DevicePixels(width), DevicePixels(height));
919+ self.handle_size_change(device_size, new_scale_factor, true);
920+ }
921+ } else {
922+ // For non-maximized windows, use the suggested RECT from the system
923+ let rect = unsafe { &*(lparam.0 as *const RECT) };
924+ let width = rect.right - rect.left;
925+ let height = rect.bottom - rect.top;
926+ // this will emit `WM_SIZE` and `WM_MOVE` right here
927+ // even before this function returns
928+ // the new size is handled in `WM_SIZE`
929+ unsafe {
930+ SetWindowPos(
931+ handle,
932+ None,
933+ rect.left,
934+ rect.top,
935+ width,
936+ height,
937+ SWP_NOZORDER | SWP_NOACTIVATE,
938+ )
939+ .context("unable to set window position after dpi has changed")
940+ .log_err();
941+ }
942+ }
943+
944+ Some(0)
945+ }
946+
947+ fn handle_display_change_msg(self: &Rc<Self>, handle: HWND) -> Option<isize> {
948+ let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };
949+ if new_monitor.is_invalid() {
950+ log::error!("No monitor detected!");
951+ return None;
952+ }
953+ let new_display = WindowsDisplay::new(WindowsDisplay::display_id_for_monitor(new_monitor))?;
954+ self.set_display(new_display);
955+ Some(0)
956+ }
957+
958+ // Windows can deliver `WM_DISPLAYCHANGE` and `WM_MOVE` while GPUI is
959+ // updating a window (e.g. a clipboard read during a draw pumps sent
960+ // messages), so report the change after that update completes.
961+ fn set_display(self: &Rc<Self>, display: WindowsDisplay) {
962+ self.state.display.set(display);
963+ let this = self.clone();
964+ self.executor
965+ .spawn(async move {
966+ if let Some(mut callback) = this.state.callbacks.display_changed.take() {
967+ callback();
968+ this.state.callbacks.display_changed.set(Some(callback));
969+ }
970+ })
971+ .detach();
972+ }
973+
974+ fn handle_hit_test_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
975+ if self.state.is_fullscreen() {
976+ return None;
977+ }
978+
979+ let callback = self.state.callbacks.hit_test_window_control.take();
980+ let drag_area = if let Some(mut callback) = callback {
981+ let area = callback();
982+ self.state
983+ .callbacks
984+ .hit_test_window_control
985+ .set(Some(callback));
986+ area.and_then(|area| match area {
987+ WindowControlArea::Drag if self.is_movable => Some(HTCAPTION as _),
988+ WindowControlArea::Drag => None,
989+ WindowControlArea::Close => Some(HTCLOSE as _),
990+ WindowControlArea::Max if self.is_resizable => Some(HTMAXBUTTON as _),
991+ WindowControlArea::Max if self.is_movable => Some(HTCAPTION as _),
992+ WindowControlArea::Max => Some(HTNOWHERE as _),
993+ WindowControlArea::Min if self.is_minimizable => Some(HTMINBUTTON as _),
994+ WindowControlArea::Min if self.is_movable => Some(HTCAPTION as _),
995+ WindowControlArea::Min => Some(HTNOWHERE as _),
996+ })
997+ } else {
998+ None
999+ };
1000+
1001+ if !self.hide_title_bar {
1002+ // If the OS draws the title bar, we don't need to handle hit test messages.
1003+ return drag_area;
1004+ }
1005+
1006+ let dpi = unsafe { GetDpiForWindow(handle) };
1007+ // We do not use the OS title bar, so the default `DefWindowProcW` will only register a 1px edge for resizes
1008+ // We need to calculate the frame thickness ourselves and do the hit test manually.
1009+ let frame_y = get_frame_thicknessx(dpi);
1010+ let frame_x = get_frame_thicknessy(dpi);
1011+ let mut cursor_point = POINT {
1012+ x: lparam.signed_loword().into(),
1013+ y: lparam.signed_hiword().into(),
1014+ };
1015+
1016+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1017+ if self.is_resizable
1018+ && !self.state.is_maximized()
1019+ && 0 <= cursor_point.y
1020+ && cursor_point.y <= frame_y
1021+ {
1022+ // x-axis actually goes from -frame_x to 0
1023+ return Some(if cursor_point.x <= 0 {
1024+ HTTOPLEFT
1025+ } else {
1026+ let mut rect = Default::default();
1027+ unsafe { GetWindowRect(handle, &mut rect) }.log_err();
1028+ // right and bottom bounds of RECT are exclusive, thus `-1`
1029+ let right = rect.right - rect.left - 1;
1030+ // the bounds include the padding frames, so accommodate for both of them
1031+ if right - 2 * frame_x <= cursor_point.x {
1032+ HTTOPRIGHT
1033+ } else {
1034+ HTTOP
1035+ }
1036+ } as _);
1037+ }
1038+
1039+ drag_area
1040+ }
1041+
1042+ fn handle_nc_mouse_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1043+ self.start_tracking_mouse(handle, TME_LEAVE | TME_NONCLIENT);
1044+ self.restore_cursor_after_hide();
1045+
1046+ let mut func = self.state.callbacks.input.take()?;
1047+ let scale_factor = self.state.scale_factor.get();
1048+
1049+ let mut cursor_point = POINT {
1050+ x: lparam.signed_loword().into(),
1051+ y: lparam.signed_hiword().into(),
1052+ };
1053+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1054+ let input = PlatformInput::MouseMove(MouseMoveEvent {
1055+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1056+ pressed_button: None,
1057+ modifiers: current_modifiers(),
1058+ });
1059+ let handled = !func(input).propagate;
1060+ self.state.callbacks.input.set(Some(func));
1061+
1062+ if handled { Some(0) } else { None }
1063+ }
1064+
1065+ fn handle_nc_mouse_down_msg(
1066+ &self,
1067+ handle: HWND,
1068+ button: MouseButton,
1069+ wparam: WPARAM,
1070+ lparam: LPARAM,
1071+ ) -> Option<isize> {
1072+ if let Some(mut func) = self.state.callbacks.input.take() {
1073+ let scale_factor = self.state.scale_factor.get();
1074+ let mut cursor_point = POINT {
1075+ x: lparam.signed_loword().into(),
1076+ y: lparam.signed_hiword().into(),
1077+ };
1078+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1079+ let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));
1080+ let click_count = self.state.click_state.update(button, physical_point);
1081+
1082+ let input = PlatformInput::MouseDown(MouseDownEvent {
1083+ button,
1084+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1085+ modifiers: current_modifiers(),
1086+ click_count,
1087+ first_mouse: false,
1088+ });
1089+ let handled = !func(input).propagate;
1090+ self.state.callbacks.input.set(Some(func));
1091+
1092+ if handled {
1093+ return Some(0);
1094+ }
1095+ } else {
1096+ };
1097+
1098+ // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc
1099+ if button == MouseButton::Left {
1100+ match wparam.0 as u32 {
1101+ HTMINBUTTON => self.state.nc_button_pressed.set(Some(HTMINBUTTON)),
1102+ HTMAXBUTTON => self.state.nc_button_pressed.set(Some(HTMAXBUTTON)),
1103+ HTCLOSE => self.state.nc_button_pressed.set(Some(HTCLOSE)),
1104+ _ => return None,
1105+ };
1106+ Some(0)
1107+ } else {
1108+ None
1109+ }
1110+ }
1111+
1112+ fn handle_nc_mouse_up_msg(
1113+ &self,
1114+ handle: HWND,
1115+ button: MouseButton,
1116+ wparam: WPARAM,
1117+ lparam: LPARAM,
1118+ ) -> Option<isize> {
1119+ if let Some(mut func) = self.state.callbacks.input.take() {
1120+ let scale_factor = self.state.scale_factor.get();
1121+
1122+ let mut cursor_point = POINT {
1123+ x: lparam.signed_loword().into(),
1124+ y: lparam.signed_hiword().into(),
1125+ };
1126+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
1127+ let input = PlatformInput::MouseUp(MouseUpEvent {
1128+ button,
1129+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),
1130+ modifiers: current_modifiers(),
1131+ click_count: 1,
1132+ });
1133+ let handled = !func(input).propagate;
1134+ self.state.callbacks.input.set(Some(func));
1135+
1136+ if handled {
1137+ return Some(0);
1138+ }
1139+ } else {
1140+ }
1141+
1142+ let last_pressed = self.state.nc_button_pressed.take();
1143+ if button == MouseButton::Left
1144+ && let Some(last_pressed) = last_pressed
1145+ {
1146+ let handled = match (wparam.0 as u32, last_pressed) {
1147+ (HTMINBUTTON, HTMINBUTTON) if self.is_minimizable => {
1148+ unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };
1149+ true
1150+ }
1151+ (HTMINBUTTON, HTMINBUTTON) => true,
1152+ (HTMAXBUTTON, HTMAXBUTTON) if self.is_resizable => {
1153+ if self.state.is_maximized() {
1154+ unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };
1155+ } else {
1156+ unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };
1157+ }
1158+ true
1159+ }
1160+ (HTMAXBUTTON, HTMAXBUTTON) => true,
1161+ (HTCLOSE, HTCLOSE) => {
1162+ unsafe {
1163+ PostMessageW(Some(handle), WM_CLOSE, WPARAM::default(), LPARAM::default())
1164+ .log_err()
1165+ };
1166+ true
1167+ }
1168+ _ => false,
1169+ };
1170+ if handled {
1171+ return Some(0);
1172+ }
1173+ }
1174+
1175+ None
1176+ }
1177+
1178+ fn handle_cursor_changed(&self, lparam: LPARAM) -> Option<isize> {
1179+ let had_cursor = self.state.current_cursor.get().is_some();
1180+
1181+ self.state.current_cursor.set(if lparam.0 == 0 {
1182+ None
1183+ } else {
1184+ Some(HCURSOR(lparam.0 as _))
1185+ });
1186+
1187+ if had_cursor != self.state.current_cursor.get().is_some() {
1188+ unsafe { SetCursor(self.state.current_cursor.get()) };
1189+ }
1190+
1191+ Some(0)
1192+ }
1193+
1194+ fn handle_set_cursor(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1195+ if unsafe { !IsWindowEnabled(handle).as_bool() }
1196+ || matches!(
1197+ lparam.loword() as u32,
1198+ HTLEFT
1199+ | HTRIGHT
1200+ | HTTOP
1201+ | HTTOPLEFT
1202+ | HTTOPRIGHT
1203+ | HTBOTTOM
1204+ | HTBOTTOMLEFT
1205+ | HTBOTTOMRIGHT
1206+ )
1207+ {
1208+ return None;
1209+ }
1210+ let cursor = if self.state.cursor_visible.load(Ordering::Relaxed) {
1211+ self.state.current_cursor.get()
1212+ } else {
1213+ None
1214+ };
1215+ unsafe {
1216+ SetCursor(cursor);
1217+ };
1218+ Some(0)
1219+ }
1220+
1221+ fn handle_system_settings_changed(
1222+ &self,
1223+ handle: HWND,
1224+ wparam: WPARAM,
1225+ lparam: LPARAM,
1226+ ) -> Option<isize> {
1227+ if wparam.0 != 0 {
1228+ self.state.click_state.system_update(wparam.0);
1229+ self.state.border_offset.update(handle).log_err();
1230+ // system settings may emit a window message which wants to take the refcell self.state, so drop it
1231+
1232+ self.system_settings().update(wparam.0);
1233+ } else {
1234+ self.handle_system_theme_changed(handle, lparam)?;
1235+ };
1236+
1237+ Some(0)
1238+ }
1239+
1240+ fn handle_system_theme_changed(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {
1241+ // lParam is a pointer to a string that indicates the area containing the system parameter
1242+ // that was changed.
1243+ let parameter = PCWSTR::from_raw(lparam.0 as _);
1244+ if unsafe { !parameter.is_null() && !parameter.is_empty() }
1245+ && let Some(parameter_string) = unsafe { parameter.to_string() }.log_err()
1246+ {
1247+ log::info!("System settings changed: {}", parameter_string);
1248+ if parameter_string.as_str() == "ImmersiveColorSet" {
1249+ let new_appearance = system_appearance()
1250+ .context("unable to get system appearance when handling ImmersiveColorSet")
1251+ .log_err()?;
1252+
1253+ if new_appearance != self.state.appearance.get() {
1254+ self.state.appearance.set(new_appearance);
1255+ let mut callback = self.state.callbacks.appearance_changed.take()?;
1256+
1257+ callback();
1258+ self.state.callbacks.appearance_changed.set(Some(callback));
1259+ configure_dwm_dark_mode(handle, new_appearance);
1260+ }
1261+ }
1262+ }
1263+ Some(0)
1264+ }
1265+
1266+ fn handle_input_language_changed(&self) -> Option<isize> {
1267+ unsafe {
1268+ PostMessageW(
1269+ Some(self.platform_window_handle),
1270+ WM_GPUI_KEYBOARD_LAYOUT_CHANGED,
1271+ WPARAM(self.validation_number),
1272+ LPARAM(0),
1273+ )
1274+ .log_err();
1275+ }
1276+ Some(0)
1277+ }
1278+
1279+ fn handle_window_visibility_changed(
1280+ self: &Rc<Self>,
1281+ handle: HWND,
1282+ wparam: WPARAM,
1283+ ) -> Option<isize> {
1284+ self.report_visibility();
1285+ if wparam.0 == 1 {
1286+ self.draw_window(handle, false);
1287+ }
1288+ None
1289+ }
1290+
1291+ // The window procedure can run while GPUI is updating this window (e.g.
1292+ // `ShowWindow` from an action handler), so deliver observers after that
1293+ // update completes, as activation does. The state is read at delivery so
1294+ // a burst of messages collapses to the final value.
1295+ fn report_visibility(self: &Rc<Self>) {
1296+ if self.state.last_visibility.get().is_none() {
1297+ return;
1298+ }
1299+ let this = self.clone();
1300+ self.executor
1301+ .spawn(async move {
1302+ let visibility = this.visibility();
1303+ if this.state.last_visibility.get() == Some(visibility) {
1304+ return;
1305+ }
1306+ this.state.last_visibility.set(Some(visibility));
1307+ if let Some(mut callback) = this.state.callbacks.visibility_change.take() {
1308+ callback(visibility);
1309+ this.state.callbacks.visibility_change.set(Some(callback));
1310+ }
1311+ })
1312+ .detach();
1313+ }
1314+
1315+ fn handle_gpui_events(
1316+ &self,
1317+ handle: HWND,
1318+ message: u32,
1319+ wparam: WPARAM,
1320+ lparam: LPARAM,
1321+ ) -> Option<isize> {
1322+ if wparam.0 != self.validation_number {
1323+ return None;
1324+ }
1325+ match message {
1326+ WM_GPUI_CURSOR_STYLE_CHANGED => self.handle_cursor_changed(lparam),
1327+ WM_GPUI_FORCE_UPDATE_WINDOW => self.draw_window(handle, true),
1328+ WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),
1329+ _ => unreachable!(),
1330+ }
1331+ }
1332+
1333+ fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
1334+ if lparam.0 == 0 {
1335+ return None;
1336+ }
1337+ let devices = lparam.0 as *const DirectXDevices;
1338+ let devices = unsafe { &*devices };
1339+ if let Err(err) = self
1340+ .state
1341+ .renderer
1342+ .borrow_mut()
1343+ .handle_device_lost(&devices)
1344+ {
1345+ panic!("Device lost: {err}");
1346+ }
1347+ // Make sure the first `draw_window` after recovery (whether it comes
1348+ // from the forced WM_GPUI_FORCE_UPDATE_WINDOW or a stray WM_PAINT in
1349+ // between) is treated as a forced render so it both clears
1350+ // `skip_draws` and bypasses the view cache.
1351+ self.state.force_render_pending.set(true);
1352+ Some(0)
1353+ }
1354+
1355+ fn handle_dm_pointer_hit_test(&self, wparam: WPARAM) -> Option<isize> {
1356+ self.state.direct_manipulation.on_pointer_hit_test(wparam);
1357+ None
1358+ }
1359+
1360+ #[inline]
1361+ fn draw_window(&self, handle: HWND, force_render: bool) -> Option<isize> {
1362+ let Some(_guard) = self.state.draw_coordinator.try_begin_draw() else {
1363+ log::debug!("deferring re-entrant draw of window {handle:?}");
1364+ if force_render {
1365+ self.state.force_render_pending.set(true);
1366+ }
1367+ // Validate the region so a nested message pump doesn't keep
1368+ // re-dispatching WM_PAINT for the still-invalid region in a busy
1369+ // loop until the in-progress draw unwinds. The vsync thread
1370+ // re-invalidates every window on each vsync (see
1371+ // `begin_vsync_thread`), so the deferred frame still gets drawn,
1372+ // at most one vsync late.
1373+ unsafe { ValidateRect(Some(handle), None).ok().log_err() };
1374+ return Some(0);
1375+ };
1376+ let mut request_frame = self.state.callbacks.request_frame.take()?;
1377+
1378+ self.state.direct_manipulation.update();
1379+
1380+ let events = self.state.direct_manipulation.drain_events();
1381+ if !events.is_empty() {
1382+ if let Some(mut func) = self.state.callbacks.input.take() {
1383+ for event in events {
1384+ func(event);
1385+ }
1386+ self.state.callbacks.input.set(Some(func));
1387+ }
1388+ }
1389+
1390+ let force_render = force_render || self.state.force_render_pending.take();
1391+ if force_render {
1392+ // Re-enable drawing after a device loss recovery. The forced render
1393+ // will rebuild the scene with fresh atlas textures.
1394+ self.state.renderer.borrow_mut().mark_drawable();
1395+ }
1396+ let (signal_at, signal_source) = self.state.frame_signal.take().map_or(
1397+ (None, FrameRequestSource::NativeCallback),
1398+ |(at, source)| (Some(at), source),
1399+ );
1400+ request_frame(RequestFrameOptions {
1401+ require_presentation: false,
1402+ force_render,
1403+ signal_at,
1404+ signal_source,
1405+ });
1406+
1407+ self.state.callbacks.request_frame.set(Some(request_frame));
1408+ self.update_ime_enabled(handle);
1409+ unsafe { ValidateRect(Some(handle), None).ok().log_err() };
1410+
1411+ Some(0)
1412+ }
1413+
1414+ #[inline]
1415+ fn parse_char_message(&self, wparam: WPARAM) -> Option<String> {
1416+ let code_point = wparam.loword();
1417+
1418+ // https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G2630
1419+ match code_point {
1420+ 0xD800..=0xDBFF => {
1421+ // High surrogate, wait for low surrogate
1422+ self.state.pending_surrogate.set(Some(code_point));
1423+ None
1424+ }
1425+ 0xDC00..=0xDFFF => {
1426+ if let Some(high_surrogate) = self.state.pending_surrogate.take() {
1427+ // Low surrogate, combine with pending high surrogate
1428+ String::from_utf16(&[high_surrogate, code_point]).ok()
1429+ } else {
1430+ // Invalid low surrogate without a preceding high surrogate
1431+ log::warn!(
1432+ "Received low surrogate without a preceding high surrogate: {code_point:x}"
1433+ );
1434+ None
1435+ }
1436+ }
1437+ _ => {
1438+ self.state.pending_surrogate.set(None);
1439+ char::from_u32(code_point as u32)
1440+ .filter(|c| !c.is_control())
1441+ .map(|c| c.to_string())
1442+ }
1443+ }
1444+ }
1445+
1446+ /// Clear the hidden flag and restore the cursor immediately
1447+ fn restore_cursor_after_hide(&self) {
1448+ if !self.state.cursor_visible.swap(true, Ordering::Relaxed) {
1449+ unsafe {
1450+ SetCursor(self.state.current_cursor.get());
1451+ }
1452+ }
1453+ }
1454+
1455+ fn start_tracking_mouse(&self, handle: HWND, flags: TRACKMOUSEEVENT_FLAGS) {
1456+ if !self.state.hovered.get() {
1457+ self.state.hovered.set(true);
1458+ unsafe {
1459+ TrackMouseEvent(&mut TRACKMOUSEEVENT {
1460+ cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,
1461+ dwFlags: flags,
1462+ hwndTrack: handle,
1463+ dwHoverTime: HOVER_DEFAULT,
1464+ })
1465+ .log_err()
1466+ };
1467+ if let Some(mut callback) = self.state.callbacks.hovered_status_change.take() {
1468+ callback(true);
1469+ self.state
1470+ .callbacks
1471+ .hovered_status_change
1472+ .set(Some(callback));
1473+ }
1474+ }
1475+ }
1476+
1477+ fn with_input_handler<F, R>(&self, f: F) -> Option<R>
1478+ where
1479+ F: FnOnce(&mut PlatformInputHandler) -> R,
1480+ {
1481+ let mut input_handler = self.state.input_handler.take()?;
1482+ let result = f(&mut input_handler);
1483+ self.state.input_handler.set(Some(input_handler));
1484+ Some(result)
1485+ }
1486+
1487+ fn with_input_handler_and_scale_factor<F, R>(&self, f: F) -> Option<R>
1488+ where
1489+ F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,
1490+ {
1491+ let mut input_handler = self.state.input_handler.take()?;
1492+ let scale_factor = self.state.scale_factor.get();
1493+
1494+ let result = f(&mut input_handler, scale_factor);
1495+ self.state.input_handler.set(Some(input_handler));
1496+ result
1497+ }
1498+}
1499+
1500+struct ImeContext {
1501+ hwnd: HWND,
1502+ himc: HIMC,
1503+}
1504+
1505+impl ImeContext {
1506+ fn get(hwnd: HWND) -> Option<Self> {
1507+ let himc = unsafe { ImmGetContext(hwnd) };
1508+ if himc.is_invalid() {
1509+ return None;
1510+ }
1511+ Some(Self { hwnd, himc })
1512+ }
1513+}
1514+
1515+impl std::ops::Deref for ImeContext {
1516+ type Target = HIMC;
1517+ fn deref(&self) -> &HIMC {
1518+ &self.himc
1519+ }
1520+}
1521+
1522+impl Drop for ImeContext {
1523+ fn drop(&mut self) {
1524+ unsafe {
1525+ ImmReleaseContext(self.hwnd, self.himc).ok().log_err();
1526+ }
1527+ }
1528+}
1529+
1530+fn handle_key_event<F>(
1531+ wparam: WPARAM,
1532+ lparam: LPARAM,
1533+ state: &WindowsWindowState,
1534+ f: F,
1535+) -> Option<PlatformInput>
1536+where
1537+ F: FnOnce(Keystroke, bool) -> PlatformInput,
1538+{
1539+ let virtual_key = VIRTUAL_KEY(wparam.loword());
1540+ let modifiers = current_modifiers();
1541+
1542+ match virtual_key {
1543+ VK_SHIFT | VK_CONTROL | VK_MENU | VK_LMENU | VK_RMENU | VK_LWIN | VK_RWIN => {
1544+ if state
1545+ .last_reported_modifiers
1546+ .get()
1547+ .is_some_and(|prev_modifiers| prev_modifiers == modifiers)
1548+ {
1549+ return None;
1550+ }
1551+ state.last_reported_modifiers.set(Some(modifiers));
1552+ Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1553+ modifiers,
1554+ capslock: current_capslock(),
1555+ }))
1556+ }
1557+ VK_PACKET => None,
1558+ VK_CAPITAL => {
1559+ let capslock = current_capslock();
1560+ if state
1561+ .last_reported_capslock
1562+ .get()
1563+ .is_some_and(|prev_capslock| prev_capslock == capslock)
1564+ {
1565+ return None;
1566+ }
1567+ state.last_reported_capslock.set(Some(capslock));
1568+ Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1569+ modifiers,
1570+ capslock,
1571+ }))
1572+ }
1573+ vkey => {
1574+ let keystroke = parse_normal_key(vkey, lparam, modifiers)?;
1575+ Some(f(keystroke.0, keystroke.1))
1576+ }
1577+ }
1578+}
1579+
1580+fn parse_immutable(vkey: VIRTUAL_KEY) -> Option<String> {
1581+ Some(
1582+ match vkey {
1583+ VK_SPACE => "space",
1584+ VK_BACK => "backspace",
1585+ VK_RETURN => "enter",
1586+ VK_TAB => "tab",
1587+ VK_UP => "up",
1588+ VK_DOWN => "down",
1589+ VK_RIGHT => "right",
1590+ VK_LEFT => "left",
1591+ VK_HOME => "home",
1592+ VK_END => "end",
1593+ VK_PRIOR => "pageup",
1594+ VK_NEXT => "pagedown",
1595+ VK_BROWSER_BACK => "back",
1596+ VK_BROWSER_FORWARD => "forward",
1597+ VK_ESCAPE => "escape",
1598+ VK_INSERT => "insert",
1599+ VK_DELETE => "delete",
1600+ VK_APPS => "menu",
1601+ VK_F1 => "f1",
1602+ VK_F2 => "f2",
1603+ VK_F3 => "f3",
1604+ VK_F4 => "f4",
1605+ VK_F5 => "f5",
1606+ VK_F6 => "f6",
1607+ VK_F7 => "f7",
1608+ VK_F8 => "f8",
1609+ VK_F9 => "f9",
1610+ VK_F10 => "f10",
1611+ VK_F11 => "f11",
1612+ VK_F12 => "f12",
1613+ VK_F13 => "f13",
1614+ VK_F14 => "f14",
1615+ VK_F15 => "f15",
1616+ VK_F16 => "f16",
1617+ VK_F17 => "f17",
1618+ VK_F18 => "f18",
1619+ VK_F19 => "f19",
1620+ VK_F20 => "f20",
1621+ VK_F21 => "f21",
1622+ VK_F22 => "f22",
1623+ VK_F23 => "f23",
1624+ VK_F24 => "f24",
1625+ _ => return None,
1626+ }
1627+ .to_string(),
1628+ )
1629+}
1630+
1631+fn parse_normal_key(
1632+ vkey: VIRTUAL_KEY,
1633+ lparam: LPARAM,
1634+ mut modifiers: Modifiers,
1635+) -> Option<(Keystroke, bool)> {
1636+ let (key_char, prefer_character_input) = process_key(vkey, lparam.hiword());
1637+
1638+ let key = parse_immutable(vkey).or_else(|| {
1639+ let scan_code = lparam.hiword() & 0xFF;
1640+ get_keystroke_key(vkey, scan_code as u32, &mut modifiers)
1641+ })?;
1642+
1643+ Some((
1644+ Keystroke {
1645+ modifiers,
1646+ key,
1647+ key_char,
1648+ },
1649+ prefer_character_input,
1650+ ))
1651+}
1652+
1653+fn process_key(vkey: VIRTUAL_KEY, scan_code: u16) -> (Option<String>, bool) {
1654+ let mut keyboard_state = [0u8; 256];
1655+ unsafe {
1656+ if GetKeyboardState(&mut keyboard_state).is_err() {
1657+ return (None, false);
1658+ }
1659+ }
1660+
1661+ let mut buffer_c = [0u16; 8];
1662+ let result_c = unsafe {
1663+ ToUnicode(
1664+ vkey.0 as u32,
1665+ scan_code as u32,
1666+ Some(&keyboard_state),
1667+ &mut buffer_c,
1668+ 0x4,
1669+ )
1670+ };
1671+
1672+ if result_c == 0 {
1673+ return (None, false);
1674+ }
1675+
1676+ let c = &buffer_c[..result_c.unsigned_abs() as usize];
1677+ let key_char = String::from_utf16(c)
1678+ .ok()
1679+ .filter(|s| !s.is_empty() && !s.chars().next().unwrap().is_control());
1680+
1681+ if result_c < 0 {
1682+ return (key_char, true);
1683+ }
1684+
1685+ if key_char.is_none() {
1686+ return (None, false);
1687+ }
1688+
1689+ // Workaround for some bug that makes the compiler think keyboard_state is still zeroed out
1690+ let keyboard_state = std::hint::black_box(keyboard_state);
1691+ let ctrl_down = (keyboard_state[VK_CONTROL.0 as usize] & 0x80) != 0;
1692+ let alt_down = (keyboard_state[VK_MENU.0 as usize] & 0x80) != 0;
1693+ let win_down = (keyboard_state[VK_LWIN.0 as usize] & 0x80) != 0
1694+ || (keyboard_state[VK_RWIN.0 as usize] & 0x80) != 0;
1695+
1696+ let has_modifiers = ctrl_down || alt_down || win_down;
1697+ if !has_modifiers {
1698+ return (key_char, false);
1699+ }
1700+
1701+ let mut state_no_modifiers = keyboard_state;
1702+ state_no_modifiers[VK_CONTROL.0 as usize] = 0;
1703+ state_no_modifiers[VK_LCONTROL.0 as usize] = 0;
1704+ state_no_modifiers[VK_RCONTROL.0 as usize] = 0;
1705+ state_no_modifiers[VK_MENU.0 as usize] = 0;
1706+ state_no_modifiers[VK_LMENU.0 as usize] = 0;
1707+ state_no_modifiers[VK_RMENU.0 as usize] = 0;
1708+ state_no_modifiers[VK_LWIN.0 as usize] = 0;
1709+ state_no_modifiers[VK_RWIN.0 as usize] = 0;
1710+
1711+ let mut buffer_c_no_modifiers = [0u16; 8];
1712+ let result_c_no_modifiers = unsafe {
1713+ ToUnicode(
1714+ vkey.0 as u32,
1715+ scan_code as u32,
1716+ Some(&state_no_modifiers),
1717+ &mut buffer_c_no_modifiers,
1718+ 0x4,
1719+ )
1720+ };
1721+
1722+ let c_no_modifiers = &buffer_c_no_modifiers[..result_c_no_modifiers.unsigned_abs() as usize];
1723+ (
1724+ key_char,
1725+ result_c != result_c_no_modifiers || c != c_no_modifiers,
1726+ )
1727+}
1728+
1729+fn parse_ime_composition_string(ctx: HIMC, comp_type: IME_COMPOSITION_STRING) -> Option<Vec<u16>> {
1730+ unsafe {
1731+ let string_len = ImmGetCompositionStringW(ctx, comp_type, None, 0);
1732+ if string_len >= 0 {
1733+ let mut buffer = vec![0u8; string_len as usize + 2];
1734+ ImmGetCompositionStringW(
1735+ ctx,
1736+ comp_type,
1737+ Some(buffer.as_mut_ptr() as _),
1738+ string_len as _,
1739+ );
1740+ let wstring = std::slice::from_raw_parts::<u16>(
1741+ buffer.as_mut_ptr().cast::<u16>(),
1742+ string_len as usize / 2,
1743+ );
1744+ Some(wstring.to_vec())
1745+ } else {
1746+ None
1747+ }
1748+ }
1749+}
1750+
1751+#[inline]
1752+fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {
1753+ unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }
1754+}
1755+
1756+fn should_use_ime_cursor_position(ctx: HIMC, cursor_pos: usize) -> bool {
1757+ let attrs_size = unsafe { ImmGetCompositionStringW(ctx, GCS_COMPATTR, None, 0) } as usize;
1758+ if attrs_size == 0 {
1759+ return false;
1760+ }
1761+
1762+ let mut attrs = vec![0u8; attrs_size];
1763+ let result = unsafe {
1764+ ImmGetCompositionStringW(
1765+ ctx,
1766+ GCS_COMPATTR,
1767+ Some(attrs.as_mut_ptr() as *mut _),
1768+ attrs_size as u32,
1769+ )
1770+ };
1771+ if result <= 0 {
1772+ return false;
1773+ }
1774+
1775+ // Keep the cursor adjacent to the inserted text by only using the suggested position
1776+ // if it's adjacent to unconverted text.
1777+ let at_cursor_is_input = cursor_pos < attrs.len() && attrs[cursor_pos] == (ATTR_INPUT as u8);
1778+ let before_cursor_is_input = cursor_pos > 0
1779+ && (cursor_pos - 1) < attrs.len()
1780+ && attrs[cursor_pos - 1] == (ATTR_INPUT as u8);
1781+
1782+ at_cursor_is_input || before_cursor_is_input
1783+}
1784+
1785+#[inline]
1786+fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {
1787+ unsafe { GetKeyState(vkey.0 as i32) < 0 }
1788+}
1789+
1790+#[inline]
1791+pub(crate) fn current_modifiers() -> Modifiers {
1792+ Modifiers {
1793+ control: is_virtual_key_pressed(VK_CONTROL),
1794+ alt: is_virtual_key_pressed(VK_MENU),
1795+ shift: is_virtual_key_pressed(VK_SHIFT),
1796+ platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),
1797+ function: false,
1798+ }
1799+}
1800+
1801+#[inline]
1802+pub(crate) fn current_capslock() -> Capslock {
1803+ let on = unsafe { GetKeyState(VK_CAPITAL.0 as i32) & 1 } > 0;
1804+ Capslock { on }
1805+}
1806+
1807+// there is some additional non-visible space when talking about window
1808+// borders on Windows:
1809+// - SM_CXSIZEFRAME: The resize handle.
1810+// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.
1811+fn get_frame_thicknessx(dpi: u32) -> i32 {
1812+ let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };
1813+ let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1814+ resize_frame_thickness + padding_thickness
1815+}
1816+
1817+fn get_frame_thicknessy(dpi: u32) -> i32 {
1818+ let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CYSIZEFRAME, dpi) };
1819+ let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };
1820+ resize_frame_thickness + padding_thickness
1821+}
1822+
1823+fn notify_frame_changed(handle: HWND) {
1824+ unsafe {
1825+ SetWindowPos(
1826+ handle,
1827+ None,
1828+ 0,
1829+ 0,
1830+ 0,
1831+ 0,
1832+ SWP_FRAMECHANGED
1833+ | SWP_NOACTIVATE
1834+ | SWP_NOCOPYBITS
1835+ | SWP_NOMOVE
1836+ | SWP_NOOWNERZORDER
1837+ | SWP_NOREPOSITION
1838+ | SWP_NOSENDCHANGING
1839+ | SWP_NOSIZE
1840+ | SWP_NOZORDER,
1841+ )
1842+ .log_err();
1843+ }
1844+}
vendor/gpui-pre-windows/src/gpui_windows.rsadded+43 -0
@@ -0,0 +1,43 @@
1+#![cfg(target_os = "windows")]
2+
3+mod clipboard;
4+mod destination_list;
5+mod dialog;
6+mod direct_manipulation;
7+mod direct_write;
8+mod directx_atlas;
9+mod directx_devices;
10+mod directx_renderer;
11+mod dispatcher;
12+mod display;
13+mod events;
14+mod keyboard;
15+mod platform;
16+mod system_notifications;
17+mod system_settings;
18+mod util;
19+mod vsync;
20+mod window;
21+mod wrapper;
22+
23+pub(crate) use clipboard::*;
24+pub(crate) use destination_list::*;
25+pub(crate) use direct_write::*;
26+pub(crate) use directx_atlas::*;
27+pub(crate) use directx_devices::*;
28+pub(crate) use directx_renderer::*;
29+pub(crate) use dispatcher::*;
30+pub(crate) use display::*;
31+pub(crate) use events::*;
32+pub(crate) use keyboard::*;
33+pub(crate) use platform::*;
34+pub(crate) use system_notifications::*;
35+pub(crate) use system_settings::*;
36+pub(crate) use util::*;
37+pub(crate) use vsync::*;
38+pub(crate) use window::*;
39+pub(crate) use wrapper::*;
40+
41+pub use platform::WindowsPlatform;
42+
43+pub(crate) use windows::Win32::Foundation::HWND;
vendor/gpui-pre-windows/src/keyboard.rsadded+371 -0
@@ -0,0 +1,371 @@
1+use anyhow::Result;
2+use collections::HashMap;
3+use windows::Win32::UI::{
4+ Input::KeyboardAndMouse::{
5+ GetKeyboardLayoutNameW, MAPVK_VK_TO_CHAR, MAPVK_VK_TO_VSC, MapVirtualKeyW, ToUnicode,
6+ VIRTUAL_KEY, VK_0, VK_1, VK_2, VK_3, VK_4, VK_5, VK_6, VK_7, VK_8, VK_9, VK_ABNT_C1,
7+ VK_CONTROL, VK_MENU, VK_OEM_1, VK_OEM_2, VK_OEM_3, VK_OEM_4, VK_OEM_5, VK_OEM_6, VK_OEM_7,
8+ VK_OEM_8, VK_OEM_102, VK_OEM_COMMA, VK_OEM_MINUS, VK_OEM_PERIOD, VK_OEM_PLUS, VK_SHIFT,
9+ },
10+ WindowsAndMessaging::KL_NAMELENGTH,
11+};
12+
13+use gpui::{
14+ KeybindingKeystroke, Keystroke, Modifiers, PlatformKeyboardLayout, PlatformKeyboardMapper,
15+};
16+
17+pub(crate) struct WindowsKeyboardLayout {
18+ id: String,
19+ name: String,
20+}
21+
22+pub(crate) struct WindowsKeyboardMapper {
23+ key_to_vkey: HashMap<String, (u16, bool)>,
24+ vkey_to_key: HashMap<u16, String>,
25+ vkey_to_shifted: HashMap<u16, String>,
26+}
27+
28+impl PlatformKeyboardLayout for WindowsKeyboardLayout {
29+ fn id(&self) -> &str {
30+ &self.id
31+ }
32+
33+ fn name(&self) -> &str {
34+ &self.name
35+ }
36+}
37+
38+impl PlatformKeyboardMapper for WindowsKeyboardMapper {
39+ fn map_key_equivalent(
40+ &self,
41+ mut keystroke: Keystroke,
42+ use_key_equivalents: bool,
43+ ) -> KeybindingKeystroke {
44+ let Some((vkey, shifted_key)) = self.get_vkey_from_key(&keystroke.key, use_key_equivalents)
45+ else {
46+ return KeybindingKeystroke::from_keystroke(keystroke);
47+ };
48+ if shifted_key && keystroke.modifiers.shift {
49+ log::warn!(
50+ "Keystroke '{}' has both shift and a shifted key, this is likely a bug",
51+ keystroke.key
52+ );
53+ }
54+
55+ let shift = shifted_key || keystroke.modifiers.shift;
56+ keystroke.modifiers.shift = false;
57+
58+ let Some(key) = self.vkey_to_key.get(&vkey).cloned() else {
59+ log::error!(
60+ "Failed to map key equivalent '{:?}' to a valid key",
61+ keystroke
62+ );
63+ return KeybindingKeystroke::from_keystroke(keystroke);
64+ };
65+
66+ keystroke.key = if shift {
67+ let Some(shifted_key) = self.vkey_to_shifted.get(&vkey).cloned() else {
68+ log::error!(
69+ "Failed to map keystroke {:?} with virtual key '{:?}' to a shifted key",
70+ keystroke,
71+ vkey
72+ );
73+ return KeybindingKeystroke::from_keystroke(keystroke);
74+ };
75+ shifted_key
76+ } else {
77+ key.clone()
78+ };
79+
80+ let modifiers = Modifiers {
81+ shift,
82+ ..keystroke.modifiers
83+ };
84+
85+ KeybindingKeystroke::new(keystroke, modifiers, key)
86+ }
87+
88+ fn get_key_equivalents(&self) -> Option<&HashMap<char, char>> {
89+ None
90+ }
91+}
92+
93+impl WindowsKeyboardLayout {
94+ pub(crate) fn new() -> Result<Self> {
95+ let mut buffer = [0u16; KL_NAMELENGTH as usize]; // KL_NAMELENGTH includes the null terminator
96+ unsafe { GetKeyboardLayoutNameW(&mut buffer)? };
97+ let id = String::from_utf16_lossy(&buffer[..buffer.len() - 1]); // Remove the null terminator
98+ let entry = windows_registry::LOCAL_MACHINE.open(format!(
99+ "System\\CurrentControlSet\\Control\\Keyboard Layouts\\{id}"
100+ ))?;
101+ let name = entry.get_string("Layout Text")?;
102+ Ok(Self { id, name })
103+ }
104+
105+ pub(crate) fn unknown() -> Self {
106+ Self {
107+ id: "unknown".to_string(),
108+ name: "unknown".to_string(),
109+ }
110+ }
111+}
112+
113+impl WindowsKeyboardMapper {
114+ pub(crate) fn new() -> Self {
115+ let mut key_to_vkey = HashMap::default();
116+ let mut vkey_to_key = HashMap::default();
117+ let mut vkey_to_shifted = HashMap::default();
118+ for vkey in CANDIDATE_VKEYS {
119+ if let Some(key) = get_key_from_vkey(*vkey) {
120+ key_to_vkey.insert(key.clone(), (vkey.0, false));
121+ vkey_to_key.insert(vkey.0, key);
122+ }
123+ let scan_code = unsafe { MapVirtualKeyW(vkey.0 as u32, MAPVK_VK_TO_VSC) };
124+ if scan_code == 0 {
125+ continue;
126+ }
127+ if let Some(shifted_key) = get_shifted_key(*vkey, scan_code) {
128+ key_to_vkey.insert(shifted_key.clone(), (vkey.0, true));
129+ vkey_to_shifted.insert(vkey.0, shifted_key);
130+ }
131+ }
132+ Self {
133+ key_to_vkey,
134+ vkey_to_key,
135+ vkey_to_shifted,
136+ }
137+ }
138+
139+ fn get_vkey_from_key(&self, key: &str, use_key_equivalents: bool) -> Option<(u16, bool)> {
140+ if use_key_equivalents {
141+ get_vkey_from_key_with_us_layout(key)
142+ } else {
143+ self.key_to_vkey.get(key).cloned()
144+ }
145+ }
146+}
147+
148+pub(crate) fn get_keystroke_key(
149+ vkey: VIRTUAL_KEY,
150+ scan_code: u32,
151+ modifiers: &mut Modifiers,
152+) -> Option<String> {
153+ if modifiers.shift && need_to_convert_to_shifted_key(vkey) {
154+ get_shifted_key(vkey, scan_code).inspect(|_| {
155+ modifiers.shift = false;
156+ })
157+ } else {
158+ get_key_from_vkey(vkey)
159+ }
160+}
161+
162+fn get_key_from_vkey(vkey: VIRTUAL_KEY) -> Option<String> {
163+ let key_data = unsafe { MapVirtualKeyW(vkey.0 as u32, MAPVK_VK_TO_CHAR) };
164+ if key_data == 0 {
165+ return None;
166+ }
167+
168+ // The high word contains dead key flag, the low word contains the character
169+ let key = char::from_u32(key_data & 0xFFFF)?;
170+
171+ Some(key.to_ascii_lowercase().to_string())
172+}
173+
174+#[inline]
175+fn need_to_convert_to_shifted_key(vkey: VIRTUAL_KEY) -> bool {
176+ matches!(
177+ vkey,
178+ VK_OEM_3
179+ | VK_OEM_MINUS
180+ | VK_OEM_PLUS
181+ | VK_OEM_4
182+ | VK_OEM_5
183+ | VK_OEM_6
184+ | VK_OEM_1
185+ | VK_OEM_7
186+ | VK_OEM_COMMA
187+ | VK_OEM_PERIOD
188+ | VK_OEM_2
189+ | VK_OEM_102
190+ | VK_OEM_8
191+ | VK_ABNT_C1
192+ | VK_0
193+ | VK_1
194+ | VK_2
195+ | VK_3
196+ | VK_4
197+ | VK_5
198+ | VK_6
199+ | VK_7
200+ | VK_8
201+ | VK_9
202+ )
203+}
204+
205+fn get_shifted_key(vkey: VIRTUAL_KEY, scan_code: u32) -> Option<String> {
206+ generate_key_char(vkey, scan_code, false, true, false)
207+}
208+
209+pub(crate) fn generate_key_char(
210+ vkey: VIRTUAL_KEY,
211+ scan_code: u32,
212+ control: bool,
213+ shift: bool,
214+ alt: bool,
215+) -> Option<String> {
216+ let mut state = [0; 256];
217+ if control {
218+ state[VK_CONTROL.0 as usize] = 0x80;
219+ }
220+ if shift {
221+ state[VK_SHIFT.0 as usize] = 0x80;
222+ }
223+ if alt {
224+ state[VK_MENU.0 as usize] = 0x80;
225+ }
226+
227+ let mut buffer = [0; 8];
228+ let len = unsafe { ToUnicode(vkey.0 as u32, scan_code, Some(&state), &mut buffer, 0x5) };
229+
230+ match len {
231+ len if len > 0 => String::from_utf16(&buffer[..len as usize])
232+ .ok()
233+ .filter(|candidate| {
234+ !candidate.is_empty() && !candidate.chars().next().unwrap().is_control()
235+ }),
236+ len if len < 0 => String::from_utf16(&buffer[..(-len as usize)]).ok(),
237+ _ => None,
238+ }
239+}
240+
241+fn get_vkey_from_key_with_us_layout(key: &str) -> Option<(u16, bool)> {
242+ match key {
243+ // ` => VK_OEM_3
244+ "`" => Some((VK_OEM_3.0, false)),
245+ "~" => Some((VK_OEM_3.0, true)),
246+ "1" => Some((VK_1.0, false)),
247+ "!" => Some((VK_1.0, true)),
248+ "2" => Some((VK_2.0, false)),
249+ "@" => Some((VK_2.0, true)),
250+ "3" => Some((VK_3.0, false)),
251+ "#" => Some((VK_3.0, true)),
252+ "4" => Some((VK_4.0, false)),
253+ "$" => Some((VK_4.0, true)),
254+ "5" => Some((VK_5.0, false)),
255+ "%" => Some((VK_5.0, true)),
256+ "6" => Some((VK_6.0, false)),
257+ "^" => Some((VK_6.0, true)),
258+ "7" => Some((VK_7.0, false)),
259+ "&" => Some((VK_7.0, true)),
260+ "8" => Some((VK_8.0, false)),
261+ "*" => Some((VK_8.0, true)),
262+ "9" => Some((VK_9.0, false)),
263+ "(" => Some((VK_9.0, true)),
264+ "0" => Some((VK_0.0, false)),
265+ ")" => Some((VK_0.0, true)),
266+ "-" => Some((VK_OEM_MINUS.0, false)),
267+ "_" => Some((VK_OEM_MINUS.0, true)),
268+ "=" => Some((VK_OEM_PLUS.0, false)),
269+ "+" => Some((VK_OEM_PLUS.0, true)),
270+ "[" => Some((VK_OEM_4.0, false)),
271+ "{" => Some((VK_OEM_4.0, true)),
272+ "]" => Some((VK_OEM_6.0, false)),
273+ "}" => Some((VK_OEM_6.0, true)),
274+ "\\" => Some((VK_OEM_5.0, false)),
275+ "|" => Some((VK_OEM_5.0, true)),
276+ ";" => Some((VK_OEM_1.0, false)),
277+ ":" => Some((VK_OEM_1.0, true)),
278+ "'" => Some((VK_OEM_7.0, false)),
279+ "\"" => Some((VK_OEM_7.0, true)),
280+ "," => Some((VK_OEM_COMMA.0, false)),
281+ "<" => Some((VK_OEM_COMMA.0, true)),
282+ "." => Some((VK_OEM_PERIOD.0, false)),
283+ ">" => Some((VK_OEM_PERIOD.0, true)),
284+ "/" => Some((VK_OEM_2.0, false)),
285+ "?" => Some((VK_OEM_2.0, true)),
286+ _ => None,
287+ }
288+}
289+
290+const CANDIDATE_VKEYS: &[VIRTUAL_KEY] = &[
291+ VK_OEM_3,
292+ VK_OEM_MINUS,
293+ VK_OEM_PLUS,
294+ VK_OEM_4,
295+ VK_OEM_5,
296+ VK_OEM_6,
297+ VK_OEM_1,
298+ VK_OEM_7,
299+ VK_OEM_COMMA,
300+ VK_OEM_PERIOD,
301+ VK_OEM_2,
302+ VK_OEM_102,
303+ VK_OEM_8,
304+ VK_ABNT_C1,
305+ VK_0,
306+ VK_1,
307+ VK_2,
308+ VK_3,
309+ VK_4,
310+ VK_5,
311+ VK_6,
312+ VK_7,
313+ VK_8,
314+ VK_9,
315+];
316+
317+#[cfg(test)]
318+mod tests {
319+ use crate::WindowsKeyboardMapper;
320+ use gpui::{Keystroke, Modifiers, PlatformKeyboardMapper};
321+
322+ #[test]
323+ fn test_keyboard_mapper() {
324+ let mapper = WindowsKeyboardMapper::new();
325+
326+ // Normal case
327+ let keystroke = Keystroke {
328+ modifiers: Modifiers::control(),
329+ key: "a".to_string(),
330+ key_char: None,
331+ };
332+ let mapped = mapper.map_key_equivalent(keystroke.clone(), true);
333+ assert_eq!(*mapped.inner(), keystroke);
334+ assert_eq!(mapped.key(), "a");
335+ assert_eq!(*mapped.modifiers(), Modifiers::control());
336+
337+ // Shifted case, ctrl-$
338+ let keystroke = Keystroke {
339+ modifiers: Modifiers::control(),
340+ key: "$".to_string(),
341+ key_char: None,
342+ };
343+ let mapped = mapper.map_key_equivalent(keystroke.clone(), true);
344+ assert_eq!(*mapped.inner(), keystroke);
345+ assert_eq!(mapped.key(), "4");
346+ assert_eq!(*mapped.modifiers(), Modifiers::control_shift());
347+
348+ // Shifted case, but shift is true
349+ let keystroke = Keystroke {
350+ modifiers: Modifiers::control_shift(),
351+ key: "$".to_string(),
352+ key_char: None,
353+ };
354+ let mapped = mapper.map_key_equivalent(keystroke, true);
355+ assert_eq!(mapped.inner().modifiers, Modifiers::control());
356+ assert_eq!(mapped.key(), "4");
357+ assert_eq!(*mapped.modifiers(), Modifiers::control_shift());
358+
359+ // Windows style
360+ let keystroke = Keystroke {
361+ modifiers: Modifiers::control_shift(),
362+ key: "4".to_string(),
363+ key_char: None,
364+ };
365+ let mapped = mapper.map_key_equivalent(keystroke, true);
366+ assert_eq!(mapped.inner().modifiers, Modifiers::control());
367+ assert_eq!(mapped.inner().key, "$");
368+ assert_eq!(mapped.key(), "4");
369+ assert_eq!(*mapped.modifiers(), Modifiers::control_shift());
370+ }
371+}
vendor/gpui-pre-windows/src/platform.rsadded+2045 -0

Diff too large; view file

@@ -0,0 +1,2045 @@
1+use std::{
2+ cell::{Cell, RefCell},
3+ ffi::{OsStr, OsString},
4+ os::windows::ffi::{OsStrExt as _, OsStringExt as _},
5+ path::{Path, PathBuf},
6+ rc::{Rc, Weak},
7+ sync::{
8+ Arc,
9+ atomic::{AtomicBool, Ordering},
10+ },
11+};
12+
13+use anyhow::{Context as _, Result, anyhow};
14+use futures::channel::oneshot::Receiver;
15+use gpui_util::{ResultExt, get_powershell, new_std_command};
16+use itertools::Itertools;
17+use parking_lot::RwLock;
18+use smallvec::SmallVec;
19+use windows::{
20+ UI::ViewManagement::UISettings,
21+ Win32::{
22+ Foundation::*,
23+ Graphics::{Direct3D11::ID3D11Device, Gdi::*},
24+ Security::Credentials::*,
25+ System::{
26+ Com::*,
27+ LibraryLoader::*,
28+ Ole::*,
29+ Power::*,
30+ SystemInformation::*,
31+ SystemServices::{GUID_POWER_SAVING_STATUS, POWER_REQUEST_CONTEXT_VERSION},
32+ Threading::{POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT, REASON_CONTEXT_0},
33+ },
34+ UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
35+ },
36+ core::*,
37+};
38+
39+use crate::*;
40+use gpui::*;
41+
42+struct TrackedWindow {
43+ handle: SafeHwnd,
44+ frame_signal: Arc<PlatformFrameSignal>,
45+}
46+
47+impl TrackedWindow {
48+ fn as_raw(&self) -> HWND {
49+ self.handle.as_raw()
50+ }
51+}
52+
53+pub struct WindowsPlatform {
54+ inner: Rc<WindowsPlatformInner>,
55+ raw_window_handles: Arc<RwLock<SmallVec<[TrackedWindow; 4]>>>,
56+ /// The windowing mode to start in, applied when `run` starts. Windowed when unset.
57+ initial_windowing: RefCell<Option<WindowingRequest>>,
58+ /// Set to stop the current `VSyncProvider` thread, which runs while windowed.
59+ vsync_stop: RefCell<Option<Arc<AtomicBool>>>,
60+ // The below members will never change throughout the entire lifecycle of the app.
61+ /// Created with `headless()`: never windowed, and without a real text system.
62+ headless: bool,
63+ icon: HICON,
64+ background_executor: BackgroundExecutor,
65+ foreground_executor: ForegroundExecutor,
66+ text_system: Arc<dyn PlatformTextSystem>,
67+ drop_target_helper: Option<IDropTargetHelper>,
68+ /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
69+ /// as resizing them has failed, causing us to have lost at least the render target.
70+ invalidate_devices: Arc<AtomicBool>,
71+ handle: HWND,
72+ suspend_resume_notification: RefCell<Option<HPOWERNOTIFY>>,
73+ power_saving_notification: RefCell<Option<HPOWERNOTIFY>>,
74+ disable_direct_composition: bool,
75+ has_package_identity: bool,
76+ app_identity: RefCell<Option<(String, String)>>,
77+ system_notifications: RefCell<SystemNotificationState>,
78+}
79+
80+struct WindowsPlatformInner {
81+ state: WindowsPlatformState,
82+ raw_window_handles: std::sync::Weak<RwLock<SmallVec<[TrackedWindow; 4]>>>,
83+ // The below members will never change throughout the entire lifecycle of the app.
84+ validation_number: usize,
85+ main_receiver: PriorityQueueReceiver<RunnableVariant>,
86+ dispatcher: Arc<WindowsDispatcher>,
87+}
88+
89+pub(crate) struct WindowsPlatformState {
90+ callbacks: PlatformCallbacks,
91+ menus: RefCell<Vec<OwnedMenu>>,
92+ jump_list: RefCell<JumpList>,
93+ // NOTE: standard cursor handles don't need to close.
94+ pub(crate) current_cursor: Cell<Option<HCURSOR>>,
95+ /// Shared with each window so `WM_SETCURSOR` can read it directly.
96+ pub(crate) cursor_visible: Arc<AtomicBool>,
97+ /// Shared with each window to coordinate draws across windows on the UI
98+ /// thread; see [`DrawCoordinator`].
99+ pub(crate) draw_coordinator: Rc<DrawCoordinator>,
100+ directx_devices: RefCell<Option<DirectXDevices>>,
101+ low_power_mode_enabled: Cell<bool>,
102+}
103+
104+#[derive(Default)]
105+struct PlatformCallbacks {
106+ open_urls: Cell<Option<Box<dyn FnMut(Vec<String>)>>>,
107+ quit: Cell<Option<Box<dyn FnMut() -> bool>>>,
108+ reopen: Cell<Option<Box<dyn FnMut()>>>,
109+ app_menu_action: Cell<Option<Box<dyn FnMut(&dyn Action)>>>,
110+ will_open_app_menu: Cell<Option<Box<dyn FnMut()>>>,
111+ validate_app_menu_command: Cell<Option<Box<dyn FnMut(&dyn Action) -> bool>>>,
112+ keyboard_layout_change: Cell<Option<Box<dyn FnMut()>>>,
113+ system_sleep: Cell<Option<Box<dyn FnMut()>>>,
114+ system_wake: Cell<Option<Box<dyn FnMut()>>>,
115+ low_power_mode_change: Cell<Option<Box<dyn FnMut()>>>,
116+ displays_changed: Cell<Option<Box<dyn FnMut()>>>,
117+}
118+
119+impl WindowsPlatformState {
120+ fn new(directx_devices: Option<DirectXDevices>) -> Self {
121+ let callbacks = PlatformCallbacks::default();
122+ let jump_list = JumpList::new();
123+ let current_cursor = load_cursor(CursorStyle::Arrow);
124+
125+ Self {
126+ callbacks,
127+ jump_list: RefCell::new(jump_list),
128+ current_cursor: Cell::new(current_cursor),
129+ cursor_visible: Arc::new(AtomicBool::new(true)),
130+ draw_coordinator: Rc::new(DrawCoordinator::new()),
131+ directx_devices: RefCell::new(directx_devices),
132+ low_power_mode_enabled: Cell::new(false),
133+ menus: RefCell::new(Vec::new()),
134+ }
135+ }
136+}
137+
138+struct PowerRequest {
139+ handle: HANDLE,
140+ // `PowerCreateRequest` retains a pointer into the reason string for the
141+ // lifetime of the handle, so the UTF-16 buffer must outlive the request.
142+ _reason: Vec<u16>,
143+}
144+
145+unsafe impl Send for PowerRequest {}
146+
147+impl PowerRequest {
148+ fn prevent_idle_sleep(reason: &str) -> Result<Self> {
149+ let mut reason = reason.encode_utf16().chain([0]).collect::<Vec<_>>();
150+ let context = REASON_CONTEXT {
151+ Version: POWER_REQUEST_CONTEXT_VERSION,
152+ Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,
153+ Reason: REASON_CONTEXT_0 {
154+ SimpleReasonString: PWSTR(reason.as_mut_ptr()),
155+ },
156+ };
157+ let handle = unsafe { PowerCreateRequest(&context) }
158+ .context("Failed to create a Windows power request")?;
159+ if let Err(error) = unsafe { PowerSetRequest(handle, PowerRequestSystemRequired) } {
160+ unsafe { CloseHandle(handle) }
161+ .context("Failed to close the Windows power request")
162+ .log_err();
163+ return Err(error).context("Failed to set the Windows power request");
164+ }
165+ Ok(Self {
166+ handle,
167+ _reason: reason,
168+ })
169+ }
170+}
171+
172+impl Drop for PowerRequest {
173+ fn drop(&mut self) {
174+ unsafe { PowerClearRequest(self.handle, PowerRequestSystemRequired) }
175+ .context("Failed to clear the Windows power request")
176+ .log_err();
177+ unsafe { CloseHandle(self.handle) }
178+ .context("Failed to close the Windows power request")
179+ .log_err();
180+ }
181+}
182+
183+impl WindowsPlatform {
184+ pub fn new(headless: bool) -> Result<Self> {
185+ unsafe {
186+ OleInitialize(None).context("unable to initialize Windows OLE")?;
187+ }
188+ // A platform that can become windowed needs the real text system from the start: the app
189+ // keeps the one it's created with.
190+ let text_system: Arc<dyn PlatformTextSystem> = if !headless {
191+ Arc::new(DirectWriteTextSystem::new().context("Error creating DirectWriteTextSystem")?)
192+ } else {
193+ Arc::new(gpui::NoopTextSystem::new())
194+ };
195+
196+ let (main_sender, main_receiver) = PriorityQueueReceiver::new();
197+ let validation_number = if usize::BITS == 64 {
198+ rand::random::<u64>() as usize
199+ } else {
200+ rand::random::<u32>() as usize
201+ };
202+ let raw_window_handles = Arc::new(RwLock::new(SmallVec::new()));
203+
204+ register_platform_window_class();
205+ let mut context = PlatformWindowCreateContext {
206+ inner: None,
207+ raw_window_handles: Arc::downgrade(&raw_window_handles),
208+ validation_number,
209+ main_sender: Some(main_sender),
210+ main_receiver: Some(main_receiver),
211+ directx_devices: None,
212+ dispatcher: None,
213+ };
214+ // A hidden top-level window rather than a message-only one, since only
215+ // top-level windows receive system broadcasts such as `WM_DISPLAYCHANGE`
216+ // and `WM_ENDSESSION`, which the app needs even with no windows open.
217+ let result = unsafe {
218+ CreateWindowExW(
219+ WS_EX_TOOLWINDOW,
220+ PLATFORM_WINDOW_CLASS_NAME,
221+ None,
222+ WINDOW_STYLE(0),
223+ 0,
224+ 0,
225+ 0,
226+ 0,
227+ None,
228+ None,
229+ None,
230+ Some(&raw const context as *const _),
231+ )
232+ };
233+ let inner = context
234+ .inner
235+ .take()
236+ .context("CreateWindowExW did not run correctly")??;
237+ let mut power_status = SYSTEM_POWER_STATUS::default();
238+ match unsafe { GetSystemPowerStatus(&mut power_status) } {
239+ Ok(()) => inner
240+ .state
241+ .low_power_mode_enabled
242+ .set(power_status.SystemStatusFlag == 1),
243+ Err(error) => log::warn!("Failed to query Windows battery saver status: {error}"),
244+ }
245+ let dispatcher = context
246+ .dispatcher
247+ .take()
248+ .context("CreateWindowExW did not run correctly")?;
249+ let handle = result?;
250+
251+ let disable_direct_composition = std::env::var(DISABLE_DIRECT_COMPOSITION)
252+ .is_ok_and(|value| value == "true" || value == "1");
253+ let background_executor = BackgroundExecutor::new(dispatcher.clone());
254+ let foreground_executor = ForegroundExecutor::new(dispatcher);
255+
256+ let drop_target_helper: Option<IDropTargetHelper> = if !headless {
257+ Some(unsafe {
258+ CoCreateInstance(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER)
259+ .context("Error creating drop target helper.")?
260+ })
261+ } else {
262+ None
263+ };
264+ let icon = if !headless {
265+ load_icon().unwrap_or_default()
266+ } else {
267+ HICON::default()
268+ };
269+
270+ Ok(Self {
271+ inner,
272+ handle,
273+ raw_window_handles,
274+ initial_windowing: RefCell::new(None),
275+ vsync_stop: RefCell::new(None),
276+ headless,
277+ icon,
278+ background_executor,
279+ foreground_executor,
280+ text_system,
281+ suspend_resume_notification: RefCell::new(None),
282+ power_saving_notification: RefCell::new(None),
283+ disable_direct_composition,
284+ has_package_identity: has_package_identity(),
285+ drop_target_helper,
286+ invalidate_devices: Arc::new(AtomicBool::new(false)),
287+ app_identity: RefCell::new(None),
288+ system_notifications: RefCell::new(SystemNotificationState::new()),
289+ })
290+ }
291+
292+ pub(crate) fn window_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
293+ self.inner.window_from_hwnd(hwnd)
294+ }
295+
296+ #[inline]
297+ fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {
298+ self.raw_window_handles
299+ .read()
300+ .iter()
301+ .for_each(|handle| unsafe {
302+ PostMessageW(Some(handle.as_raw()), message, wparam, lparam).log_err();
303+ });
304+ }
305+
306+ fn generate_creation_info(&self) -> WindowCreationInfo {
307+ WindowCreationInfo {
308+ icon: self.icon,
309+ executor: self.foreground_executor.clone(),
310+ current_cursor: self.inner.state.current_cursor.get(),
311+ cursor_visible: self.inner.state.cursor_visible.clone(),
312+ drop_target_helper: self.drop_target_helper.clone().unwrap(),
313+ validation_number: self.inner.validation_number,
314+ main_receiver: self.inner.main_receiver.clone(),
315+ platform_window_handle: self.handle,
316+ disable_direct_composition: self.disable_direct_composition,
317+ directx_devices: self.inner.state.directx_devices.borrow().clone().unwrap(),
318+ invalidate_devices: self.invalidate_devices.clone(),
319+ draw_coordinator: self.inner.state.draw_coordinator.clone(),
320+ }
321+ }
322+
323+ fn set_dock_menus(&self, menus: Vec<MenuItem>) {
324+ let mut actions = Vec::new();
325+ menus.into_iter().for_each(|menu| {
326+ if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
327+ actions.push(dock_menu);
328+ }
329+ });
330+ self.inner.state.jump_list.borrow_mut().dock_menus = actions;
331+ let borrow = self.inner.state.jump_list.borrow();
332+ let dock_menus = borrow
333+ .dock_menus
334+ .iter()
335+ .map(|menu| (menu.name.clone(), menu.description.clone()))
336+ .collect::<Vec<_>>();
337+ let recent_workspaces = borrow.recent_workspaces.clone();
338+ self.background_executor
339+ .spawn(async move {
340+ update_jump_list(&recent_workspaces, &dock_menus).log_err();
341+ })
342+ .detach();
343+ }
344+
345+ fn update_jump_list(
346+ &self,
347+ menus: Vec<MenuItem>,
348+ entries: Vec<SmallVec<[PathBuf; 2]>>,
349+ ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
350+ let mut actions = Vec::new();
351+ menus.into_iter().for_each(|menu| {
352+ if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {
353+ actions.push(dock_menu);
354+ }
355+ });
356+ let mut jump_list = self.inner.state.jump_list.borrow_mut();
357+ jump_list.dock_menus = actions;
358+ jump_list.recent_workspaces = entries.into();
359+ let dock_menus = jump_list
360+ .dock_menus
361+ .iter()
362+ .map(|menu| (menu.name.clone(), menu.description.clone()))
363+ .collect::<Vec<_>>();
364+ let recent_workspaces = jump_list.recent_workspaces.clone();
365+ self.background_executor.spawn(async move {
366+ update_jump_list(&recent_workspaces, &dock_menus)
367+ .log_err()
368+ .unwrap_or_default()
369+ })
370+ }
371+
372+ fn find_current_active_window(&self) -> Option<HWND> {
373+ let active_window_hwnd = unsafe { GetActiveWindow() };
374+ if active_window_hwnd.is_invalid() {
375+ return None;
376+ }
377+ self.raw_window_handles
378+ .read()
379+ .iter()
380+ .find(|hwnd| hwnd.as_raw() == active_window_hwnd)
381+ .map(|hwnd| hwnd.as_raw())
382+ }
383+
384+ fn is_windowed(&self) -> bool {
385+ self.inner.state.directx_devices.borrow().is_some()
386+ }
387+
388+ /// Connects in the initial windowing mode, before the app finishes launching.
389+ ///
390+ /// # Panics
391+ ///
392+ /// Panics if DirectX can't be initialized, since the app can't start. Starts headless if this
393+ /// process can't show windows, for example when started over SSH.
394+ fn connect_initially(&self) {
395+ let request = self
396+ .initial_windowing
397+ .borrow_mut()
398+ .take()
399+ .unwrap_or_else(|| WindowingRequest::Windowed(GraphicalEnvironment::detect()));
400+ let WindowingRequest::Windowed(environment) = request else {
401+ return;
402+ };
403+ if let Err(error) = check_can_show_windows(&environment) {
404+ log::info!("starting headless: {error:#}");
405+ return;
406+ }
407+ self.attach_gpu()
408+ .unwrap_or_else(|error| panic!("failed to initialize DirectX: {error:#}"));
409+ }
410+
411+ /// Creates the DirectX devices that windows draw with, and starts vsync.
412+ fn attach_gpu(&self) -> Result<()> {
413+ let devices = DirectXDevices::new().context("Creating DirectX devices")?;
414+ *self.inner.state.directx_devices.borrow_mut() = Some(devices);
415+ self.begin_vsync_thread();
416+ Ok(())
417+ }
418+
419+ /// Stops vsync and releases the DirectX devices. No window may be open.
420+ fn detach_gpu(&self) {
421+ if let Some(stop) = self.vsync_stop.borrow_mut().take() {
422+ // Not joined: the thread can be sending this thread a message. It exits after its
423+ // next vsync, and drops its reference to the devices then.
424+ stop.store(true, Ordering::Release);
425+ }
426+ self.inner.state.directx_devices.borrow_mut().take();
427+ }
428+
429+ fn begin_vsync_thread(&self) {
430+ let Some(directx_devices) = self.inner.state.directx_devices.borrow().clone() else {
431+ return;
432+ };
433+ let stop = Arc::new(AtomicBool::new(false));
434+ *self.vsync_stop.borrow_mut() = Some(stop.clone());
435+ let mut directx_device = directx_devices;
436+ let platform_window: SafeHwnd = self.handle.into();
437+ let validation_number = self.inner.validation_number;
438+ let all_windows = Arc::downgrade(&self.raw_window_handles);
439+ let invalidate_devices = self.invalidate_devices.clone();
440+
441+ std::thread::Builder::new()
442+ .name("VSyncProvider".to_owned())
443+ .spawn(move || {
444+ let vsync_provider = VSyncProvider::new();
445+ loop {
446+ let signal_source = vsync_provider.wait_for_vsync();
447+ let signal_at = PlatformFrameSignal::capture(scheduler::Instant::now);
448+ if stop.load(Ordering::Acquire) {
449+ break;
450+ }
451+ if check_device_lost(&directx_device.device)
452+ || invalidate_devices.fetch_and(false, Ordering::Acquire)
453+ {
454+ if let Err(err) = handle_gpu_device_lost(
455+ &mut directx_device,
456+ platform_window.as_raw(),
457+ validation_number,
458+ &all_windows,
459+ ) {
460+ panic!("Device lost: {err}");
461+ }
462+ }
463+ let Some(all_windows) = all_windows.upgrade() else {
464+ break;
465+ };
466+ for hwnd in all_windows.read().iter() {
467+ unsafe {
468+ if let Some(signal_at) = signal_at {
469+ if IsWindowVisible(hwnd.as_raw()).as_bool()
470+ && !IsIconic(hwnd.as_raw()).as_bool()
471+ {
472+ hwnd.frame_signal.record(signal_at, signal_source);
473+ } else {
474+ // Hidden windows may not consume WM_PAINT until shown again.
475+ hwnd.frame_signal.take();
476+ }
477+ }
478+ RedrawWindow(Some(hwnd.as_raw()), None, None, RDW_INVALIDATE)
479+ .ok()
480+ .log_err();
481+ }
482+ }
483+ }
484+ })
485+ .unwrap();
486+ }
487+}
488+
489+fn encode_restart_arguments(arguments: &[OsString]) -> OsString {
490+ // `Start-Process` accepts a single native command line, so quote each argument according to
491+ // the Windows argv parsing rules before passing the complete string through the environment.
492+ let mut encoded = Vec::new();
493+
494+ for (index, argument) in arguments.iter().enumerate() {
495+ if index > 0 {
496+ encoded.push(b' ' as u16);
497+ }
498+ encoded.push(b'"' as u16);
499+
500+ let mut backslash_count = 0;
501+ for code_unit in argument.encode_wide() {
502+ if code_unit == b'\\' as u16 {
503+ backslash_count += 1;
504+ } else {
505+ if code_unit == b'"' as u16 {
506+ encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count * 2 + 1));
507+ } else {
508+ encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count));
509+ }
510+ backslash_count = 0;
511+ encoded.push(code_unit);
512+ }
513+ }
514+
515+ encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count * 2));
516+ encoded.push(b'"' as u16);
517+ }
518+
519+ OsString::from_wide(&encoded)
520+}
521+
522+impl Platform for WindowsPlatform {
523+ fn platform_info(&self) -> gpui::PlatformInfo {
524+ gpui::PlatformInfo {
525+ os: gpui::OperatingSystem::Windows,
526+ target: gpui::PlatformTarget::Native,
527+ }
528+ }
529+
530+ fn background_executor(&self) -> BackgroundExecutor {
531+ self.background_executor.clone()
532+ }
533+
534+ fn foreground_executor(&self) -> ForegroundExecutor {
535+ self.foreground_executor.clone()
536+ }
537+
538+ fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
539+ self.text_system.clone()
540+ }
541+
542+ fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
543+ Box::new(
544+ WindowsKeyboardLayout::new()
545+ .log_err()
546+ .unwrap_or(WindowsKeyboardLayout::unknown()),
547+ )
548+ }
549+
550+ fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
551+ Rc::new(WindowsKeyboardMapper::new())
552+ }
553+
554+ fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
555+ self.inner
556+ .state
557+ .callbacks
558+ .keyboard_layout_change
559+ .set(Some(callback));
560+ }
561+
562+ fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
563+
564+ fn thermal_state(&self) -> ThermalState {
565+ ThermalState::Nominal
566+ }
567+
568+ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
569+ Task::ready(
570+ PowerRequest::prevent_idle_sleep(reason)
571+ .map(|request| ActivityGuard::new(move || drop(request))),
572+ )
573+ }
574+
575+ fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
576+ if !self.headless {
577+ self.connect_initially();
578+ }
579+ on_finish_launching();
580+
581+ let mut msg = MSG::default();
582+ unsafe {
583+ while GetMessageW(&mut msg, None, 0, 0).as_bool() {
584+ if !self.inner.translate_accelerator(&msg) {
585+ _ = TranslateMessage(&msg);
586+ DispatchMessageW(&msg);
587+ }
588+ }
589+ }
590+
591+ self.inner.with_callback(
592+ |callbacks| &callbacks.quit,
593+ |callback| {
594+ callback();
595+ },
596+ );
597+ }
598+
599+ fn quit(&self) {
600+ self.foreground_executor()
601+ .spawn(async { unsafe { PostQuitMessage(0) } })
602+ .detach();
603+ }
604+
605+ fn set_initial_windowing(&self, request: WindowingRequest) {
606+ *self.initial_windowing.borrow_mut() = Some(request);
607+ }
608+
609+ fn request_windowing(&self, request: WindowingRequest) -> Task<Result<()>> {
610+ if self.headless {
611+ return Task::ready(Err(anyhow!(
612+ "a platform created headless can't switch windowing modes"
613+ )));
614+ }
615+ let windowed = self.is_windowed();
616+ Task::ready(match request {
617+ WindowingRequest::Headless if !windowed => Err(anyhow!("already headless")),
618+ WindowingRequest::Headless => {
619+ self.detach_gpu();
620+ Ok(())
621+ }
622+ WindowingRequest::Windowed(_) if windowed => Err(anyhow!("already windowed")),
623+ WindowingRequest::Windowed(environment) => {
624+ check_can_show_windows(&environment).and_then(|()| self.attach_gpu())
625+ }
626+ })
627+ }
628+
629+ fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
630+ self.is_windowed().then(GraphicalEnvironment::detect)
631+ }
632+
633+ fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>) {
634+ let pid = std::process::id();
635+ let Some(app_path) = binary_path.or(self.app_path().log_err()) else {
636+ return;
637+ };
638+ let script = r#"
639+ $pidToWaitFor = $env:ZED_RESTART_PID
640+ $exePath = $env:ZED_RESTART_EXECUTABLE
641+ $argumentList = $env:ZED_RESTART_ARGUMENTS
642+
643+ [Environment]::SetEnvironmentVariable("ZED_RESTART_PID", $null)
644+ [Environment]::SetEnvironmentVariable("ZED_RESTART_EXECUTABLE", $null)
645+ [Environment]::SetEnvironmentVariable("ZED_RESTART_ARGUMENTS", $null)
646+
647+ while ($true) {
648+ $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue
649+ if (-not $process) {
650+ if ([string]::IsNullOrEmpty($argumentList)) {
651+ Start-Process -FilePath $exePath
652+ } else {
653+ Start-Process -FilePath $exePath -ArgumentList $argumentList
654+ }
655+ break
656+ }
657+ Start-Sleep -Seconds 0.1
658+ }
659+ "#;
660+
661+ // Defer spawning to the foreground executor so it runs after the
662+ // current `AppCell` borrow is released. On Windows, `Command::spawn()`
663+ // can pump the Win32 message loop (via `CreateProcessW`), which
664+ // re-enters message handling possibly resulting in another mutable
665+ // borrow of the `AppCell` ending up with a double borrow panic
666+ let Some(powershell) = get_powershell() else {
667+ log::error!("failed to restart: PowerShell is unavailable");
668+ return;
669+ };
670+ self.foreground_executor
671+ .spawn(async move {
672+ let mut command = new_std_command(powershell);
673+ let arguments = encode_restart_arguments(&arguments);
674+ command
675+ .arg("-command")
676+ .arg(script)
677+ .env("ZED_RESTART_PID", pid.to_string())
678+ .env("ZED_RESTART_EXECUTABLE", app_path)
679+ .env("ZED_RESTART_ARGUMENTS", arguments);
680+ #[allow(
681+ clippy::disallowed_methods,
682+ reason = "We are restarting ourselves, using std command thus is fine"
683+ )]
684+ let restart_process = command.spawn();
685+
686+ match restart_process {
687+ Ok(_) => unsafe { PostQuitMessage(0) },
688+ Err(e) => log::error!("failed to spawn restart script: {:?}", e),
689+ }
690+ })
691+ .detach();
692+ }
693+
694+ fn activate(&self, _ignoring_other_apps: bool) {}
695+
696+ fn hide(&self) {}
697+
698+ // todo(windows)
699+ fn hide_other_apps(&self) {
700+ unimplemented!()
701+ }
702+
703+ // todo(windows)
704+ fn unhide_other_apps(&self) {
705+ unimplemented!()
706+ }
707+
708+ fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
709+ WindowsDisplay::displays()
710+ }
711+
712+ fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
713+ WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
714+ }
715+
716+ fn on_displays_changed(&self, callback: Box<dyn FnMut()>) {
717+ self.inner
718+ .state
719+ .callbacks
720+ .displays_changed
721+ .set(Some(callback));
722+ }
723+
724+ #[cfg(feature = "screen-capture")]
725+ fn is_screen_capture_supported(&self) -> bool {
726+ true
727+ }
728+
729+ #[cfg(feature = "screen-capture")]
730+ fn screen_capture_sources(
731+ &self,
732+ ) -> futures::channel::oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
733+ gpui::scap_screen_capture::scap_screen_sources(&self.foreground_executor)
734+ }
735+
736+ fn active_window(&self) -> Option<AnyWindowHandle> {
737+ let active_window_hwnd = unsafe { GetActiveWindow() };
738+ self.window_from_hwnd(active_window_hwnd)
739+ .map(|inner| inner.handle)
740+ }
741+
742+ fn open_window(
743+ &self,
744+ handle: AnyWindowHandle,
745+ options: WindowParams,
746+ ) -> Result<Box<dyn PlatformWindow>> {
747+ if !self.is_windowed() {
748+ return Err(anyhow!("cannot open windows while headless"));
749+ }
750+ let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
751+ let handle = window.get_raw_handle();
752+ self.raw_window_handles.write().push(TrackedWindow {
753+ handle: handle.into(),
754+ frame_signal: window.state.frame_signal.clone(),
755+ });
756+
757+ Ok(Box::new(window))
758+ }
759+
760+ fn window_appearance(&self) -> WindowAppearance {
761+ system_appearance().log_err().unwrap_or_default()
762+ }
763+
764+ fn open_url(&self, url: &str) {
765+ if url.is_empty() {
766+ return;
767+ }
768+ let url_string = url.to_string();
769+ self.background_executor()
770+ .spawn(async move {
771+ open_target(&url_string)
772+ .with_context(|| format!("Opening url: {}", url_string))
773+ .log_err();
774+ })
775+ .detach();
776+ }
777+
778+ fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
779+ self.inner.state.callbacks.open_urls.set(Some(callback));
780+ }
781+
782+ fn prompt_for_paths(
783+ &self,
784+ options: PathPromptOptions,
785+ ) -> Receiver<Result<Option<Vec<PathBuf>>>> {
786+ let owner = self
787+ .find_current_active_window()
788+ .and_then(|hwnd| self.window_from_hwnd(hwnd))
789+ .map(|window| window.dialog_owner.clone());
790+ crate::dialog::show_dialog(owner, &self.foreground_executor, move |window| {
791+ file_open_dialog(options, Some(window))
792+ })
793+ }
794+
795+ fn prompt_for_new_path(
796+ &self,
797+ directory: &Path,
798+ suggested_name: Option<&str>,
799+ ) -> Receiver<Result<Option<PathBuf>>> {
800+ let directory = directory.to_owned();
801+ let suggested_name = suggested_name.map(|s| s.to_owned());
802+ let owner = self
803+ .find_current_active_window()
804+ .and_then(|hwnd| self.window_from_hwnd(hwnd))
805+ .map(|window| window.dialog_owner.clone());
806+ crate::dialog::show_dialog(owner, &self.foreground_executor, move |window| {
807+ file_save_dialog(directory, suggested_name, Some(window))
808+ })
809+ }
810+
811+ fn can_select_mixed_files_and_dirs(&self) -> bool {
812+ // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".
813+ false
814+ }
815+
816+ fn reveal_path(&self, path: &Path) {
817+ if path.as_os_str().is_empty() {
818+ return;
819+ }
820+ let path = path.to_path_buf();
821+ self.background_executor()
822+ .spawn(async move {
823+ open_target_in_explorer(&path)
824+ .with_context(|| format!("Revealing path {} in explorer", path.display()))
825+ .log_err();
826+ })
827+ .detach();
828+ }
829+
830+ fn open_with_system(&self, path: &Path) {
831+ if path.as_os_str().is_empty() {
832+ return;
833+ }
834+ let path = path.to_path_buf();
835+ self.background_executor()
836+ .spawn(async move {
837+ open_target(&path)
838+ .with_context(|| format!("Opening {} with system", path.display()))
839+ .log_err();
840+ })
841+ .detach();
842+ }
843+
844+ fn on_quit(&self, callback: Box<dyn FnMut() -> bool>) {
845+ self.inner.state.callbacks.quit.set(Some(callback));
846+ }
847+
848+ fn on_reopen(&self, callback: Box<dyn FnMut()>) {
849+ self.inner.state.callbacks.reopen.set(Some(callback));
850+ }
851+
852+ fn on_system_sleep(&self, callback: Box<dyn FnMut()>) {
853+ self.inner.state.callbacks.system_sleep.set(Some(callback));
854+ }
855+
856+ fn on_system_wake(&self, callback: Box<dyn FnMut()>) {
857+ self.inner.state.callbacks.system_wake.set(Some(callback));
858+ let mut notification = self.suspend_resume_notification.borrow_mut();
859+ if notification.is_none() {
860+ *notification = unsafe {
861+ // SAFETY: self.handle is the platform window receiving WM_POWERBROADCAST.
862+ RegisterSuspendResumeNotification(
863+ HANDLE(self.handle.0),
864+ DEVICE_NOTIFY_WINDOW_HANDLE,
865+ )
866+ .log_err()
867+ };
868+ }
869+ }
870+
871+ fn power_mode(&self) -> PowerMode {
872+ if self.inner.state.low_power_mode_enabled.get() {
873+ PowerMode::LowPower
874+ } else {
875+ PowerMode::HighPower
876+ }
877+ }
878+
879+ fn on_power_mode_change(&self, callback: Box<dyn FnMut()>) {
880+ self.inner
881+ .state
882+ .callbacks
883+ .low_power_mode_change
884+ .set(Some(callback));
885+ let mut notification = self.power_saving_notification.borrow_mut();
886+ if notification.is_none() {
887+ *notification = unsafe {
888+ RegisterPowerSettingNotification(
889+ HANDLE(self.handle.0),
890+ &GUID_POWER_SAVING_STATUS,
891+ DEVICE_NOTIFY_WINDOW_HANDLE,
892+ )
893+ .log_err()
894+ };
895+ }
896+ }
897+
898+ fn set_app_identity(&self, identifier: &str, name: &str) {
899+ // If the process has package identity, it's automatally granted an AUMID by the system.
900+ if self.has_package_identity {
901+ return;
902+ }
903+
904+ let identifier_utf16 = windows::core::HSTRING::from(identifier);
905+ // SAFETY: `identifier_utf16` outlives the call and is null-terminated.
906+ if let Err(error) = unsafe {
907+ windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(
908+ windows::core::PCWSTR(identifier_utf16.as_ptr()),
909+ )
910+ } {
911+ log::warn!("failed to set the process AppUserModelID: {error}");
912+ }
913+ *self.app_identity.borrow_mut() = Some((identifier.to_string(), name.to_string()));
914+ }
915+
916+ fn show_system_notification(&self, notification: gpui::SystemNotification) {
917+ let app_identity = self.app_identity.borrow().clone();
918+ self.system_notifications
919+ .borrow_mut()
920+ .show(
921+ self.has_package_identity,
922+ app_identity
923+ .as_ref()
924+ .map(|(identifier, name)| (identifier.as_str(), name.as_str())),
925+ notification,
926+ )
927+ .log_err();
928+ }
929+
930+ fn dismiss_system_notification(&self, tag: &str) -> Task<()> {
931+ self.system_notifications.borrow_mut().dismiss(tag);
932+ Task::ready(())
933+ }
934+
935+ fn on_system_notification_response(
936+ &self,
937+ callback: Box<dyn FnMut(gpui::SystemNotificationResponse)>,
938+ ) {
939+ self.system_notifications
940+ .borrow_mut()
941+ .on_response(&self.foreground_executor, callback);
942+ }
943+
944+ fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
945+ *self.inner.state.menus.borrow_mut() = menus.into_iter().map(|menu| menu.owned()).collect();
946+ }
947+
948+ fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
949+ Some(self.inner.state.menus.borrow().clone())
950+ }
951+
952+ fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {
953+ self.set_dock_menus(menus);
954+ }
955+
956+ fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
957+ self.inner
958+ .state
959+ .callbacks
960+ .app_menu_action
961+ .set(Some(callback));
962+ }
963+
964+ fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
965+ self.inner
966+ .state
967+ .callbacks
968+ .will_open_app_menu
969+ .set(Some(callback));
970+ }
971+
972+ fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
973+ self.inner
974+ .state
975+ .callbacks
976+ .validate_app_menu_command
977+ .set(Some(callback));
978+ }
979+
980+ fn app_path(&self) -> Result<PathBuf> {
981+ Ok(std::env::current_exe()?)
982+ }
983+
984+ // todo(windows)
985+ fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
986+ anyhow::bail!("not yet implemented");
987+ }
988+
989+ fn set_cursor_style(&self, style: CursorStyle) {
990+ let hcursor = load_cursor(style);
991+ if self.inner.state.current_cursor.get().map(|c| c.0) != hcursor.map(|c| c.0) {
992+ self.post_message(
993+ WM_GPUI_CURSOR_STYLE_CHANGED,
994+ WPARAM(self.inner.validation_number),
995+ LPARAM(hcursor.map_or(0, |c| c.0 as isize)),
996+ );
997+ self.inner.state.current_cursor.set(hcursor);
998+ }
999+ }
1000+
1001+ fn hide_cursor_until_mouse_moves(&self) {
1002+ if !self
1003+ .inner
1004+ .state
1005+ .cursor_visible
1006+ .swap(false, Ordering::Relaxed)
1007+ {
1008+ return;
1009+ }
1010+
1011+ for handle in self.raw_window_handles.read().iter() {
1012+ let Some(window) = window_from_hwnd(handle.as_raw()) else {
1013+ continue;
1014+ };
1015+ if window.state.hovered.get() {
1016+ unsafe { SetCursor(None) };
1017+ break;
1018+ }
1019+ }
1020+ }
1021+
1022+ fn is_cursor_visible(&self) -> bool {
1023+ self.inner.state.cursor_visible.load(Ordering::Relaxed)
1024+ }
1025+
1026+ fn should_auto_hide_scrollbars(&self) -> bool {
1027+ should_auto_hide_scrollbars().log_err().unwrap_or(false)
1028+ }
1029+
1030+ fn write_to_clipboard(&self, item: ClipboardItem) {
1031+ write_to_clipboard(item);
1032+ }
1033+
1034+ fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1035+ read_from_clipboard()
1036+ }
1037+
1038+ fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1039+ // CredWriteW rejects larger blobs with the opaque RPC error
1040+ // 0x800706F7 "The stub received bad data", so fail with a clear
1041+ // message instead.
1042+ if password.len() > CRED_MAX_CREDENTIAL_BLOB_SIZE as usize {
1043+ return Task::ready(Err(anyhow!(
1044+ "credential for {url} is {} bytes, which exceeds the Windows Credential Manager limit of {CRED_MAX_CREDENTIAL_BLOB_SIZE} bytes",
1045+ password.len()
1046+ )));
1047+ }
1048+ let password = password.to_vec();
1049+ let mut username = username.encode_utf16().chain(Some(0)).collect_vec();
1050+ let mut target_name = windows_credentials_target_name(url)
1051+ .encode_utf16()
1052+ .chain(Some(0))
1053+ .collect_vec();
1054+ self.background_executor().spawn(async move {
1055+ let credentials = CREDENTIALW {
1056+ LastWritten: unsafe { GetSystemTimeAsFileTime() },
1057+ Flags: CRED_FLAGS(0),
1058+ Type: CRED_TYPE_GENERIC,
1059+ TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
1060+ CredentialBlobSize: password.len() as u32,
1061+ CredentialBlob: password.as_ptr() as *mut _,
1062+ Persist: CRED_PERSIST_LOCAL_MACHINE,
1063+ UserName: PWSTR::from_raw(username.as_mut_ptr()),
1064+ ..CREDENTIALW::default()
1065+ };
1066+ unsafe {
1067+ CredWriteW(&credentials, 0).map_err(|err| {
1068+ anyhow!(
1069+ "Failed to write credentials to Windows Credential Manager: {}",
1070+ err,
1071+ )
1072+ })?;
1073+ }
1074+ Ok(())
1075+ })
1076+ }
1077+
1078+ fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1079+ let target_name = windows_credentials_target_name(url)
1080+ .encode_utf16()
1081+ .chain(Some(0))
1082+ .collect_vec();
1083+ self.background_executor().spawn(async move {
1084+ let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
1085+ let result = unsafe {
1086+ CredReadW(
1087+ PCWSTR::from_raw(target_name.as_ptr()),
1088+ CRED_TYPE_GENERIC,
1089+ None,
1090+ &mut credentials,
1091+ )
1092+ };
1093+
1094+ if let Err(err) = result {
1095+ // ERROR_NOT_FOUND means the credential doesn't exist.
1096+ // Return Ok(None) to match macOS and Linux behavior.
1097+ if err.code() == ERROR_NOT_FOUND.to_hresult() {
1098+ return Ok(None);
1099+ }
1100+ return Err(err.into());
1101+ }
1102+
1103+ if credentials.is_null() {
1104+ return Ok(None);
1105+ }
1106+
1107+ // SAFETY: `CredReadW` succeeded, so this points to a valid `CREDENTIALW` until `CredFree` below.
1108+ let result = unsafe { username_and_password(&*credentials) };
1109+ unsafe { CredFree(credentials as *const _ as _) };
1110+ result.map(Some)
1111+ })
1112+ }
1113+
1114+ fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1115+ let target_name = windows_credentials_target_name(url)
1116+ .encode_utf16()
1117+ .chain(Some(0))
1118+ .collect_vec();
1119+ self.background_executor().spawn(async move {
1120+ unsafe {
1121+ CredDeleteW(
1122+ PCWSTR::from_raw(target_name.as_ptr()),
1123+ CRED_TYPE_GENERIC,
1124+ None,
1125+ )?
1126+ };
1127+ Ok(())
1128+ })
1129+ }
1130+
1131+ fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
1132+ Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
1133+ }
1134+
1135+ fn perform_dock_menu_action(&self, action: usize) {
1136+ unsafe {
1137+ PostMessageW(
1138+ Some(self.handle),
1139+ WM_GPUI_DOCK_MENU_ACTION,
1140+ WPARAM(self.inner.validation_number),
1141+ LPARAM(action as isize),
1142+ )
1143+ .log_err();
1144+ }
1145+ }
1146+
1147+ fn update_jump_list(
1148+ &self,
1149+ menus: Vec<MenuItem>,
1150+ entries: Vec<SmallVec<[PathBuf; 2]>>,
1151+ ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
1152+ self.update_jump_list(menus, entries)
1153+ }
1154+}
1155+
1156+impl WindowsPlatformInner {
1157+ fn new(context: &mut PlatformWindowCreateContext) -> Result<Rc<Self>> {
1158+ let state = WindowsPlatformState::new(context.directx_devices.take());
1159+ Ok(Rc::new(Self {
1160+ state,
1161+ raw_window_handles: context.raw_window_handles.clone(),
1162+ dispatcher: context
1163+ .dispatcher
1164+ .as_ref()
1165+ .context("missing dispatcher")?
1166+ .clone(),
1167+ validation_number: context.validation_number,
1168+ main_receiver: context
1169+ .main_receiver
1170+ .take()
1171+ .context("missing main receiver")?,
1172+ }))
1173+ }
1174+
1175+ fn window_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
1176+ self.raw_window_handles
1177+ .upgrade()?
1178+ .read()
1179+ .iter()
1180+ .find(|window| window.as_raw() == hwnd)
1181+ .and_then(|window| window_from_hwnd(window.as_raw()))
1182+ }
1183+
1184+ fn translate_accelerator(&self, msg: &MSG) -> bool {
1185+ if msg.message != WM_KEYDOWN && msg.message != WM_SYSKEYDOWN {
1186+ return false;
1187+ }
1188+
1189+ self.window_from_hwnd(msg.hwnd)
1190+ .is_some_and(|window| window.handle_keydown_msg(msg.wParam, msg.lParam) == Some(0))
1191+ }
1192+
1193+ /// Calls `project` to project to the corresponding callback field, removes it from callbacks, calls `f` with the callback and then puts the callback back.
1194+ fn with_callback<T>(
1195+ &self,
1196+ project: impl Fn(&PlatformCallbacks) -> &Cell<Option<T>>,
1197+ f: impl FnOnce(&mut T),
1198+ ) {
1199+ let callback = project(&self.state.callbacks).take();
1200+ if let Some(mut callback) = callback {
1201+ f(&mut callback);
1202+ project(&self.state.callbacks).set(Some(callback));
1203+ }
1204+ }
1205+
1206+ fn handle_msg(
1207+ self: &Rc<Self>,
1208+ handle: HWND,
1209+ msg: u32,
1210+ wparam: WPARAM,
1211+ lparam: LPARAM,
1212+ ) -> LRESULT {
1213+ let handled = match msg {
1214+ WM_GPUI_CLOSE_ONE_WINDOW
1215+ | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD
1216+ | WM_GPUI_DOCK_MENU_ACTION
1217+ | WM_GPUI_KEYBOARD_LAYOUT_CHANGED
1218+ | WM_GPUI_DISPLAYS_CHANGED
1219+ | WM_GPUI_GPU_DEVICE_LOST => self.handle_gpui_events(msg, wparam, lparam),
1220+ WM_POWERBROADCAST => self.handle_power_broadcast(wparam, lparam),
1221+ WM_DISPLAYCHANGE => self.handle_display_change(handle),
1222+ WM_QUERYENDSESSION => Some(1),
1223+ WM_ENDSESSION if wparam.0 != 0 => self.handle_end_session(),
1224+ _ => None,
1225+ };
1226+ if let Some(result) = handled {
1227+ LRESULT(result)
1228+ } else {
1229+ unsafe { DefWindowProcW(handle, msg, wparam, lparam) }
1230+ }
1231+ }
1232+
1233+ fn handle_gpui_events(&self, message: u32, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
1234+ if wparam.0 != self.validation_number {
1235+ log::error!("Wrong validation number while processing message: {message}");
1236+ return None;
1237+ }
1238+ match message {
1239+ WM_GPUI_CLOSE_ONE_WINDOW => {
1240+ self.close_one_window(HWND(lparam.0 as _));
1241+ Some(0)
1242+ }
1243+ WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),
1244+ WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),
1245+ WM_GPUI_KEYBOARD_LAYOUT_CHANGED => self.handle_keyboard_layout_change(),
1246+ WM_GPUI_DISPLAYS_CHANGED => self.handle_displays_changed(),
1247+ WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),
1248+ _ => unreachable!(),
1249+ }
1250+ }
1251+
1252+ fn handle_display_change(&self, handle: HWND) -> Option<isize> {
1253+ // Broadcasts can be delivered while the app is mid-update, e.g. inside a
1254+ // COM call, so report the change from the message loop instead.
1255+ unsafe {
1256+ PostMessageW(
1257+ Some(handle),
1258+ WM_GPUI_DISPLAYS_CHANGED,
1259+ WPARAM(self.validation_number),
1260+ LPARAM(0),
1261+ )
1262+ .log_err();
1263+ }
1264+ Some(0)
1265+ }
1266+
1267+ fn handle_displays_changed(&self) -> Option<isize> {
1268+ self.with_callback(
1269+ |callbacks| &callbacks.displays_changed,
1270+ |callback| callback(),
1271+ );
1272+ Some(0)
1273+ }
1274+
1275+ fn handle_end_session(&self) -> Option<isize> {
1276+ let mut shutdown_completed = false;
1277+ self.with_callback(
1278+ |callbacks| &callbacks.quit,
1279+ |callback| shutdown_completed = callback(),
1280+ );
1281+ log::logger().flush();
1282+ if shutdown_completed {
1283+ std::process::exit(0);
1284+ }
1285+
1286+ // Shutdown couldn't run synchronously, since the AppCell is already borrowed.
1287+ // Windows may terminate the application as soon as we return from this handler, but if we post a WM_QUIT message now,
1288+ // we may get to gracefully shut down the app before we're terminated by the OS.
1289+ unsafe { PostQuitMessage(0) };
1290+ Some(0)
1291+ }
1292+
1293+ fn close_one_window(&self, target_window: HWND) -> bool {
1294+ let Some(all_windows) = self.raw_window_handles.upgrade() else {
1295+ log::error!("Failed to upgrade raw window handles");
1296+ return false;
1297+ };
1298+ let mut lock = all_windows.write();
1299+ let index = lock
1300+ .iter()
1301+ .position(|handle| handle.as_raw() == target_window)
1302+ .unwrap();
1303+ lock.remove(index);
1304+
1305+ lock.is_empty()
1306+ }
1307+
1308+ #[inline]
1309+ fn run_foreground_task(&self) -> Option<isize> {
1310+ const MAIN_TASK_TIMEOUT: u128 = 10;
1311+
1312+ let start = std::time::Instant::now();
1313+ 'tasks: loop {
1314+ 'timeout_loop: loop {
1315+ if start.elapsed().as_millis() >= MAIN_TASK_TIMEOUT {
1316+ log::debug!("foreground task timeout reached");
1317+ // we spent our budget on gpui tasks, we likely have a lot of work queued so drain system events first to stay responsive
1318+ // then quit out of foreground work to allow us to process other gpui events first before returning back to foreground task work
1319+ // if we don't we might not for example process window quit events
1320+ let mut msg = MSG::default();
1321+ let process_message = |msg: &_| {
1322+ if !self.translate_accelerator(msg) {
1323+ _ = unsafe { TranslateMessage(msg) };
1324+ unsafe { DispatchMessageW(msg) };
1325+ }
1326+ };
1327+ let peek_msg = |msg: &mut _, msg_kind| unsafe {
1328+ PeekMessageW(msg, None, 0, 0, PM_REMOVE | msg_kind).as_bool()
1329+ };
1330+ // We need to process a paint message here as otherwise we will re-enter `run_foreground_task` before painting if we have work remaining.
1331+ // The reason for this is that windows prefers custom application message processing over system messages.
1332+ if peek_msg(&mut msg, PM_QS_PAINT) {
1333+ process_message(&msg);
1334+ }
1335+ while peek_msg(&mut msg, PM_QS_INPUT) {
1336+ process_message(&msg);
1337+ }
1338+ // Allow the main loop to process other gpui events before going back into `run_foreground_task`
1339+ unsafe {
1340+ if let Err(_) = PostMessageW(
1341+ Some(self.dispatcher.platform_window_handle.as_raw()),
1342+ WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
1343+ WPARAM(self.validation_number),
1344+ LPARAM(0),
1345+ ) {
1346+ self.dispatcher.wake_posted.store(false, Ordering::Release);
1347+ };
1348+ }
1349+ break 'tasks;
1350+ }
1351+ let mut main_receiver = self.main_receiver.clone();
1352+ match main_receiver.try_pop() {
1353+ Ok(Some(runnable)) => WindowsDispatcher::execute_runnable(runnable),
1354+ _ => break 'timeout_loop,
1355+ }
1356+ }
1357+
1358+ // Someone could enqueue a Runnable here. The flag is still true, so they will not PostMessage.
1359+ // We need to check for those Runnables after we clear the flag.
1360+ self.dispatcher.wake_posted.store(false, Ordering::Release);
1361+ let mut main_receiver = self.main_receiver.clone();
1362+ match main_receiver.try_pop() {
1363+ Ok(Some(runnable)) => {
1364+ self.dispatcher.wake_posted.store(true, Ordering::Release);
1365+
1366+ WindowsDispatcher::execute_runnable(runnable);
1367+ }
1368+ _ => break 'tasks,
1369+ }
1370+ }
1371+
1372+ Some(0)
1373+ }
1374+
1375+ fn handle_dock_action_event(&self, action_idx: usize) -> Option<isize> {
1376+ let Some(action) = self
1377+ .state
1378+ .jump_list
1379+ .borrow()
1380+ .dock_menus
1381+ .get(action_idx)
1382+ .map(|dock_menu| dock_menu.action.boxed_clone())
1383+ else {
1384+ log::error!("Dock menu for index {action_idx} not found");
1385+ return Some(1);
1386+ };
1387+ self.with_callback(
1388+ |callbacks| &callbacks.app_menu_action,
1389+ |callback| callback(&*action),
1390+ );
1391+ Some(0)
1392+ }
1393+
1394+ fn handle_keyboard_layout_change(&self) -> Option<isize> {
1395+ self.with_callback(
1396+ |callbacks| &callbacks.keyboard_layout_change,
1397+ |callback| callback(),
1398+ );
1399+ Some(0)
1400+ }
1401+
1402+ fn handle_power_broadcast(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {
1403+ match wparam.0 as u32 {
1404+ PBT_APMSUSPEND => {
1405+ self.with_callback(|callbacks| &callbacks.system_sleep, |callback| callback());
1406+ }
1407+ PBT_APMRESUMEAUTOMATIC => {
1408+ self.with_callback(|callbacks| &callbacks.system_wake, |callback| callback());
1409+ }
1410+ PBT_POWERSETTINGCHANGE => {
1411+ if let Some(enabled) = unsafe { power_saving_status(lparam) } {
1412+ if self.state.low_power_mode_enabled.replace(enabled) != enabled {
1413+ self.with_callback(
1414+ |callbacks| &callbacks.low_power_mode_change,
1415+ |callback| callback(),
1416+ );
1417+ }
1418+ }
1419+ }
1420+ _ => {}
1421+ }
1422+ Some(1)
1423+ }
1424+
1425+ fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
1426+ let directx_devices = lparam.0 as *const DirectXDevices;
1427+ let directx_devices = unsafe { &*directx_devices };
1428+ let mut current = self.state.directx_devices.borrow_mut();
1429+ // The platform may have switched to headless while the device was being recovered.
1430+ if current.is_some() {
1431+ *current = Some(directx_devices.clone());
1432+ }
1433+
1434+ Some(0)
1435+ }
1436+}
1437+
1438+unsafe fn power_saving_status(lparam: LPARAM) -> Option<bool> {
1439+ let setting = unsafe { (lparam.0 as *const POWERBROADCAST_SETTING).as_ref()? };
1440+ if setting.PowerSetting != GUID_POWER_SAVING_STATUS || setting.DataLength != 4 {
1441+ return None;
1442+ }
1443+ let data = unsafe {
1444+ std::ptr::addr_of!(setting.Data)
1445+ .cast::<u32>()
1446+ .read_unaligned()
1447+ };
1448+ match data {
1449+ 0 => Some(false),
1450+ 1 => Some(true),
1451+ _ => None,
1452+ }
1453+}
1454+
1455+impl Drop for WindowsPlatform {
1456+ fn drop(&mut self) {
1457+ if let Some(stop) = self.vsync_stop.borrow_mut().take() {
1458+ stop.store(true, Ordering::Release);
1459+ }
1460+ unsafe {
1461+ if let Some(notification) = self.suspend_resume_notification.borrow_mut().take() {
1462+ // SAFETY: notification was returned by RegisterSuspendResumeNotification.
1463+ UnregisterSuspendResumeNotification(notification).log_err();
1464+ }
1465+ if let Some(notification) = self.power_saving_notification.borrow_mut().take() {
1466+ UnregisterPowerSettingNotification(notification).log_err();
1467+ }
1468+ DestroyWindow(self.handle)
1469+ .context("Destroying platform window")
1470+ .log_err();
1471+ OleUninitialize();
1472+ }
1473+ }
1474+}
1475+
1476+pub(crate) struct WindowCreationInfo {
1477+ pub(crate) icon: HICON,
1478+ pub(crate) executor: ForegroundExecutor,
1479+ pub(crate) current_cursor: Option<HCURSOR>,
1480+ pub(crate) cursor_visible: Arc<AtomicBool>,
1481+ pub(crate) drop_target_helper: IDropTargetHelper,
1482+ pub(crate) validation_number: usize,
1483+ pub(crate) main_receiver: PriorityQueueReceiver<RunnableVariant>,
1484+ pub(crate) platform_window_handle: HWND,
1485+ pub(crate) disable_direct_composition: bool,
1486+ pub(crate) directx_devices: DirectXDevices,
1487+ /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
1488+ /// as resizing them has failed, causing us to have lost at least the render target.
1489+ pub(crate) invalidate_devices: Arc<AtomicBool>,
1490+ /// Shared with [`WindowsPlatformState::draw_coordinator`] and every other window.
1491+ pub(crate) draw_coordinator: Rc<DrawCoordinator>,
1492+}
1493+
1494+struct PlatformWindowCreateContext {
1495+ inner: Option<Result<Rc<WindowsPlatformInner>>>,
1496+ raw_window_handles: std::sync::Weak<RwLock<SmallVec<[TrackedWindow; 4]>>>,
1497+ validation_number: usize,
1498+ main_sender: Option<PriorityQueueSender<RunnableVariant>>,
1499+ main_receiver: Option<PriorityQueueReceiver<RunnableVariant>>,
1500+ directx_devices: Option<DirectXDevices>,
1501+ dispatcher: Option<Arc<WindowsDispatcher>>,
1502+}
1503+
1504+fn has_package_identity() -> bool {
1505+ let mut package_full_name_length = 0;
1506+ let result = unsafe {
1507+ windows::Win32::Storage::Packaging::Appx::GetCurrentPackageFullName(
1508+ &mut package_full_name_length,
1509+ None,
1510+ )
1511+ };
1512+ if result == ERROR_INSUFFICIENT_BUFFER {
1513+ true
1514+ } else if result == APPMODEL_ERROR_NO_PACKAGE {
1515+ false
1516+ } else {
1517+ log::warn!("failed to determine whether the process has package identity: {result:?}");
1518+ false
1519+ }
1520+}
1521+
1522+fn open_target(target: impl AsRef<OsStr>) -> Result<()> {
1523+ let target = target.as_ref();
1524+ let ret = unsafe {
1525+ ShellExecuteW(
1526+ None,
1527+ windows::core::w!("open"),
1528+ &HSTRING::from(target),
1529+ None,
1530+ None,
1531+ SW_SHOWDEFAULT,
1532+ )
1533+ };
1534+ if ret.0 as isize <= 32 {
1535+ Err(anyhow::anyhow!(
1536+ "Unable to open target: {}",
1537+ std::io::Error::last_os_error()
1538+ ))
1539+ } else {
1540+ Ok(())
1541+ }
1542+}
1543+
1544+fn open_target_in_explorer(target: &Path) -> Result<()> {
1545+ let dir = target.parent().context("No parent folder found")?;
1546+ let desktop = unsafe { SHGetDesktopFolder()? };
1547+
1548+ let mut dir_item = std::ptr::null_mut();
1549+ unsafe {
1550+ desktop.ParseDisplayName(
1551+ HWND::default(),
1552+ None,
1553+ &HSTRING::from(dir),
1554+ None,
1555+ &mut dir_item,
1556+ std::ptr::null_mut(),
1557+ )?;
1558+ }
1559+
1560+ let mut file_item = std::ptr::null_mut();
1561+ unsafe {
1562+ desktop.ParseDisplayName(
1563+ HWND::default(),
1564+ None,
1565+ &HSTRING::from(target),
1566+ None,
1567+ &mut file_item,
1568+ std::ptr::null_mut(),
1569+ )?;
1570+ }
1571+
1572+ let highlight = [file_item as *const _];
1573+ unsafe { SHOpenFolderAndSelectItems(dir_item as _, Some(&highlight), 0) }.or_else(|err| {
1574+ if err.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {
1575+ // On some systems, the above call mysteriously fails with "file not
1576+ // found" even though the file is there. In these cases, ShellExecute()
1577+ // seems to work as a fallback (although it won't select the file).
1578+ open_target(dir).context("Opening target parent folder")
1579+ } else {
1580+ Err(anyhow::anyhow!("Can not open target path: {}", err))
1581+ }
1582+ })
1583+}
1584+
1585+fn file_open_dialog(
1586+ options: PathPromptOptions,
1587+ window: Option<HWND>,
1588+) -> Result<Option<Vec<PathBuf>>> {
1589+ let folder_dialog: IFileOpenDialog =
1590+ unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };
1591+
1592+ let mut dialog_options = FOS_FILEMUSTEXIST;
1593+ if options.multiple {
1594+ dialog_options |= FOS_ALLOWMULTISELECT;
1595+ }
1596+ if options.directories {
1597+ dialog_options |= FOS_PICKFOLDERS;
1598+ }
1599+
1600+ unsafe {
1601+ folder_dialog.SetOptions(dialog_options)?;
1602+
1603+ if let Some(prompt) = options.prompt {
1604+ let prompt: &str = &prompt;
1605+ folder_dialog.SetOkButtonLabel(&HSTRING::from(prompt))?;
1606+ }
1607+
1608+ if let Err(error) = folder_dialog.Show(window) {
1609+ if error.code() == HRESULT::from_win32(ERROR_CANCELLED.0) {
1610+ return Ok(None);
1611+ }
1612+ return Err(error.into());
1613+ }
1614+ }
1615+
1616+ let results = unsafe { folder_dialog.GetResults()? };
1617+ let file_count = unsafe { results.GetCount()? };
1618+ if file_count == 0 {
1619+ return Ok(None);
1620+ }
1621+
1622+ let mut paths = Vec::with_capacity(file_count as usize);
1623+ for i in 0..file_count {
1624+ let item = unsafe { results.GetItemAt(i)? };
1625+ let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };
1626+ paths.push(PathBuf::from(path));
1627+ }
1628+
1629+ Ok(Some(paths))
1630+}
1631+
1632+fn file_save_dialog(
1633+ directory: PathBuf,
1634+ suggested_name: Option<String>,
1635+ window: Option<HWND>,
1636+) -> Result<Option<PathBuf>> {
1637+ let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
1638+ if !directory.to_string_lossy().is_empty()
1639+ && let Some(full_path) = directory
1640+ .canonicalize()
1641+ .context("failed to canonicalize directory")
1642+ .log_err()
1643+ {
1644+ let full_path = dunce::simplified(&full_path);
1645+ let full_path_string = full_path.display().to_string();
1646+ let path_item: IShellItem =
1647+ unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };
1648+ unsafe {
1649+ dialog
1650+ .SetFolder(&path_item)
1651+ .context("failed to set dialog folder")
1652+ .log_err()
1653+ };
1654+ }
1655+
1656+ if let Some(suggested_name) = suggested_name {
1657+ unsafe {
1658+ dialog
1659+ .SetFileName(&HSTRING::from(suggested_name))
1660+ .context("failed to set file name")
1661+ .log_err()
1662+ };
1663+ }
1664+
1665+ unsafe {
1666+ dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {
1667+ pszName: windows::core::w!("All files"),
1668+ pszSpec: windows::core::w!("*.*"),
1669+ }])?;
1670+ if let Err(error) = dialog.Show(window) {
1671+ if error.code() == HRESULT::from_win32(ERROR_CANCELLED.0) {
1672+ return Ok(None);
1673+ }
1674+ return Err(error.into());
1675+ }
1676+ }
1677+ let shell_item = unsafe { dialog.GetResult()? };
1678+ let file_path_string = unsafe {
1679+ let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;
1680+ let string = pwstr.to_string()?;
1681+ CoTaskMemFree(Some(pwstr.0 as _));
1682+ string
1683+ };
1684+ Ok(Some(PathBuf::from(file_path_string)))
1685+}
1686+
1687+fn load_icon() -> Result<HICON> {
1688+ let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };
1689+ let handle = unsafe {
1690+ LoadImageW(
1691+ Some(module.into()),
1692+ windows::core::PCWSTR(1 as _),
1693+ IMAGE_ICON,
1694+ 0,
1695+ 0,
1696+ LR_DEFAULTSIZE | LR_SHARED,
1697+ )
1698+ .context("unable to load icon file")?
1699+ };
1700+ Ok(HICON(handle.0))
1701+}
1702+
1703+#[inline]
1704+fn should_auto_hide_scrollbars() -> Result<bool> {
1705+ let ui_settings = UISettings::new()?;
1706+ Ok(ui_settings.AutoHideScrollBars()?)
1707+}
1708+
1709+fn check_device_lost(device: &ID3D11Device) -> bool {
1710+ let device_state = unsafe { device.GetDeviceRemovedReason() };
1711+ match device_state {
1712+ Ok(_) => false,
1713+ Err(err) => {
1714+ log::error!("DirectX device lost detected: {:?}", err);
1715+ true
1716+ }
1717+ }
1718+}
1719+
1720+/// Checks that this process can show windows in the session `environment` names.
1721+fn check_can_show_windows(environment: &GraphicalEnvironment) -> Result<()> {
1722+ let current = GraphicalEnvironment::detect().session_id;
1723+ if let (Some(requested), Some(current)) = (environment.session_id, current)
1724+ && requested != current
1725+ {
1726+ return Err(anyhow!(
1727+ "windows can only be shown in this process's session ({current}), not session \
1728+ {requested}"
1729+ ));
1730+ }
1731+ if !is_window_station_visible() {
1732+ return Err(anyhow!(
1733+ "this process's window station is not interactive, so it can't show windows"
1734+ ));
1735+ }
1736+ Ok(())
1737+}
1738+
1739+/// Whether this process's window station has a visible desktop. A service's, or an SSH login's,
1740+/// doesn't.
1741+fn is_window_station_visible() -> bool {
1742+ use windows::Win32::System::StationsAndDesktops::{
1743+ GetProcessWindowStation, GetUserObjectInformationW, UOI_FLAGS, USEROBJECTFLAGS,
1744+ };
1745+
1746+ let Ok(station) = (unsafe { GetProcessWindowStation() }) else {
1747+ return false;
1748+ };
1749+ let mut flags = USEROBJECTFLAGS::default();
1750+ // SAFETY: `flags` is valid for writes of the size passed.
1751+ let result = unsafe {
1752+ GetUserObjectInformationW(
1753+ HANDLE(station.0),
1754+ UOI_FLAGS,
1755+ Some(&mut flags as *mut USEROBJECTFLAGS as *mut std::ffi::c_void),
1756+ std::mem::size_of::<USEROBJECTFLAGS>() as u32,
1757+ None,
1758+ )
1759+ };
1760+ result.is_ok() && flags.dwFlags & WSF_VISIBLE as u32 != 0
1761+}
1762+
1763+fn handle_gpu_device_lost(
1764+ directx_devices: &mut DirectXDevices,
1765+ platform_window: HWND,
1766+ validation_number: usize,
1767+ all_windows: &std::sync::Weak<RwLock<SmallVec<[TrackedWindow; 4]>>>,
1768+) -> Result<()> {
1769+ // Here we wait a bit to ensure the system has time to recover from the device lost state.
1770+ // If we don't wait, the final drawing result will be blank.
1771+ std::thread::sleep(std::time::Duration::from_millis(350));
1772+
1773+ *directx_devices = try_to_recover_from_device_lost(|| {
1774+ DirectXDevices::new().context("Failed to recreate new DirectX devices after device lost")
1775+ })?;
1776+ log::info!("DirectX devices successfully recreated.");
1777+
1778+ let lparam = LPARAM(directx_devices as *const _ as _);
1779+ unsafe {
1780+ SendMessageW(
1781+ platform_window,
1782+ WM_GPUI_GPU_DEVICE_LOST,
1783+ Some(WPARAM(validation_number)),
1784+ Some(lparam),
1785+ );
1786+ }
1787+
1788+ if let Some(all_windows) = all_windows.upgrade() {
1789+ for window in all_windows.read().iter() {
1790+ unsafe {
1791+ SendMessageW(
1792+ window.as_raw(),
1793+ WM_GPUI_GPU_DEVICE_LOST,
1794+ Some(WPARAM(validation_number)),
1795+ Some(lparam),
1796+ );
1797+ }
1798+ }
1799+ std::thread::sleep(std::time::Duration::from_millis(200));
1800+ for window in all_windows.read().iter() {
1801+ unsafe {
1802+ SendMessageW(
1803+ window.as_raw(),
1804+ WM_GPUI_FORCE_UPDATE_WINDOW,
1805+ Some(WPARAM(validation_number)),
1806+ None,
1807+ );
1808+ }
1809+ }
1810+ }
1811+ Ok(())
1812+}
1813+
1814+const PLATFORM_WINDOW_CLASS_NAME: PCWSTR = w!("Zed::PlatformWindow");
1815+
1816+fn register_platform_window_class() {
1817+ let wc = WNDCLASSW {
1818+ lpfnWndProc: Some(window_procedure),
1819+ lpszClassName: PCWSTR(PLATFORM_WINDOW_CLASS_NAME.as_ptr()),
1820+ ..Default::default()
1821+ };
1822+ unsafe { RegisterClassW(&wc) };
1823+}
1824+
1825+unsafe extern "system" fn window_procedure(
1826+ hwnd: HWND,
1827+ msg: u32,
1828+ wparam: WPARAM,
1829+ lparam: LPARAM,
1830+) -> LRESULT {
1831+ if msg == WM_NCCREATE {
1832+ let params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1833+ let creation_context = params.lpCreateParams as *mut PlatformWindowCreateContext;
1834+ let creation_context = unsafe { &mut *creation_context };
1835+
1836+ let Some(main_sender) = creation_context.main_sender.take() else {
1837+ creation_context.inner = Some(Err(anyhow!("missing main sender")));
1838+ return LRESULT(0);
1839+ };
1840+ creation_context.dispatcher = Some(Arc::new(WindowsDispatcher::new(
1841+ main_sender,
1842+ hwnd,
1843+ creation_context.validation_number,
1844+ )));
1845+
1846+ return match WindowsPlatformInner::new(creation_context) {
1847+ Ok(inner) => {
1848+ let weak = Box::new(Rc::downgrade(&inner));
1849+ unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1850+ creation_context.inner = Some(Ok(inner));
1851+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1852+ }
1853+ Err(error) => {
1854+ creation_context.inner = Some(Err(error));
1855+ LRESULT(0)
1856+ }
1857+ };
1858+ }
1859+
1860+ let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsPlatformInner>;
1861+ if ptr.is_null() {
1862+ return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1863+ }
1864+ let inner = unsafe { &*ptr };
1865+ let result = if let Some(inner) = inner.upgrade() {
1866+ if cfg!(debug_assertions) {
1867+ let inner = std::panic::AssertUnwindSafe(inner);
1868+ match std::panic::catch_unwind(|| { inner }.handle_msg(hwnd, msg, wparam, lparam)) {
1869+ Ok(result) => result,
1870+ Err(_) => std::process::abort(),
1871+ }
1872+ } else {
1873+ inner.handle_msg(hwnd, msg, wparam, lparam)
1874+ }
1875+ } else {
1876+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1877+ };
1878+
1879+ if msg == WM_NCDESTROY {
1880+ unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1881+ unsafe { drop(Box::from_raw(ptr)) };
1882+ }
1883+
1884+ result
1885+}
1886+
1887+/// Copies the username and secret out of a credential returned by `CredReadW`.
1888+///
1889+/// Both `UserName` and `CredentialBlob` are optional in Credential Manager and
1890+/// come back as null pointers when absent, so they are treated as empty here.
1891+///
1892+/// # Safety
1893+///
1894+/// A non-null `UserName` must point to a NUL-terminated wide string and a
1895+/// non-null `CredentialBlob` must be readable for `CredentialBlobSize` bytes,
1896+/// as is the case for credentials returned by `CredReadW`.
1897+unsafe fn username_and_password(credential: &CREDENTIALW) -> Result<(String, Vec<u8>)> {
1898+ let username = if credential.UserName.is_null() {
1899+ String::new()
1900+ } else {
1901+ // SAFETY: guaranteed by the caller.
1902+ unsafe { credential.UserName.to_string()? }
1903+ };
1904+ let password = if credential.CredentialBlob.is_null() {
1905+ Vec::new()
1906+ } else {
1907+ // SAFETY: guaranteed by the caller.
1908+ unsafe {
1909+ std::slice::from_raw_parts(
1910+ credential.CredentialBlob,
1911+ credential.CredentialBlobSize as usize,
1912+ )
1913+ }
1914+ .to_vec()
1915+ };
1916+ Ok((username, password))
1917+}
1918+
1919+#[cfg(test)]
1920+mod tests {
1921+ use std::ffi::{OsStr, OsString};
1922+
1923+ use crate::clipboard::read_raw_clipboard_text;
1924+ use crate::{read_from_clipboard, write_to_clipboard};
1925+ use gpui::ClipboardItem;
1926+ use windows::Win32::Security::Credentials::{
1927+ CRED_PERSIST_SESSION, CRED_TYPE_GENERIC, CREDENTIALW, CredDeleteW, CredFree, CredReadW,
1928+ CredWriteW,
1929+ };
1930+ use windows::core::{PCWSTR, PWSTR};
1931+
1932+ use super::{encode_restart_arguments, username_and_password};
1933+
1934+ #[test]
1935+ fn test_read_credential_with_username() {
1936+ assert_eq!(
1937+ round_trip_credential(Some("alice"), b"secret"),
1938+ ("alice".to_string(), b"secret".to_vec())
1939+ );
1940+ }
1941+
1942+ #[test]
1943+ fn test_read_credential_without_username() {
1944+ assert_eq!(
1945+ round_trip_credential(None, b"secret"),
1946+ (String::new(), b"secret".to_vec())
1947+ );
1948+ }
1949+
1950+ fn round_trip_credential(username: Option<&str>, secret: &[u8]) -> (String, Vec<u8>) {
1951+ let mut target_name: Vec<u16> = format!(
1952+ "zed-test-{}-{}",
1953+ std::process::id(),
1954+ username.unwrap_or_default()
1955+ )
1956+ .encode_utf16()
1957+ .chain(Some(0))
1958+ .collect();
1959+ let mut username: Vec<u16> = username
1960+ .map(|username| username.encode_utf16().chain(Some(0)).collect())
1961+ .unwrap_or_default();
1962+ let mut secret = secret.to_vec();
1963+ let credential = CREDENTIALW {
1964+ Type: CRED_TYPE_GENERIC,
1965+ TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),
1966+ CredentialBlobSize: secret.len() as u32,
1967+ CredentialBlob: secret.as_mut_ptr(),
1968+ Persist: CRED_PERSIST_SESSION,
1969+ UserName: if username.is_empty() {
1970+ PWSTR::null()
1971+ } else {
1972+ PWSTR::from_raw(username.as_mut_ptr())
1973+ },
1974+ ..CREDENTIALW::default()
1975+ };
1976+ let target_name = PCWSTR::from_raw(target_name.as_ptr());
1977+ unsafe { CredWriteW(&credential, 0) }.unwrap();
1978+
1979+ let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();
1980+ unsafe { CredReadW(target_name, CRED_TYPE_GENERIC, None, &mut credentials) }.unwrap();
1981+ let result = unsafe { username_and_password(&*credentials) };
1982+ unsafe { CredFree(credentials as *const _ as _) };
1983+ unsafe { CredDeleteW(target_name, CRED_TYPE_GENERIC, None) }.unwrap();
1984+ result.unwrap()
1985+ }
1986+
1987+ #[test]
1988+ fn test_encode_restart_arguments() {
1989+ assert_eq!(encode_restart_arguments(&[]), OsStr::new(""));
1990+ assert_eq!(
1991+ encode_restart_arguments(&[
1992+ OsString::from("--user-data-dir"),
1993+ OsString::from(r"C:\Zed Data"),
1994+ ]),
1995+ OsStr::new(r#""--user-data-dir" "C:\Zed Data""#)
1996+ );
1997+ assert_eq!(
1998+ encode_restart_arguments(&[OsString::from(r"C:\")]),
1999+ OsStr::new(r#""C:\\""#)
2000+ );
vendor/gpui-pre-windows/src/shaders.hlsladded+1372 -0
@@ -0,0 +1,1372 @@
1+#include "alpha_correction.hlsl"
2+
3+cbuffer GlobalParams: register(b0) {
4+ float4 gamma_ratios;
5+ float2 global_viewport_size;
6+ float grayscale_enhanced_contrast;
7+ float subpixel_enhanced_contrast;
8+ uint is_bgr;
9+ float depth_scale;
10+ uint2 global_pad;
11+};
12+
13+cbuffer BatchParams: register(b1) {
14+ uint batch_start_index;
15+ uint3 batch_pad;
16+};
17+
18+Texture2D<float4> t_sprite: register(t0);
19+SamplerState s_sprite: register(s0);
20+
21+struct SubpixelSpriteFragmentOutput {
22+ float4 foreground : SV_Target0;
23+ float4 alpha : SV_Target1;
24+};
25+
26+struct Bounds {
27+ float2 origin;
28+ float2 size;
29+};
30+
31+struct Corners {
32+ float top_left;
33+ float top_right;
34+ float bottom_right;
35+ float bottom_left;
36+};
37+
38+struct Edges {
39+ float top;
40+ float right;
41+ float bottom;
42+ float left;
43+};
44+
45+struct Hsla {
46+ float h;
47+ float s;
48+ float l;
49+ float a;
50+};
51+
52+struct LinearColorStop {
53+ Hsla color;
54+ float percentage;
55+};
56+
57+struct Background {
58+ // 0u is Solid
59+ // 1u is LinearGradient
60+ // 2u is PatternSlash
61+ uint tag;
62+ // 0u is sRGB color
63+ // 1u is Oklab color
64+ uint color_space;
65+ Hsla solid;
66+ float gradient_angle_or_pattern_height;
67+ LinearColorStop colors[2];
68+ uint pad;
69+};
70+
71+struct PreparedBackground {
72+ nointerpolation float4 color0: COLOR1;
73+ nointerpolation float4 color1: COLOR2;
74+ nointerpolation uint tag: TEXCOORD2;
75+};
76+
77+struct AtlasTextureId {
78+ uint index;
79+ uint kind;
80+};
81+
82+struct AtlasBounds {
83+ int2 origin;
84+ int2 size;
85+};
86+
87+struct AtlasTile {
88+ AtlasTextureId texture_id;
89+ uint tile_id;
90+ uint padding;
91+ AtlasBounds bounds;
92+};
93+
94+struct TransformationMatrix {
95+ float2x2 rotation_scale;
96+ float2 translation;
97+};
98+
99+static const float M_PI_F = 3.141592653f;
100+static const float3 GRAYSCALE_FACTORS = float3(0.2126f, 0.7152f, 0.0722f);
101+
102+static const uint SIMPLE_PRIMITIVE_FLAG = 1u << 31;
103+
104+float4 to_device_position_impl(float2 position) {
105+ float2 device_position = position / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);
106+ return float4(device_position, 0., 1.);
107+}
108+
109+float4 to_device_position(float2 unit_vertex, Bounds bounds) {
110+ float2 position = unit_vertex * bounds.size + bounds.origin;
111+ return to_device_position_impl(position);
112+}
113+
114+float quad_depth(uint quad_id) {
115+ return saturate(float(quad_id + 1u) * depth_scale);
116+}
117+
118+static const float4 CULLED_POSITION = float4(0.0, 0.0, 0.0, 1.0);
119+
120+float4 distance_from_clip_rect_impl(float2 position, Bounds clip_bounds) {
121+ float2 tl = position - clip_bounds.origin;
122+ float2 br = clip_bounds.origin + clip_bounds.size - position;
123+ return float4(tl.x, br.x, tl.y, br.y);
124+}
125+
126+float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds bounds, Bounds clip_bounds, TransformationMatrix transformation) {
127+ float2 position = unit_vertex * bounds.size + bounds.origin;
128+ float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation;
129+ return distance_from_clip_rect_impl(transformed, clip_bounds);
130+}
131+
132+struct ClippedVertex {
133+ float2 position;
134+ // The corner as a fraction of the original bounds.
135+ float2 unit_vertex;
136+};
137+
138+ClippedVertex clip_to_mask(float2 unit_vertex, Bounds bounds, Bounds mask) {
139+ float2 origin = max(bounds.origin, mask.origin);
140+ float2 corner = min(bounds.origin + bounds.size, mask.origin + mask.size);
141+ float2 size = max(corner - origin, float2(0.0, 0.0));
142+
143+ ClippedVertex result;
144+ result.position = origin + unit_vertex * size;
145+ result.unit_vertex = (result.position - bounds.origin) / bounds.size;
146+ return result;
147+}
148+
149+// Convert linear RGB to sRGB
150+float3 linear_to_srgb(float3 color) {
151+ return pow(color, float3(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2));
152+}
153+
154+// Convert sRGB to linear RGB
155+float3 srgb_to_linear(float3 color) {
156+ return pow(color, float3(2.2, 2.2, 2.2));
157+}
158+
159+/// Hsla to sRGB conversion.
160+float4 hsla_to_rgba(Hsla hsla) {
161+ float h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range
162+ float s = hsla.s;
163+ float l = hsla.l;
164+ float a = hsla.a;
165+
166+ float c = (1.0 - abs(2.0 * l - 1.0)) * s;
167+ float x = c * (1.0 - abs(fmod(h, 2.0) - 1.0));
168+ float m = l - c / 2.0;
169+
170+ float r = 0.0;
171+ float g = 0.0;
172+ float b = 0.0;
173+
174+ if (h >= 0.0 && h < 1.0) {
175+ r = c;
176+ g = x;
177+ b = 0.0;
178+ } else if (h >= 1.0 && h < 2.0) {
179+ r = x;
180+ g = c;
181+ b = 0.0;
182+ } else if (h >= 2.0 && h < 3.0) {
183+ r = 0.0;
184+ g = c;
185+ b = x;
186+ } else if (h >= 3.0 && h < 4.0) {
187+ r = 0.0;
188+ g = x;
189+ b = c;
190+ } else if (h >= 4.0 && h < 5.0) {
191+ r = x;
192+ g = 0.0;
193+ b = c;
194+ } else {
195+ r = c;
196+ g = 0.0;
197+ b = x;
198+ }
199+
200+ float4 rgba;
201+ rgba.x = (r + m);
202+ rgba.y = (g + m);
203+ rgba.z = (b + m);
204+ rgba.w = a;
205+ return rgba;
206+}
207+
208+// Converts a sRGB color to the Oklab color space.
209+// Reference: https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab
210+float4 srgb_to_oklab(float4 color) {
211+ // Convert non-linear sRGB to linear sRGB
212+ color = float4(srgb_to_linear(color.rgb), color.a);
213+
214+ float l = 0.4122214708 * color.r + 0.5363325363 * color.g + 0.0514459929 * color.b;
215+ float m = 0.2119034982 * color.r + 0.6806995451 * color.g + 0.1073969566 * color.b;
216+ float s = 0.0883024619 * color.r + 0.2817188376 * color.g + 0.6299787005 * color.b;
217+
218+ float l_ = pow(l, 1.0/3.0);
219+ float m_ = pow(m, 1.0/3.0);
220+ float s_ = pow(s, 1.0/3.0);
221+
222+ return float4(
223+ 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
224+ 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
225+ 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
226+ color.a
227+ );
228+}
229+
230+// Converts an Oklab color to the sRGB color space.
231+float4 oklab_to_srgb(float4 color) {
232+ float l_ = color.r + 0.3963377774 * color.g + 0.2158037573 * color.b;
233+ float m_ = color.r - 0.1055613458 * color.g - 0.0638541728 * color.b;
234+ float s_ = color.r - 0.0894841775 * color.g - 1.2914855480 * color.b;
235+
236+ float l = l_ * l_ * l_;
237+ float m = m_ * m_ * m_;
238+ float s = s_ * s_ * s_;
239+
240+ float3 linear_rgb = float3(
241+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
242+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
243+ -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
244+ );
245+
246+ // Convert linear sRGB to non-linear sRGB
247+ return float4(linear_to_srgb(linear_rgb), color.a);
248+}
249+
250+float4 over(float4 below, float4 above) {
251+ float alpha = above.a + below.a * (1.0 - above.a);
252+ float3 premultiplied = above.rgb * above.a + below.rgb * below.a * (1.0 - above.a);
253+ return float4(premultiplied / (alpha == 0.0 ? 1.0 : alpha), alpha);
254+}
255+
256+float2 to_tile_position(float2 unit_vertex, AtlasTile tile) {
257+ float2 atlas_size;
258+ t_sprite.GetDimensions(atlas_size.x, atlas_size.y);
259+ return (float2(tile.bounds.origin) + unit_vertex * float2(tile.bounds.size)) / atlas_size;
260+}
261+
262+// Selects corner radius based on quadrant.
263+float pick_corner_radius(float2 center_to_point, Corners corner_radii) {
264+ if (center_to_point.x < 0.) {
265+ if (center_to_point.y < 0.) {
266+ return corner_radii.top_left;
267+ } else {
268+ return corner_radii.bottom_left;
269+ }
270+ } else {
271+ if (center_to_point.y < 0.) {
272+ return corner_radii.top_right;
273+ } else {
274+ return corner_radii.bottom_right;
275+ }
276+ }
277+}
278+
279+float4 to_device_position_transformed(float2 unit_vertex, Bounds bounds,
280+ TransformationMatrix transformation) {
281+ float2 position = unit_vertex * bounds.size + bounds.origin;
282+ float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation;
283+ float2 device_position = transformed / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);
284+ return float4(device_position, 0.0, 1.0);
285+}
286+
287+// Implementation of quad signed distance field
288+float quad_sdf_impl(float2 corner_center_to_point, float corner_radius) {
289+ if (corner_radius == 0.0) {
290+ // Fast path for unrounded corners
291+ return max(corner_center_to_point.x, corner_center_to_point.y);
292+ } else {
293+ // Signed distance of the point from a quad that is inset by corner_radius
294+ // It is negative inside this quad, and positive outside
295+ float signed_distance_to_inset_quad =
296+ // 0 inside the inset quad, and positive outside
297+ length(max(float2(0.0, 0.0), corner_center_to_point)) +
298+ // 0 outside the inset quad, and negative inside
299+ min(0.0, max(corner_center_to_point.x, corner_center_to_point.y));
300+
301+ return signed_distance_to_inset_quad - corner_radius;
302+ }
303+}
304+
305+float quad_sdf(float2 pt, Bounds bounds, Corners corner_radii) {
306+ float2 half_size = bounds.size / 2.;
307+ float2 center = bounds.origin + half_size;
308+ float2 center_to_point = pt - center;
309+ float corner_radius = pick_corner_radius(center_to_point, corner_radii);
310+ float2 corner_to_point = abs(center_to_point) - half_size;
311+ float2 corner_center_to_point = corner_to_point + corner_radius;
312+ return quad_sdf_impl(corner_center_to_point, corner_radius);
313+}
314+
315+PreparedBackground prepare_background(Background background) {
316+ PreparedBackground output;
317+ output.tag = background.tag;
318+ output.color1 = float4(0.0, 0.0, 0.0, 0.0);
319+
320+ if (background.tag == 1) {
321+ output.color0 = hsla_to_rgba(background.colors[0].color);
322+ output.color1 = hsla_to_rgba(background.colors[1].color);
323+ // Interpolating in Oklab means converting the endpoints once rather
324+ // than at every stop evaluation.
325+ if (background.color_space == 1) {
326+ output.color0 = srgb_to_oklab(output.color0);
327+ output.color1 = srgb_to_oklab(output.color1);
328+ }
329+ } else {
330+ output.color0 = hsla_to_rgba(background.solid);
331+ }
332+
333+ return output;
334+}
335+
336+// Ordered (Bayer 4x4) dither threshold, remapped to [-1, +1].
337+float dither_offset(float2 position) {
338+ uint2 cell = uint2(position) & 3u;
339+ uint z = cell.x ^ cell.y;
340+ uint threshold = ((z & 1u) << 3)
341+ | ((cell.y & 1u) << 2)
342+ | (z & 2u)
343+ | ((cell.y & 2u) >> 1);
344+ return (float(threshold) + 0.5) * (1.0 / 8.0) - 1.0;
345+}
346+
347+float4 background_color(PreparedBackground prepared, Background background, Bounds bounds,
348+ float2 position) {
349+ float4 color = prepared.color0;
350+ if (prepared.tag == 0u) {
351+ return color;
352+ }
353+
354+ switch (prepared.tag) {
355+ case 1: {
356+ // -90 degrees to match the CSS gradient angle.
357+ float radians = (fmod(background.gradient_angle_or_pattern_height, 360.0) - 90.0)
358+ * (M_PI_F / 180.0);
359+ float2 direction = float2(cos(radians), sin(radians));
360+
361+ // Expand the short side to be the same as the long side
362+ if (bounds.size.x > bounds.size.y) {
363+ direction.y *= bounds.size.y / bounds.size.x;
364+ } else {
365+ direction.x *= bounds.size.x / bounds.size.y;
366+ }
367+
368+ float extent = abs(direction.x) > abs(direction.y)
369+ ? bounds.size.x
370+ : bounds.size.y;
371+ float direction_length = length(direction);
372+ float span = background.colors[1].percentage - background.colors[0].percentage;
373+ // The half-extent term is exactly half of `extent`, so the
374+ // position-independent part reduces to this.
375+ float offset = 0.5 - background.colors[0].percentage;
376+
377+ // t = dot(position - center, gradient.xy) + gradient.z
378+ float3 gradient = float3(0.0, 0.0, 0.0);
379+ if (direction_length != 0.0 && extent != 0.0) {
380+ if (span == 0.0) {
381+ const float STEP = 1e30;
382+ gradient = float3(direction / (direction_length * extent) * STEP, offset * STEP);
383+ } else {
384+ gradient = float3(direction / (direction_length * extent * span), offset / span);
385+ }
386+ }
387+ float2 center = bounds.origin + bounds.size * 0.5;
388+ float t = saturate(dot(position - center, gradient.xy) + gradient.z);
389+ color = lerp(prepared.color0, prepared.color1, t);
390+ if (background.color_space == 1) {
391+ color = oklab_to_srgb(color);
392+ }
393+
394+ // Dither to reduce banding in gradients (especially dark/alpha).
395+ float dither = dither_offset(position);
396+ color.rgb += dither * 1.0 / 255.0;
397+ color.a += dither * 1.5 / 255.0;
398+ break;
399+ }
400+ case 2: {
401+ float pattern_height_encoded = background.gradient_angle_or_pattern_height;
402+ float pattern_width = (pattern_height_encoded / 65535.0) / 255.0;
403+ float pattern_interval = fmod(pattern_height_encoded, 65535.0) / 255.0;
404+ float pattern_height = pattern_width + pattern_interval;
405+ // Only the rotated x coordinate is used, and a row-vector multiply
406+ // by the rotation reduces it to dot(v, float2(cos a, sin a)).
407+ float stripe_angle = M_PI_F / 4.0;
408+ float2 stripe_direction = float2(cos(stripe_angle), sin(stripe_angle));
409+ float pattern_period = pattern_height * sin(stripe_angle);
410+ float threshold = pattern_period * (pattern_width / pattern_height) / 2.0;
411+ float pattern = fmod(dot(position - bounds.origin, stripe_direction), pattern_period);
412+ float distance = min(pattern, pattern_period - pattern) - threshold;
413+ color.a *= saturate(0.5 - distance);
414+ break;
415+ }
416+ case 3: {
417+ // checkerboard
418+ float cell_size = background.gradient_angle_or_pattern_height;
419+ float2 relative_position = position - bounds.origin;
420+ float x_index = floor(relative_position.x / cell_size);
421+ float y_index = floor(relative_position.y / cell_size);
422+ color.a *= saturate((x_index + y_index) % 2.0);
423+ break;
424+ }
425+ }
426+
427+ return color;
428+}
429+
430+// Returns the dash velocity of a corner given the dash velocity of the two
431+// sides, by returning the slower velocity (larger dashes).
432+//
433+// Since 0 is used for dash velocity when the border width is 0 (instead of
434+// +inf), this returns the other dash velocity in that case.
435+//
436+// An alternative to this might be to appropriately interpolate the dash
437+// velocity around the corner, but that seems overcomplicated.
438+float corner_dash_velocity(float dv1, float dv2) {
439+ if (dv1 == 0.0) {
440+ return dv2;
441+ } else if (dv2 == 0.0) {
442+ return dv1;
443+ } else {
444+ return min(dv1, dv2);
445+ }
446+}
447+
448+// Returns alpha used to render antialiased dashes.
449+// `t` is within the dash when `fmod(t, period) < length`.
450+float dash_alpha(
451+ float t, float period, float length, float dash_velocity,
452+ float antialias_threshold
453+) {
454+ float half_period = period / 2.0;
455+ float half_length = length / 2.0;
456+ // Value in [-half_period, half_period]
457+ // The dash is in [-half_length, half_length]
458+ float centered = fmod(t + half_period - half_length, period) - half_period;
459+ // Signed distance for the dash, negative values are inside the dash
460+ float signed_distance = abs(centered) - half_length;
461+ // Antialiased alpha based on the signed distance
462+ return saturate(antialias_threshold - signed_distance / dash_velocity);
463+}
464+
465+// This approximates distance to the nearest point to a quarter ellipse in a way
466+// that is sufficient for anti-aliasing when the ellipse is not very eccentric.
467+// The components of `point` are expected to be positive.
468+//
469+// Negative on the outside and positive on the inside.
470+float quarter_ellipse_sdf(float2 pt, float2 radii) {
471+ // Scale the space to treat the ellipse like a unit circle
472+ float2 circle_vec = pt / radii;
473+ float unit_circle_sdf = length(circle_vec) - 1.0;
474+ // Approximate up-scaling of the length by using the average of the radii.
475+ //
476+ // TODO: A better solution would be to use the gradient of the implicit
477+ // function for an ellipse to approximate a scaling factor.
478+ return unit_circle_sdf * (radii.x + radii.y) * -0.5;
479+}
480+
481+/*
482+**
483+** Quads
484+**
485+*/
486+
487+struct Quad {
488+ uint order;
489+ uint border_style;
490+ Bounds bounds;
491+ Bounds content_mask;
492+ Background background;
493+ Hsla border_color;
494+ Corners corner_radii;
495+ Edges border_widths;
496+};
497+
498+bool has_rounded_corners(Corners corner_radii) {
499+ return corner_radii.top_left != 0.0
500+ || corner_radii.top_right != 0.0
501+ || corner_radii.bottom_right != 0.0
502+ || corner_radii.bottom_left != 0.0;
503+}
504+
505+bool has_border(Edges border_widths) {
506+ return border_widths.top != 0.0
507+ || border_widths.right != 0.0
508+ || border_widths.bottom != 0.0
509+ || border_widths.left != 0.0;
510+}
511+
512+bool is_shaped(Quad quad) {
513+ return has_rounded_corners(quad.corner_radii) || has_border(quad.border_widths);
514+}
515+
516+struct QuadFragmentInput {
517+ nointerpolation uint quad_id: TEXCOORD0;
518+ float4 position: SV_Position;
519+ nointerpolation float4 border_color: COLOR0;
520+ PreparedBackground background;
521+};
522+
523+// Opaque rectangles are drawn by the opaque pass instead of the quad pass.
524+bool is_opaque_rectangle(Quad quad) {
525+ return quad.background.tag == 0u
526+ && quad.background.solid.a >= 1.0
527+ && !has_rounded_corners(quad.corner_radii)
528+ && !has_border(quad.border_widths);
529+}
530+
531+StructuredBuffer<Quad> quads: register(t1);
532+
533+QuadFragmentInput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {
534+ uint quad_id = batch_start_index + instance_id;
535+ Quad quad = quads[quad_id];
536+
537+ if (is_opaque_rectangle(quad)) {
538+ QuadFragmentInput culled = (QuadFragmentInput)0;
539+ culled.position = CULLED_POSITION;
540+ return culled;
541+ }
542+
543+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
544+ ClippedVertex vertex = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask);
545+ float4 device_position = to_device_position_impl(vertex.position);
546+
547+ float4 border_color = hsla_to_rgba(quad.border_color);
548+
549+ QuadFragmentInput output;
550+ output.position = device_position;
551+ output.position.z = quad_depth(quad_id);
552+ output.border_color = border_color;
553+ bool simple = !is_shaped(quad) && quad.background.tag == 0u;
554+ output.quad_id = quad_id | (simple ? SIMPLE_PRIMITIVE_FLAG : 0u);
555+ output.background = prepare_background(quad.background);
556+ return output;
557+}
558+
559+float4 quad_fragment(QuadFragmentInput input): SV_Target {
560+ if ((input.quad_id & SIMPLE_PRIMITIVE_FLAG) != 0u) {
561+ return input.background.color0;
562+ }
563+
564+ Quad quad = quads[input.quad_id];
565+ float4 background =
566+ background_color(input.background, quad.background, quad.bounds, input.position.xy);
567+ bool unrounded = !has_rounded_corners(quad.corner_radii);
568+
569+ float2 size = quad.bounds.size;
570+ float2 half_size = size / 2.;
571+ float2 the_point = input.position.xy - quad.bounds.origin;
572+ float2 center_to_point = the_point - half_size;
573+
574+ // Signed distance field threshold for inclusion of pixels. 0.5 is the
575+ // minimum distance between the center of the pixel and the edge.
576+ const float antialias_threshold = 0.5;
577+
578+ // Radius of the nearest corner
579+ float corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
580+
581+ float2 border = float2(
582+ center_to_point.x < 0.0 ? quad.border_widths.left : quad.border_widths.right,
583+ center_to_point.y < 0.0 ? quad.border_widths.top : quad.border_widths.bottom
584+ );
585+
586+ // 0-width borders are reduced so that `inner_sdf >= antialias_threshold`.
587+ // The purpose of this is to not draw antialiasing pixels in this case.
588+ float2 reduced_border = float2(
589+ border.x == 0.0 ? -antialias_threshold : border.x,
590+ border.y == 0.0 ? -antialias_threshold : border.y
591+ );
592+
593+ // Vector from the corner of the quad bounds to the point, after mirroring
594+ // the point into the bottom right quadrant. Both components are <= 0.
595+ float2 corner_to_point = abs(center_to_point) - half_size;
596+
597+ // Vector from the point to the center of the rounded corner's circle, also
598+ // mirrored into bottom right quadrant.
599+ float2 corner_center_to_point = corner_to_point + corner_radius;
600+
601+ // Whether the nearest point on the border is rounded
602+ bool is_near_rounded_corner =
603+ corner_center_to_point.x >= 0.0 &&
604+ corner_center_to_point.y >= 0.0;
605+
606+ // Vector from straight border inner corner to point.
607+ //
608+ // 0-width borders are turned into width -1 so that inner_sdf is > 1.0 near
609+ // the border. Without this, antialiasing pixels would be drawn.
610+ float2 straight_border_inner_corner_to_point = corner_to_point + reduced_border;
611+
612+ // Whether the point is beyond the inner edge of the straight border
613+ bool is_beyond_inner_straight_border =
614+ straight_border_inner_corner_to_point.x > 0.0 ||
615+ straight_border_inner_corner_to_point.y > 0.0;
616+
617+ // Whether the point is far enough inside the quad, such that the pixels are
618+ // not affected by the straight border.
619+ bool is_within_inner_straight_border =
620+ straight_border_inner_corner_to_point.x < -antialias_threshold &&
621+ straight_border_inner_corner_to_point.y < -antialias_threshold;
622+
623+ // Fast path for points that must be part of the background
624+ if (is_within_inner_straight_border && !is_near_rounded_corner) {
625+ return background;
626+ }
627+
628+ // Signed distance of the point to the outside edge of the quad's border
629+ float outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius);
630+
631+ // Approximate signed distance of the point to the inside edge of the quad's
632+ // border. It is negative outside this edge (within the border), and
633+ // positive inside.
634+ //
635+ // This is not always an accurate signed distance:
636+ // * The rounded portions with varying border width use an approximation of
637+ // nearest-point-on-ellipse.
638+ // * When it is quickly known to be outside the edge, -1.0 is used.
639+ float inner_sdf = 0.0;
640+ if (corner_center_to_point.x <= 0.0 || corner_center_to_point.y <= 0.0) {
641+ // Fast paths for straight borders
642+ inner_sdf = -max(straight_border_inner_corner_to_point.x,
643+ straight_border_inner_corner_to_point.y);
644+ } else if (is_beyond_inner_straight_border) {
645+ // Fast path for points that must be outside the inner edge
646+ inner_sdf = -1.0;
647+ } else if (reduced_border.x == reduced_border.y) {
648+ // Fast path for circular inner edge.
649+ inner_sdf = -(outer_sdf + reduced_border.x);
650+ } else {
651+ float2 ellipse_radii = max(float2(0.0, 0.0), float2(corner_radius, corner_radius) - reduced_border);
652+ inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii);
653+ }
654+
655+ // Negative when inside the border
656+ float border_sdf = max(inner_sdf, outer_sdf);
657+
658+ float4 color = background;
659+ if (border_sdf < antialias_threshold) {
660+ float4 border_color = input.border_color;
661+ // Dashed border logic when border_style == 1
662+ if (quad.border_style == 1) {
663+ // Position along the perimeter in "dash space", where each dash
664+ // period has length 1
665+ float t = 0.0;
666+
667+ // Total number of dash periods, so that the dash spacing can be
668+ // adjusted to evenly divide it
669+ float max_t = 0.0;
670+
671+ // Border width is proportional to dash size. This is the behavior
672+ // used by browsers, but also avoids dashes from different segments
673+ // overlapping when dash size is smaller than the border width.
674+ //
675+ // Dash pattern: (2 * border width) dash, (1 * border width) gap
676+ const float dash_length_per_width = 2.0;
677+ const float dash_gap_per_width = 1.0;
678+ const float dash_period_per_width = dash_length_per_width + dash_gap_per_width;
679+
680+ // Since the dash size is determined by border width, the density of
681+ // dashes varies. Multiplying a pixel distance by this returns a
682+ // position in dash space - it has units (dash period / pixels). So
683+ // a dash velocity of (1 / 10) is 1 dash every 10 pixels.
684+ float dash_velocity = 0.0;
685+
686+ // Dividing this by the border width gives the dash velocity
687+ const float dv_numerator = 1.0 / dash_period_per_width;
688+
689+ if (unrounded) {
690+ // When corners aren't rounded, the dashes are separately laid
691+ // out on each straight line, rather than around the whole
692+ // perimeter. This way each line starts and ends with a dash.
693+ bool is_horizontal = corner_center_to_point.x < corner_center_to_point.y;
694+ // Choosing the right border width for dashed borders.
695+ // TODO: A better solution exists taking a look at the whole file.
696+ // this does not fix single dashed borders at the corners
697+ float2 dashed_border = float2(
698+ max(quad.border_widths.bottom, quad.border_widths.top),
699+ max(quad.border_widths.right, quad.border_widths.left)
700+ );
701+ float border_width = is_horizontal ? dashed_border.x : dashed_border.y;
702+ dash_velocity = dv_numerator / border_width;
703+ t = is_horizontal ? the_point.x : the_point.y;
704+ t *= dash_velocity;
705+ max_t = is_horizontal ? size.x : size.y;
706+ max_t *= dash_velocity;
707+ } else {
708+ // When corners are rounded, the dashes are laid out clockwise
709+ // around the whole perimeter.
710+
711+ float r_tr = quad.corner_radii.top_right;
712+ float r_br = quad.corner_radii.bottom_right;
713+ float r_bl = quad.corner_radii.bottom_left;
714+ float r_tl = quad.corner_radii.top_left;
715+
716+ float w_t = quad.border_widths.top;
717+ float w_r = quad.border_widths.right;
718+ float w_b = quad.border_widths.bottom;
719+ float w_l = quad.border_widths.left;
720+
721+ // Straight side dash velocities
722+ float dv_t = w_t <= 0.0 ? 0.0 : dv_numerator / w_t;
723+ float dv_r = w_r <= 0.0 ? 0.0 : dv_numerator / w_r;
724+ float dv_b = w_b <= 0.0 ? 0.0 : dv_numerator / w_b;
725+ float dv_l = w_l <= 0.0 ? 0.0 : dv_numerator / w_l;
726+
727+ // Straight side lengths in dash space
728+ float s_t = (size.x - r_tl - r_tr) * dv_t;
729+ float s_r = (size.y - r_tr - r_br) * dv_r;
730+ float s_b = (size.x - r_br - r_bl) * dv_b;
731+ float s_l = (size.y - r_bl - r_tl) * dv_l;
732+
733+ float corner_dash_velocity_tr = corner_dash_velocity(dv_t, dv_r);
734+ float corner_dash_velocity_br = corner_dash_velocity(dv_b, dv_r);
735+ float corner_dash_velocity_bl = corner_dash_velocity(dv_b, dv_l);
736+ float corner_dash_velocity_tl = corner_dash_velocity(dv_t, dv_l);
737+
738+ // Corner lengths in dash space
739+ float c_tr = r_tr * (M_PI_F / 2.0) * corner_dash_velocity_tr;
740+ float c_br = r_br * (M_PI_F / 2.0) * corner_dash_velocity_br;
741+ float c_bl = r_bl * (M_PI_F / 2.0) * corner_dash_velocity_bl;
742+ float c_tl = r_tl * (M_PI_F / 2.0) * corner_dash_velocity_tl;
743+
744+ // Cumulative dash space upto each segment
745+ float upto_tr = s_t;
746+ float upto_r = upto_tr + c_tr;
747+ float upto_br = upto_r + s_r;
748+ float upto_b = upto_br + c_br;
749+ float upto_bl = upto_b + s_b;
750+ float upto_l = upto_bl + c_bl;
751+ float upto_tl = upto_l + s_l;
752+ max_t = upto_tl + c_tl;
753+
754+ if (is_near_rounded_corner) {
755+ float radians = atan2(corner_center_to_point.y, corner_center_to_point.x);
756+ float corner_t = radians * corner_radius;
757+
758+ if (center_to_point.x >= 0.0) {
759+ if (center_to_point.y < 0.0) {
760+ dash_velocity = corner_dash_velocity_tr;
761+ // Subtracted because radians is pi/2 to 0 when
762+ // going clockwise around the top right corner,
763+ // since the y axis has been flipped
764+ t = upto_r - corner_t * dash_velocity;
765+ } else {
766+ dash_velocity = corner_dash_velocity_br;
767+ // Added because radians is 0 to pi/2 when going
768+ // clockwise around the bottom-right corner
769+ t = upto_br + corner_t * dash_velocity;
770+ }
771+ } else {
772+ if (center_to_point.y >= 0.0) {
773+ dash_velocity = corner_dash_velocity_bl;
774+ // Subtracted because radians is pi/1 to 0 when
775+ // going clockwise around the bottom-left corner,
776+ // since the x axis has been flipped
777+ t = upto_l - corner_t * dash_velocity;
778+ } else {
779+ dash_velocity = corner_dash_velocity_tl;
780+ // Added because radians is 0 to pi/2 when going
781+ // clockwise around the top-left corner, since both
782+ // axis were flipped
783+ t = upto_tl + corner_t * dash_velocity;
784+ }
785+ }
786+ } else {
787+ // Straight borders
788+ bool is_horizontal = corner_center_to_point.x < corner_center_to_point.y;
789+ if (is_horizontal) {
790+ if (center_to_point.y < 0.0) {
791+ dash_velocity = dv_t;
792+ t = (the_point.x - r_tl) * dash_velocity;
793+ } else {
794+ dash_velocity = dv_b;
795+ t = upto_bl - (the_point.x - r_bl) * dash_velocity;
796+ }
797+ } else {
798+ if (center_to_point.x < 0.0) {
799+ dash_velocity = dv_l;
800+ t = upto_tl - (the_point.y - r_tl) * dash_velocity;
801+ } else {
802+ dash_velocity = dv_r;
803+ t = upto_r + (the_point.y - r_tr) * dash_velocity;
804+ }
805+ }
806+ }
807+ }
808+ float dash_length = dash_length_per_width / dash_period_per_width;
809+ float desired_dash_gap = dash_gap_per_width / dash_period_per_width;
810+
811+ // Straight borders should start and end with a dash, so max_t is
812+ // reduced to cause this.
813+ max_t -= unrounded ? dash_length : 0.0;
814+ if (max_t >= 1.0) {
815+ // Adjust dash gap to evenly divide max_t
816+ float dash_count = floor(max_t);
817+ float dash_period = max_t / dash_count;
818+ border_color.a *= dash_alpha(t, dash_period, dash_length, dash_velocity, antialias_threshold);
819+ } else if (unrounded) {
820+ // When there isn't enough space for the full gap between the
821+ // two start / end dashes of a straight border, reduce gap to
822+ // make them fit.
823+ float dash_gap = max_t - dash_length;
824+ if (dash_gap > 0.0) {
825+ float dash_period = dash_length + dash_gap;
826+ border_color.a *= dash_alpha(t, dash_period, dash_length, dash_velocity, antialias_threshold);
827+ }
828+ }
829+ }
830+
831+ border_color.a *= saturate(antialias_threshold - inner_sdf);
832+ color = over(background, border_color);
833+ }
834+
835+ return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf));
836+}
837+
838+/*
839+**
840+** Opaque quads
841+**
842+*/
843+
844+struct OpaqueQuadFragmentInput {
845+ float4 position: SV_Position;
846+ nointerpolation float4 color: COLOR0;
847+};
848+
849+OpaqueQuadFragmentInput opaque_quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {
850+ uint quad_id = batch_start_index - instance_id;
851+ Quad quad = quads[quad_id];
852+
853+ OpaqueQuadFragmentInput output;
854+ if (!is_opaque_rectangle(quad)) {
855+ output.position = CULLED_POSITION;
856+ output.color = float4(0.0, 0.0, 0.0, 0.0);
857+ return output;
858+ }
859+
860+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
861+ ClippedVertex vertex = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask);
862+
863+ output.position = to_device_position_impl(vertex.position);
864+ output.position.z = quad_depth(quad_id);
865+ output.color = hsla_to_rgba(quad.background.solid);
866+ return output;
867+}
868+
869+float4 opaque_quad_fragment(OpaqueQuadFragmentInput input): SV_Target {
870+ return input.color;
871+}
872+
873+/*
874+**
875+** Shadows
876+**
877+*/
878+
879+struct Shadow {
880+ uint order;
881+ float blur_radius;
882+ Bounds bounds;
883+ Corners corner_radii;
884+ Bounds content_mask;
885+ Hsla color;
886+ Bounds shape_bounds;
887+ Corners shape_corner_radii;
888+ uint inset;
889+ uint pad; // align to 8 bytes
890+};
891+
892+struct PreparedBlurredRoundedRect {
893+ nointerpolation float4 shape: TEXCOORD1;
894+ nointerpolation float4 r1: TEXCOORD2;
895+ nointerpolation float4 exponent: TEXCOORD3;
896+ nointerpolation float4 scale: TEXCOORD4;
897+};
898+
899+struct ShadowFragmentInput {
900+ nointerpolation uint shadow_id: TEXCOORD0;
901+ float4 position: SV_Position;
902+ nointerpolation float4 color: COLOR;
903+ PreparedBlurredRoundedRect blur;
904+};
905+
906+StructuredBuffer<Shadow> shadows: register(t1);
907+
908+float erf7(float x) {
909+ x = clamp(x, -10., 10.) * (2. / sqrt(M_PI_F));
910+ float xx = x * x;
911+ x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx);
912+ return x / sqrt(1. + x * x);
913+}
914+
915+// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2):
916+// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html
917+PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners corner_radii, float sigma) {
918+ float s = max(sigma * sqrt(2.), 1e-6);
919+ float s_inv = 1. / s;
920+ float min_edge = min(size.x, size.y);
921+ float r_max = 0.5 * min_edge;
922+ float4 radii = float4(corner_radii.top_left, corner_radii.top_right,
923+ corner_radii.bottom_right, corner_radii.bottom_left);
924+ float4 r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), r_max);
925+ float4 r1 = min(sqrt(radii * radii + 4. * s * s), r_max);
926+
927+ float2 half_extent = 0.5 * s_inv * size;
928+ float delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y));
929+ float2 adjusted_size = float2(size.x + min(delta, 0.), size.y - max(delta, 0.));
930+ float4 peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii);
931+
932+ PreparedBlurredRoundedRect output;
933+ output.shape = float4(0.5 * adjusted_size, s_inv, min_edge);
934+ output.r1 = r1;
935+ output.exponent = 2. * r1 / r0;
936+ output.scale = 0.5 * float4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w));
937+ return output;
938+}
939+
940+float pick_corner(float2 center_to_point, float4 values) {
941+ Corners corners = { values.x, values.y, values.z, values.w };
942+ return pick_corner_radius(center_to_point, corners);
943+}
944+
945+float blurred_rounded_rect(float2 center_to_point, PreparedBlurredRoundedRect prepared) {
946+ float r1 = pick_corner(center_to_point, prepared.r1);
947+ float exponent = pick_corner(center_to_point, prepared.exponent);
948+ float scale = pick_corner(center_to_point, prepared.scale);
949+ float s_inv = prepared.shape.z;
950+ float min_edge = prepared.shape.w;
951+
952+ float2 p0 = abs(center_to_point) - (prepared.shape.xy - r1);
953+ float2 p1 = max(p0, 0.);
954+ float d_pos;
955+ [branch] if (p1.x > 0. && p1.y > 0.) {
956+ d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1. / exponent);
957+ } else {
958+ d_pos = p1.x + p1.y;
959+ }
960+
961+ float d_neg = min(max(p0.x, p0.y), 0.);
962+ float d = d_pos + d_neg - r1;
963+ return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d));
964+}
965+
966+ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {
967+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
968+ uint shadow_id = batch_start_index + instance_id;
969+ Shadow shadow = shadows[shadow_id];
970+
971+ ClippedVertex vertex = clip_to_mask(unit_vertex, shadow.bounds, shadow.content_mask);
972+ float4 device_position = to_device_position_impl(vertex.position);
973+ float4 color = hsla_to_rgba(shadow.color);
974+
975+ ShadowFragmentInput output;
976+ output.position = device_position;
977+ output.color = color;
978+ output.shadow_id = shadow_id;
979+ output.blur = prepare_blurred_rounded_rect(shadow.shape_bounds.size, shadow.shape_corner_radii, shadow.blur_radius);
980+
981+ return output;
982+}
983+
984+float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET {
985+ Shadow shadow = shadows[input.shadow_id];
986+
987+ float alpha;
988+ if (shadow.blur_radius == 0.) {
989+ float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii);
990+ alpha = saturate(0.5 - distance);
991+ } else {
992+ float2 center = shadow.shape_bounds.origin + shadow.shape_bounds.size / 2.;
993+ alpha = blurred_rounded_rect(input.position.xy - center, input.blur);
994+ }
995+
996+ if (shadow.inset != 0u) {
997+ // The inset shadow is the complement of the (blurred) hole rect, clipped to the element.
998+ // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0.
999+ alpha = 1.0 - alpha;
1000+ float element_distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii);
1001+ alpha *= saturate(0.5 - element_distance);
1002+ }
1003+
1004+ return input.color * float4(1., 1., 1., alpha);
1005+}
1006+
1007+/*
1008+**
1009+** Path Tiles
1010+**
1011+*/
1012+
1013+struct PathCurve {
1014+ float2 p0;
1015+ float2 p1;
1016+ float2 a;
1017+ float2 b;
1018+ float sign;
1019+ uint pad;
1020+};
1021+
1022+struct PathTile {
1023+ uint paint;
1024+ uint curve_start;
1025+ uint curve_count;
1026+ int backdrop;
1027+ float2 top_left;
1028+ float2 bottom_right;
1029+ float2 reference;
1030+ float2 curves_top_left;
1031+ float2 curves_bottom_right;
1032+};
1033+
1034+struct PathPaint {
1035+ Bounds bounds;
1036+ Bounds content_mask;
1037+ Background color;
1038+ uint even_odd;
1039+ uint pad;
1040+};
1041+
1042+StructuredBuffer<PathTile> path_tiles: register(t1);
1043+StructuredBuffer<PathCurve> path_curves: register(t2);
1044+StructuredBuffer<PathPaint> path_paints: register(t3);
1045+
1046+struct PathTileFragmentInput {
1047+ float4 position: SV_Position;
1048+ nointerpolation uint tile_id: TEXCOORD0;
1049+ nointerpolation float4 curve_box: TEXCOORD1;
1050+ PreparedBackground background;
1051+};
1052+
1053+PathTileFragmentInput path_tile_vertex(uint vertex_id: SV_VertexID, uint tile_id: SV_InstanceID) {
1054+ uint tile_index = batch_start_index + tile_id;
1055+ PathTile tile = path_tiles[tile_index];
1056+ PathPaint paint = path_paints[tile.paint];
1057+
1058+ // Neighboring tiles store their shared edge as the same number, so clipping each corner on its
1059+ // own gives them bit-identical edges, which the rasterizer neither overlaps nor leaves gaps
1060+ // between. Interpolating from an origin and a size would not.
1061+ float2 mask_top_left = paint.content_mask.origin;
1062+ float2 mask_bottom_right = paint.content_mask.origin + paint.content_mask.size;
1063+ float2 top_left = clamp(tile.top_left, mask_top_left, mask_bottom_right);
1064+ float2 bottom_right = clamp(tile.bottom_right, top_left, mask_bottom_right);
1065+ float2 position = float2(
1066+ (vertex_id & 1u) != 0u ? bottom_right.x : top_left.x,
1067+ (vertex_id & 2u) != 0u ? bottom_right.y : top_left.y);
1068+
1069+ PathTileFragmentInput output;
1070+ output.position = to_device_position_impl(position);
1071+ output.tile_id = tile_index;
1072+ output.curve_box = float4(tile.curves_top_left, tile.curves_bottom_right);
1073+ output.background = prepare_background(paint.color);
1074+ return output;
1075+}
1076+
1077+// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece.
1078+float monotone_quadratic_root(float a, float b, float c, float direction) {
1079+ float discriminant = max(b * b - 4.0 * a * c, 0.0);
1080+ float denominator = b + direction * sqrt(discriminant);
1081+ if (denominator == 0.0) {
1082+ return 0.0;
1083+ }
1084+ return saturate(-2.0 * c / denominator);
1085+}
1086+
1087+// Coverage estimate adapted from https://github.com/EricLengyel/Slug/blob/be3c13eb7d63f9e8aa5c583e42d92c374cb91d98/SlugPixelShader.hlsl
1088+// Copyright (c) 2017 Eric Lengyel.
1089+// Licensed under the MIT license.
1090+
1091+// Accumulates the curve's winding along the pixel's leftward and upward rays. Like Slug, a crossing
1092+// within half a pixel of the center counts fractionally.
1093+void add_curve_winding(PathCurve curve, float2 center, inout float2 winding, inout float2 weight) {
1094+ float min_x = min(curve.p0.x, curve.p1.x);
1095+ float max_x = max(curve.p0.x, curve.p1.x);
1096+
1097+ [branch]
1098+ if (curve.p0.y <= center.y && center.y < curve.p1.y) {
1099+ [branch]
1100+ if (max_x <= center.x - 0.5) {
1101+ winding.x += curve.sign;
1102+ } else {
1103+ float t = monotone_quadratic_root(curve.a.y, curve.b.y, curve.p0.y - center.y, 1.0);
1104+ float x = (curve.a.x * t + curve.b.x) * t + curve.p0.x;
1105+ float distance = center.x - x;
1106+ winding.x += curve.sign * saturate(distance + 0.5);
1107+ weight.x = max(weight.x, saturate(1.0 - 2.0 * abs(distance)));
1108+ }
1109+ }
1110+
1111+ [branch]
1112+ if (min_x <= center.x && center.x < max_x) {
1113+ float direction = curve.p1.x > curve.p0.x ? 1.0 : -1.0;
1114+ [branch]
1115+ if (curve.p1.y <= center.y - 0.5) {
1116+ winding.y -= curve.sign * direction;
1117+ } else if (curve.p0.y < center.y + 0.5) {
1118+ float t = monotone_quadratic_root(curve.a.x, curve.b.x, curve.p0.x - center.x, direction);
1119+ float y = (curve.a.y * t + curve.b.y) * t + curve.p0.y;
1120+ float distance = center.y - y;
1121+ winding.y -= curve.sign * direction * saturate(distance + 0.5);
1122+ weight.y = max(weight.y, saturate(1.0 - 2.0 * abs(distance)));
1123+ }
1124+ }
1125+}
1126+
1127+// The backdrop gives the unlisted curves' winding along a leftward ray from the tile's reference
1128+// corner. We need it at the current pixel, along both leftward and upward rays. Because paths are
1129+// closed, chains of unlisted curves can only begin or end where a listed curve does. So, we can
1130+// compute the winding at the current pixel by correcting the backdrop for each listed endpoint
1131+// between its ray and the pixel.
1132+void correct_for_endpoint(float2 endpoint, float step, float2 reference, float2 center,
1133+ inout float2 winding) {
1134+ if (endpoint.x <= reference.x) {
1135+ winding.x -= step * (float(endpoint.y <= center.y) - float(endpoint.y <= reference.y));
1136+ }
1137+ if (endpoint.y <= reference.y && endpoint.x <= center.x) {
1138+ winding.y += step;
1139+ }
1140+}
1141+
1142+float4 path_tile_fragment(PathTileFragmentInput input): SV_Target {
1143+ float2 center = floor(input.position.xy) + 0.5;
1144+ if (input.background.tag == 0u
1145+ && (any(center < input.curve_box.xy) || any(center > input.curve_box.zw))) {
1146+ return input.background.color0;
1147+ }
1148+ PathTile tile = path_tiles[input.tile_id];
1149+ PathPaint paint = path_paints[tile.paint];
1150+
1151+ float2 winding = float(tile.backdrop);
1152+ float2 weight = float2(0.0, 0.0);
1153+ [loop]
1154+ for (uint i = 0u; i < tile.curve_count; i++) {
1155+ PathCurve curve = path_curves[tile.curve_start + i];
1156+ if (min(curve.p0.x, curve.p1.x) >= center.x + 0.5) {
1157+ break;
1158+ }
1159+ if (curve.p0.y < center.y + 0.5) {
1160+ add_curve_winding(curve, center, winding, weight);
1161+ correct_for_endpoint(curve.p0, curve.sign, tile.reference, center, winding);
1162+ correct_for_endpoint(curve.p1, -curve.sign, tile.reference, center, winding);
1163+ }
1164+ }
1165+
1166+ // Weight the winding computed by each ray by its nearest crossing's distance from the pixel center,
1167+ // using Slug's technique.
1168+ float coverage = max(
1169+ abs(dot(winding, weight)) / max(weight.x + weight.y, 1.0 / 65536.0),
1170+ min(abs(winding.x), abs(winding.y)));
1171+ coverage = paint.even_odd != 0u
1172+ ? 1.0 - abs(1.0 - frac(coverage * 0.5) * 2.0)
1173+ : saturate(coverage);
1174+
1175+ if (coverage == 0.0) {
1176+ return float4(0.0, 0.0, 0.0, 0.0);
1177+ }
1178+
1179+ float4 color =
1180+ background_color(input.background, paint.color, paint.bounds, input.position.xy);
1181+ return float4(color.rgb, color.a * coverage);
1182+}
1183+
1184+/*
1185+**
1186+** Underlines
1187+**
1188+*/
1189+
1190+struct Underline {
1191+ uint order;
1192+ uint pad;
1193+ Bounds bounds;
1194+ Bounds content_mask;
1195+ Hsla color;
1196+ float thickness;
1197+ uint wavy;
1198+};
1199+
1200+struct UnderlineFragmentInput {
1201+ nointerpolation uint underline_id: TEXCOORD0;
1202+ float4 position: SV_Position;
1203+ nointerpolation float4 color: COLOR;
1204+};
1205+
1206+StructuredBuffer<Underline> underlines: register(t1);
1207+
1208+UnderlineFragmentInput underline_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {
1209+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1210+ uint underline_id = batch_start_index + instance_id;
1211+ Underline underline = underlines[underline_id];
1212+ ClippedVertex vertex = clip_to_mask(unit_vertex, underline.bounds, underline.content_mask);
1213+ float4 device_position = to_device_position_impl(vertex.position);
1214+ float4 color = hsla_to_rgba(underline.color);
1215+
1216+ UnderlineFragmentInput output;
1217+ output.position = device_position;
1218+ output.color = color;
1219+ output.underline_id = underline_id | (underline.wavy == 0u ? SIMPLE_PRIMITIVE_FLAG : 0u);
1220+ return output;
1221+}
1222+
1223+float4 underline_fragment(UnderlineFragmentInput input): SV_Target {
1224+ const float WAVE_FREQUENCY = 2.0;
1225+ const float WAVE_HEIGHT_RATIO = 0.8;
1226+
1227+ if ((input.underline_id & SIMPLE_PRIMITIVE_FLAG) != 0u) {
1228+ return input.color;
1229+ }
1230+
1231+ Underline underline = underlines[input.underline_id];
1232+ float half_thickness = underline.thickness * 0.5;
1233+ float2 origin = underline.bounds.origin;
1234+
1235+ float2 st = ((input.position.xy - origin) / underline.bounds.size.y) - float2(0., 0.5);
1236+ float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.y;
1237+ float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y;
1238+
1239+ float sine = sin(st.x * frequency) * amplitude;
1240+ float dSine = cos(st.x * frequency) * amplitude * frequency;
1241+ float distance = (st.y - sine) / sqrt(1. + dSine * dSine);
1242+ float distance_in_pixels = distance * underline.bounds.size.y;
1243+ float distance_from_top_border = distance_in_pixels - half_thickness;
1244+ float distance_from_bottom_border = distance_in_pixels + half_thickness;
1245+ float alpha = saturate(
1246+ 0.5 - max(-distance_from_bottom_border, distance_from_top_border));
1247+ return input.color * float4(1., 1., 1., alpha);
1248+}
1249+
1250+/*
1251+**
1252+** Monochrome sprites
1253+**
1254+*/
1255+
1256+struct MonochromeSprite {
1257+ uint order;
1258+ uint pad;
1259+ AtlasTile tile;
1260+ Bounds bounds;
1261+ Bounds content_mask;
1262+ Hsla color;
1263+ TransformationMatrix transformation;
1264+};
1265+
1266+struct MonochromeSpriteFragmentInput {
1267+ float4 position: SV_Position;
1268+ float2 tile_position: POSITION;
1269+ nointerpolation float4 color: COLOR;
1270+ float4 clip_distance: SV_ClipDistance;
1271+};
1272+
1273+StructuredBuffer<MonochromeSprite> mono_sprites: register(t1);
1274+
1275+MonochromeSpriteFragmentInput monochrome_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {
1276+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1277+ uint sprite_id = batch_start_index + instance_id;
1278+ MonochromeSprite sprite = mono_sprites[sprite_id];
1279+ float4 device_position =
1280+ to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
1281+ float4 clip_distance = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);
1282+ float2 tile_position = to_tile_position(unit_vertex, sprite.tile);
1283+ float4 color = hsla_to_rgba(sprite.color);
1284+
1285+ MonochromeSpriteFragmentInput output;
1286+ output.position = device_position;
1287+ output.tile_position = tile_position;
1288+ output.color = color;
1289+ output.clip_distance = clip_distance;
1290+ return output;
1291+}
1292+
1293+float4 monochrome_sprite_fragment(MonochromeSpriteFragmentInput input): SV_Target {
1294+ float sample = t_sprite.Sample(s_sprite, input.tile_position).r;
1295+ float alpha_corrected = apply_contrast_and_gamma_correction(sample, input.color.rgb, grayscale_enhanced_contrast, gamma_ratios);
1296+ return float4(input.color.rgb, input.color.a * alpha_corrected);
1297+}
1298+
1299+MonochromeSpriteFragmentInput subpixel_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {
1300+ return monochrome_sprite_vertex(vertex_id, instance_id);
1301+}
1302+
1303+SubpixelSpriteFragmentOutput subpixel_sprite_fragment(MonochromeSpriteFragmentInput input) {
1304+ float3 sample = t_sprite.Sample(s_sprite, input.tile_position).rgb;
1305+ if (is_bgr) {
1306+ sample = sample.bgr;
1307+ }
1308+ float3 alpha_corrected = apply_contrast_and_gamma_correction3(sample, input.color.rgb, subpixel_enhanced_contrast, gamma_ratios);
1309+
1310+ SubpixelSpriteFragmentOutput output;
1311+ output.foreground = float4(input.color.rgb, 1.0f);
1312+ output.alpha = float4(input.color.a * alpha_corrected, 1.0f);
1313+ return output;
1314+}
1315+
1316+/*
1317+**
1318+** Polychrome sprites
1319+**
1320+*/
1321+
1322+struct PolychromeSprite {
1323+ uint order;
1324+ uint pad;
1325+ AtlasTile tile;
1326+ uint grayscale;
1327+ float opacity;
1328+ Bounds bounds;
1329+ Bounds content_mask;
1330+ Corners corner_radii;
1331+};
1332+
1333+struct PolychromeSpriteFragmentInput {
1334+ nointerpolation uint sprite_id: TEXCOORD0;
1335+ float4 position: SV_Position;
1336+ float2 tile_position: POSITION;
1337+ nointerpolation float opacity: TEXCOORD1;
1338+};
1339+
1340+StructuredBuffer<PolychromeSprite> poly_sprites: register(t1);
1341+
1342+PolychromeSpriteFragmentInput polychrome_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {
1343+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1344+ uint sprite_id = batch_start_index + instance_id;
1345+ PolychromeSprite sprite = poly_sprites[sprite_id];
1346+ ClippedVertex vertex = clip_to_mask(unit_vertex, sprite.bounds, sprite.content_mask);
1347+ float4 device_position = to_device_position_impl(vertex.position);
1348+ float2 tile_position = to_tile_position(vertex.unit_vertex, sprite.tile);
1349+
1350+ PolychromeSpriteFragmentInput output;
1351+ output.position = device_position;
1352+ output.tile_position = tile_position;
1353+ bool simple = !has_rounded_corners(sprite.corner_radii) && sprite.grayscale == 0u;
1354+ output.sprite_id = sprite_id | (simple ? SIMPLE_PRIMITIVE_FLAG : 0u);
1355+ output.opacity = sprite.opacity;
1356+ return output;
1357+}
1358+
1359+float4 polychrome_sprite_fragment(PolychromeSpriteFragmentInput input): SV_Target {
1360+ float4 color = t_sprite.Sample(s_sprite, input.tile_position);
1361+ if ((input.sprite_id & SIMPLE_PRIMITIVE_FLAG) != 0u) {
1362+ return float4(color.rgb, color.a * input.opacity);
1363+ }
1364+
1365+ PolychromeSprite sprite = poly_sprites[input.sprite_id];
1366+ if (sprite.grayscale != 0u) {
1367+ color.rgb = dot(color.rgb, GRAYSCALE_FACTORS);
1368+ }
1369+ float distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
1370+ color.a *= input.opacity * saturate(0.5 - distance);
1371+ return color;
1372+}
vendor/gpui-pre-windows/src/system_notifications.rsadded+198 -0
@@ -0,0 +1,198 @@
1+//! System notifications as Windows toast notifications.
2+
3+use std::cell::RefCell;
4+use std::collections::{HashMap, hash_map::DefaultHasher};
5+use std::hash::{Hash as _, Hasher as _};
6+use std::rc::Rc;
7+
8+use futures::StreamExt as _;
9+use futures::channel::mpsc;
10+use gpui::{
11+ ForegroundExecutor, SharedString, SystemNotification, SystemNotificationResponse, Task,
12+};
13+use windows::Data::Xml::Dom::XmlDocument;
14+use windows::Foundation::TypedEventHandler;
15+use windows::UI::Notifications::{
16+ ToastActivatedEventArgs, ToastNotification, ToastNotificationManager, ToastNotifier,
17+};
18+use windows::core::{IInspectable, Interface as _, h};
19+
20+type ResponseCallback = Rc<RefCell<Option<Box<dyn FnMut(SystemNotificationResponse)>>>>;
21+
22+pub(crate) struct SystemNotificationState {
23+ notifier: Option<ToastNotifier>,
24+ active_toasts: HashMap<SharedString, ToastNotification>,
25+ response_sender: mpsc::UnboundedSender<SystemNotificationResponse>,
26+ response_receiver: Option<mpsc::UnboundedReceiver<SystemNotificationResponse>>,
27+ callback: ResponseCallback,
28+ _response_task: Option<Task<()>>,
29+}
30+
31+impl SystemNotificationState {
32+ pub(crate) fn new() -> Self {
33+ let (response_sender, response_receiver) = mpsc::unbounded();
34+ Self {
35+ notifier: None,
36+ active_toasts: HashMap::new(),
37+ response_sender,
38+ response_receiver: Some(response_receiver),
39+ callback: Rc::new(RefCell::new(None)),
40+ _response_task: None,
41+ }
42+ }
43+
44+ pub(crate) fn show(
45+ &mut self,
46+ has_package_identity: bool,
47+ app_identity: Option<(&str, &str)>,
48+ notification: SystemNotification,
49+ ) -> windows::core::Result<()> {
50+ let Some(notifier) = self.notifier(has_package_identity, app_identity)? else {
51+ return Ok(());
52+ };
53+
54+ let document = toast_document(&notification)?;
55+ let toast = ToastNotification::CreateToastNotification(&document)?;
56+ // Windows caps toast tags at 64 characters (post-Creators Update),
57+ // so hash the arbitrary GPUI tag down to a fixed-width value.
58+ let tag = {
59+ let mut hasher = DefaultHasher::new();
60+ notification.tag.hash(&mut hasher);
61+ format!("{:016x}", hasher.finish())
62+ };
63+ toast.SetTag(&tag.into())?;
64+
65+ let sender = self.response_sender.clone();
66+ let response_tag = notification.tag.clone();
67+ toast.Activated(&TypedEventHandler::<ToastNotification, IInspectable>::new(
68+ move |_sender, arguments| {
69+ let action_id = arguments
70+ .as_ref()
71+ .and_then(|arguments| arguments.cast::<ToastActivatedEventArgs>().ok())
72+ .and_then(|arguments| arguments.Arguments().ok())
73+ .filter(|arguments| !arguments.is_empty())
74+ .map(|arguments| SharedString::from(arguments.to_string()));
75+ sender
76+ .unbounded_send(SystemNotificationResponse {
77+ tag: response_tag.clone(),
78+ action_id,
79+ })
80+ .ok();
81+ Ok(())
82+ },
83+ ))?;
84+
85+ if let Some(previous) = self.active_toasts.remove(&notification.tag) {
86+ notifier.Hide(&previous)?;
87+ }
88+ notifier.Show(&toast)?;
89+ self.active_toasts.insert(notification.tag, toast);
90+ Ok(())
91+ }
92+
93+ pub(crate) fn dismiss(&mut self, tag: &str) {
94+ let Some(toast) = self.active_toasts.remove(tag) else {
95+ return;
96+ };
97+ let Some(notifier) = &self.notifier else {
98+ return;
99+ };
100+ if let Err(error) = notifier.Hide(&toast) {
101+ log::warn!("failed to dismiss system notification: {error}");
102+ }
103+ }
104+
105+ pub(crate) fn on_response(
106+ &mut self,
107+ executor: &ForegroundExecutor,
108+ callback: Box<dyn FnMut(SystemNotificationResponse)>,
109+ ) {
110+ *self.callback.borrow_mut() = Some(callback);
111+
112+ if let Some(mut receiver) = self.response_receiver.take() {
113+ let callback = self.callback.clone();
114+ self._response_task = Some(executor.spawn(async move {
115+ while let Some(response) = receiver.next().await {
116+ // Take the callback out for the call: it may re-enter the
117+ // platform (e.g. to dismiss the notification it was told
118+ // about) or replace itself.
119+ let taken = callback.borrow_mut().take();
120+ if let Some(mut taken) = taken {
121+ taken(response);
122+ callback.borrow_mut().get_or_insert(taken);
123+ }
124+ }
125+ }));
126+ }
127+ }
128+
129+ fn notifier(
130+ &mut self,
131+ has_package_identity: bool,
132+ app_identity: Option<(&str, &str)>,
133+ ) -> windows::core::Result<Option<ToastNotifier>> {
134+ if let Some(notifier) = &self.notifier {
135+ return Ok(Some(notifier.clone()));
136+ }
137+
138+ let notifier = if has_package_identity {
139+ ToastNotificationManager::CreateToastNotifier()?
140+ } else {
141+ let Some((app_identifier, app_name)) = app_identity else {
142+ log::warn!(
143+ "cannot show a system notification without an app identity; \
144+ call `App::set_app_identity` during startup"
145+ );
146+ return Ok(None);
147+ };
148+ register_app_user_model_id(app_identifier, app_name);
149+ ToastNotificationManager::CreateToastNotifierWithId(&app_identifier.into())?
150+ };
151+
152+ self.notifier = Some(notifier.clone());
153+ Ok(Some(notifier))
154+ }
155+}
156+
157+fn toast_document(notification: &SystemNotification) -> windows::core::Result<XmlDocument> {
158+ let document = XmlDocument::new()?;
159+ let toast = document.CreateElement(h!("toast"))?;
160+ document.AppendChild(&toast)?;
161+
162+ let visual = document.CreateElement(h!("visual"))?;
163+ toast.AppendChild(&visual)?;
164+ let binding = document.CreateElement(h!("binding"))?;
165+ binding.SetAttribute(h!("template"), h!("ToastGeneric"))?;
166+ visual.AppendChild(&binding)?;
167+ for text in [&notification.title, &notification.body] {
168+ let element = document.CreateElement(h!("text"))?;
169+ element.SetInnerText(&text.as_ref().into())?;
170+ binding.AppendChild(&element)?;
171+ }
172+
173+ if !notification.actions.is_empty() {
174+ let actions = document.CreateElement(h!("actions"))?;
175+ toast.AppendChild(&actions)?;
176+ for action in &notification.actions {
177+ let action_element = document.CreateElement(h!("action"))?;
178+ action_element.SetAttribute(h!("content"), &action.label.as_ref().into())?;
179+ action_element.SetAttribute(h!("arguments"), &action.id.as_ref().into())?;
180+ actions.AppendChild(&action_element)?;
181+ }
182+ }
183+
184+ let audio = document.CreateElement(h!("audio"))?;
185+ audio.SetAttribute(h!("silent"), h!("true"))?;
186+ toast.AppendChild(&audio)?;
187+ Ok(document)
188+}
189+
190+/// Registers the app's AUMID so toasts display correctly for an unpackaged app without a Start Menu shortcut.
191+fn register_app_user_model_id(app_identifier: &str, app_name: &str) {
192+ let result = windows_registry::CURRENT_USER
193+ .create(format!(r"Software\Classes\AppUserModelId\{app_identifier}"))
194+ .and_then(|key| key.set_string("DisplayName", app_name));
195+ if let Err(error) = result {
196+ log::warn!("failed to register AppUserModelID; notifications may not display: {error}");
197+ }
198+}
vendor/gpui-pre-windows/src/system_settings.rsadded+87 -0
@@ -0,0 +1,87 @@
1+use std::{
2+ cell::Cell,
3+ ffi::{c_uint, c_void},
4+};
5+
6+use gpui_util::ResultExt;
7+use windows::Win32::UI::WindowsAndMessaging::{
8+ SPI_GETWHEELSCROLLCHARS, SPI_GETWHEELSCROLLLINES, SYSTEM_PARAMETERS_INFO_ACTION,
9+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
10+};
11+
12+/// Windows settings pulled from SystemParametersInfo
13+/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
14+#[derive(Default, Debug, Clone)]
15+pub(crate) struct WindowsSystemSettings {
16+ pub(crate) mouse_wheel_settings: MouseWheelSettings,
17+}
18+
19+#[derive(Default, Debug, Clone)]
20+pub(crate) struct MouseWheelSettings {
21+ /// SEE: SPI_GETWHEELSCROLLCHARS
22+ pub(crate) wheel_scroll_chars: Cell<u32>,
23+ /// SEE: SPI_GETWHEELSCROLLLINES
24+ pub(crate) wheel_scroll_lines: Cell<u32>,
25+}
26+
27+impl WindowsSystemSettings {
28+ pub(crate) fn new() -> Self {
29+ let mut settings = Self::default();
30+ settings.init();
31+ settings
32+ }
33+
34+ fn init(&mut self) {
35+ self.mouse_wheel_settings.update();
36+ }
37+
38+ pub(crate) fn update(&self, wparam: usize) {
39+ match SYSTEM_PARAMETERS_INFO_ACTION(wparam as u32) {
40+ SPI_GETWHEELSCROLLLINES | SPI_GETWHEELSCROLLCHARS => self.update_mouse_wheel_settings(),
41+ _ => {}
42+ }
43+ }
44+
45+ fn update_mouse_wheel_settings(&self) {
46+ self.mouse_wheel_settings.update();
47+ }
48+}
49+
50+impl MouseWheelSettings {
51+ fn update(&self) {
52+ self.update_wheel_scroll_chars();
53+ self.update_wheel_scroll_lines();
54+ }
55+
56+ fn update_wheel_scroll_chars(&self) {
57+ let mut value = c_uint::default();
58+ let result = unsafe {
59+ SystemParametersInfoW(
60+ SPI_GETWHEELSCROLLCHARS,
61+ 0,
62+ Some((&mut value) as *mut c_uint as *mut c_void),
63+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
64+ )
65+ };
66+
67+ if result.log_err() != None && self.wheel_scroll_chars.get() != value {
68+ self.wheel_scroll_chars.set(value);
69+ }
70+ }
71+
72+ fn update_wheel_scroll_lines(&self) {
73+ let mut value = c_uint::default();
74+ let result = unsafe {
75+ SystemParametersInfoW(
76+ SPI_GETWHEELSCROLLLINES,
77+ 0,
78+ Some((&mut value) as *mut c_uint as *mut c_void),
79+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
80+ )
81+ };
82+
83+ if result.log_err() != None && self.wheel_scroll_lines.get() != value {
84+ self.wheel_scroll_lines.set(value);
85+ }
86+ }
87+}
vendor/gpui-pre-windows/src/util.rsadded+191 -0
@@ -0,0 +1,191 @@
1+use std::sync::OnceLock;
2+
3+use anyhow::Context;
4+use gpui_util::ResultExt;
5+use windows::{
6+ UI::{
7+ Color,
8+ ViewManagement::{UIColorType, UISettings},
9+ },
10+ Win32::{
11+ Foundation::*, Graphics::Dwm::*, System::LibraryLoader::LoadLibraryA,
12+ UI::WindowsAndMessaging::*,
13+ },
14+ core::{BOOL, PCSTR},
15+};
16+
17+use crate::*;
18+use gpui::*;
19+
20+pub(crate) trait HiLoWord {
21+ fn hiword(&self) -> u16;
22+ fn loword(&self) -> u16;
23+ fn signed_hiword(&self) -> i16;
24+ fn signed_loword(&self) -> i16;
25+}
26+
27+impl HiLoWord for WPARAM {
28+ fn hiword(&self) -> u16 {
29+ ((self.0 >> 16) & 0xFFFF) as u16
30+ }
31+
32+ fn loword(&self) -> u16 {
33+ (self.0 & 0xFFFF) as u16
34+ }
35+
36+ fn signed_hiword(&self) -> i16 {
37+ ((self.0 >> 16) & 0xFFFF) as i16
38+ }
39+
40+ fn signed_loword(&self) -> i16 {
41+ (self.0 & 0xFFFF) as i16
42+ }
43+}
44+
45+impl HiLoWord for LPARAM {
46+ fn hiword(&self) -> u16 {
47+ ((self.0 >> 16) & 0xFFFF) as u16
48+ }
49+
50+ fn loword(&self) -> u16 {
51+ (self.0 & 0xFFFF) as u16
52+ }
53+
54+ fn signed_hiword(&self) -> i16 {
55+ ((self.0 >> 16) & 0xFFFF) as i16
56+ }
57+
58+ fn signed_loword(&self) -> i16 {
59+ (self.0 & 0xFFFF) as i16
60+ }
61+}
62+
63+pub(crate) unsafe fn get_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX) -> isize {
64+ #[cfg(target_pointer_width = "64")]
65+ unsafe {
66+ GetWindowLongPtrW(hwnd, nindex)
67+ }
68+ #[cfg(target_pointer_width = "32")]
69+ unsafe {
70+ GetWindowLongW(hwnd, nindex) as isize
71+ }
72+}
73+
74+pub(crate) unsafe fn set_window_long(
75+ hwnd: HWND,
76+ nindex: WINDOW_LONG_PTR_INDEX,
77+ dwnewlong: isize,
78+) -> isize {
79+ #[cfg(target_pointer_width = "64")]
80+ unsafe {
81+ SetWindowLongPtrW(hwnd, nindex, dwnewlong)
82+ }
83+ #[cfg(target_pointer_width = "32")]
84+ unsafe {
85+ SetWindowLongW(hwnd, nindex, dwnewlong as i32) as isize
86+ }
87+}
88+
89+pub(crate) fn windows_credentials_target_name(url: &str) -> String {
90+ format!("zed:url={}", url)
91+}
92+
93+pub(crate) fn load_cursor(style: CursorStyle) -> Option<HCURSOR> {
94+ static ARROW: OnceLock<SafeCursor> = OnceLock::new();
95+ static IBEAM: OnceLock<SafeCursor> = OnceLock::new();
96+ static CROSS: OnceLock<SafeCursor> = OnceLock::new();
97+ static HAND: OnceLock<SafeCursor> = OnceLock::new();
98+ static SIZEWE: OnceLock<SafeCursor> = OnceLock::new();
99+ static SIZENS: OnceLock<SafeCursor> = OnceLock::new();
100+ static SIZENWSE: OnceLock<SafeCursor> = OnceLock::new();
101+ static SIZENESW: OnceLock<SafeCursor> = OnceLock::new();
102+ static NO: OnceLock<SafeCursor> = OnceLock::new();
103+ let (lock, name) = match style {
104+ CursorStyle::IBeam | CursorStyle::IBeamCursorForVerticalLayout => (&IBEAM, IDC_IBEAM),
105+ CursorStyle::Crosshair => (&CROSS, IDC_CROSS),
106+ CursorStyle::PointingHand | CursorStyle::DragLink => (&HAND, IDC_HAND),
107+ CursorStyle::ResizeLeft
108+ | CursorStyle::ResizeRight
109+ | CursorStyle::ResizeLeftRight
110+ | CursorStyle::ResizeColumn => (&SIZEWE, IDC_SIZEWE),
111+ CursorStyle::ResizeUp
112+ | CursorStyle::ResizeDown
113+ | CursorStyle::ResizeUpDown
114+ | CursorStyle::ResizeRow => (&SIZENS, IDC_SIZENS),
115+ CursorStyle::ResizeUpLeftDownRight => (&SIZENWSE, IDC_SIZENWSE),
116+ CursorStyle::ResizeUpRightDownLeft => (&SIZENESW, IDC_SIZENESW),
117+ CursorStyle::OperationNotAllowed => (&NO, IDC_NO),
118+ _ => (&ARROW, IDC_ARROW),
119+ };
120+ Some(
121+ *(*lock.get_or_init(|| {
122+ HCURSOR(
123+ unsafe { LoadImageW(None, name, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED) }
124+ .log_err()
125+ .unwrap_or_default()
126+ .0,
127+ )
128+ .into()
129+ })),
130+ )
131+}
132+
133+/// This function is used to configure the dark mode for the window built-in title bar.
134+pub(crate) fn configure_dwm_dark_mode(hwnd: HWND, appearance: WindowAppearance) {
135+ let dark_mode_enabled: BOOL = match appearance {
136+ WindowAppearance::Dark | WindowAppearance::VibrantDark => true.into(),
137+ WindowAppearance::Light | WindowAppearance::VibrantLight => false.into(),
138+ };
139+ unsafe {
140+ DwmSetWindowAttribute(
141+ hwnd,
142+ DWMWA_USE_IMMERSIVE_DARK_MODE,
143+ &dark_mode_enabled as *const _ as _,
144+ std::mem::size_of::<BOOL>() as u32,
145+ )
146+ .log_err();
147+ }
148+}
149+
150+#[inline]
151+pub(crate) fn logical_point(x: f32, y: f32, scale_factor: f32) -> Point<Pixels> {
152+ Point {
153+ x: px(x / scale_factor),
154+ y: px(y / scale_factor),
155+ }
156+}
157+
158+// https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/apply-windows-themes
159+#[inline]
160+pub(crate) fn system_appearance() -> Result<WindowAppearance> {
161+ let ui_settings = UISettings::new()?;
162+ let foreground_color = ui_settings.GetColorValue(UIColorType::Foreground)?;
163+ // If the foreground is light, then is_color_light will evaluate to true,
164+ // meaning Dark mode is enabled.
165+ if is_color_light(&foreground_color) {
166+ Ok(WindowAppearance::Dark)
167+ } else {
168+ Ok(WindowAppearance::Light)
169+ }
170+}
171+
172+#[inline(always)]
173+fn is_color_light(color: &Color) -> bool {
174+ ((5 * color.G as u32) + (2 * color.R as u32) + color.B as u32) > (8 * 128)
175+}
176+
177+pub(crate) fn with_dll_library<R, F>(dll_name: PCSTR, f: F) -> Result<R>
178+where
179+ F: FnOnce(HMODULE) -> Result<R>,
180+{
181+ let library = unsafe {
182+ LoadLibraryA(dll_name).with_context(|| format!("Loading dll: {}", dll_name.display()))?
183+ };
184+ let result = f(library);
185+ unsafe {
186+ FreeLibrary(library)
187+ .with_context(|| format!("Freeing dll: {}", dll_name.display()))
188+ .log_err();
189+ }
190+ result
191+}
vendor/gpui-pre-windows/src/vsync.rsadded+119 -0
@@ -0,0 +1,119 @@
1+use std::{
2+ sync::LazyLock,
3+ time::{Duration, Instant},
4+};
5+
6+use anyhow::{Context, Result};
7+use gpui::FrameRequestSource;
8+use gpui_util::ResultExt;
9+use windows::Win32::{
10+ Foundation::HWND,
11+ Graphics::Dwm::{DWM_TIMING_INFO, DwmFlush, DwmGetCompositionTimingInfo},
12+ System::Performance::QueryPerformanceFrequency,
13+};
14+
15+static QPC_TICKS_PER_SECOND: LazyLock<u64> = LazyLock::new(|| {
16+ let mut frequency = 0;
17+ // On systems that run Windows XP or later, the function will always succeed and
18+ // will thus never return zero.
19+ unsafe { QueryPerformanceFrequency(&mut frequency).unwrap() };
20+ frequency as u64
21+});
22+
23+const VSYNC_INTERVAL_THRESHOLD: Duration = Duration::from_millis(1);
24+const DEFAULT_VSYNC_INTERVAL: Duration = Duration::from_micros(16_666); // ~60Hz
25+
26+pub(crate) struct VSyncProvider {
27+ interval: Duration,
28+ f: Box<dyn Fn() -> bool>,
29+}
30+
31+impl VSyncProvider {
32+ pub(crate) fn new() -> Self {
33+ let interval = get_dwm_interval()
34+ .context("Failed to get DWM interval")
35+ .log_err()
36+ .unwrap_or(DEFAULT_VSYNC_INTERVAL);
37+ let f = Box::new(|| unsafe { DwmFlush().is_ok() });
38+ Self { interval, f }
39+ }
40+
41+ pub(crate) fn wait_for_vsync(&self) -> FrameRequestSource {
42+ let vsync_start = Instant::now();
43+ let wait_succeeded = (self.f)();
44+ let elapsed = vsync_start.elapsed();
45+ // DwmFlush and DCompositionWaitForCompositorClock returns very early
46+ // instead of waiting until vblank when the monitor goes to sleep or is
47+ // unplugged (nothing to present due to desktop occlusion). We use 1ms as
48+ // a threshold for the duration of the wait functions and fallback to
49+ // Sleep() if it returns before that. This could happen during normal
50+ // operation for the first call after the vsync thread becomes non-idle,
51+ // but it shouldn't happen often.
52+ if !wait_succeeded || elapsed < VSYNC_INTERVAL_THRESHOLD {
53+ log::trace!("VSyncProvider::wait_for_vsync() took less time than expected");
54+ std::thread::sleep(self.interval);
55+ FrameRequestSource::LocalSchedule
56+ } else {
57+ FrameRequestSource::NativeCallback
58+ }
59+ }
60+}
61+
62+fn get_dwm_interval() -> Result<Duration> {
63+ let mut timing_info = DWM_TIMING_INFO {
64+ cbSize: std::mem::size_of::<DWM_TIMING_INFO>() as u32,
65+ ..Default::default()
66+ };
67+ unsafe { DwmGetCompositionTimingInfo(HWND::default(), &mut timing_info) }?;
68+ let interval = retrieve_duration(timing_info.qpcRefreshPeriod, *QPC_TICKS_PER_SECOND);
69+ // Check for interval values that are impossibly low. A 29 microsecond
70+ // interval was seen (from a qpcRefreshPeriod of 60).
71+ if interval < VSYNC_INTERVAL_THRESHOLD {
72+ Ok(retrieve_duration(
73+ timing_info.rateRefresh.uiDenominator as u64,
74+ timing_info.rateRefresh.uiNumerator as u64,
75+ ))
76+ } else {
77+ Ok(interval)
78+ }
79+}
80+
81+#[inline]
82+fn retrieve_duration(counts: u64, ticks_per_second: u64) -> Duration {
83+ let ticks_per_microsecond = ticks_per_second / 1_000_000;
84+ Duration::from_micros(counts / ticks_per_microsecond)
85+}
86+
87+#[cfg(test)]
88+mod tests {
89+ use super::*;
90+
91+ #[test]
92+ fn successful_compositor_wait_reports_native_callback() {
93+ let provider = VSyncProvider {
94+ interval: Duration::ZERO,
95+ f: Box::new(|| {
96+ std::thread::sleep(VSYNC_INTERVAL_THRESHOLD * 2);
97+ true
98+ }),
99+ };
100+
101+ assert_eq!(
102+ provider.wait_for_vsync(),
103+ FrameRequestSource::NativeCallback
104+ );
105+ }
106+
107+ #[test]
108+ fn failed_compositor_wait_reports_local_schedule_even_after_threshold() {
109+ let provider = VSyncProvider {
110+ interval: Duration::ZERO,
111+ f: Box::new(|| {
112+ std::thread::sleep(VSYNC_INTERVAL_THRESHOLD * 2);
113+ false
114+ }),
115+ };
116+
117+ assert_eq!(provider.wait_for_vsync(), FrameRequestSource::LocalSchedule);
118+ }
119+}
vendor/gpui-pre-windows/src/window.rsadded+1742 -0
@@ -0,0 +1,1742 @@
1+#![deny(unsafe_op_in_unsafe_fn)]
2+
3+use std::{
4+ cell::{Cell, RefCell},
5+ num::NonZeroIsize,
6+ path::PathBuf,
7+ rc::{Rc, Weak},
8+ str::FromStr,
9+ sync::{Arc, Once, atomic::AtomicBool},
10+ time::{Duration, Instant},
11+};
12+
13+use anyhow::{Context as _, Result};
14+use futures::channel::oneshot::{self, Receiver};
15+use gpui_util::ResultExt;
16+use raw_window_handle as rwh;
17+use smallvec::SmallVec;
18+use windows::{
19+ Win32::{
20+ Foundation::*,
21+ Graphics::Dwm::*,
22+ Graphics::Gdi::*,
23+ System::{
24+ Com::*, Diagnostics::Debug::MessageBeep, LibraryLoader::*, Ole::*, SystemServices::*,
25+ },
26+ UI::{Controls::*, HiDpi::*, Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
27+ },
28+ core::*,
29+};
30+
31+use crate::direct_manipulation::DirectManipulationHandler;
32+use crate::*;
33+use gpui::*;
34+
35+pub(crate) struct WindowsWindow(pub Rc<WindowsWindowInner>);
36+
37+impl std::ops::Deref for WindowsWindow {
38+ type Target = WindowsWindowInner;
39+
40+ fn deref(&self) -> &Self::Target {
41+ &self.0
42+ }
43+}
44+
45+pub struct WindowsWindowState {
46+ pub origin: Cell<Point<Pixels>>,
47+ pub logical_size: Cell<Size<Pixels>>,
48+ pub min_size: Option<Size<Pixels>>,
49+ pub fullscreen_restore_bounds: Cell<Bounds<Pixels>>,
50+ pub border_offset: WindowBorderOffset,
51+ pub appearance: Cell<WindowAppearance>,
52+ pub background_appearance: Cell<WindowBackgroundAppearance>,
53+ pub scale_factor: Cell<f32>,
54+ pub restore_from_minimized: Cell<Option<Box<dyn FnMut(RequestFrameOptions)>>>,
55+
56+ pub callbacks: Callbacks,
57+ pub frame_signal: Arc<PlatformFrameSignal>,
58+ pub input_handler: Cell<Option<PlatformInputHandler>>,
59+ pub ime_enabled: Cell<bool>,
60+ pub pending_surrogate: Cell<Option<u16>>,
61+ pub last_reported_modifiers: Cell<Option<Modifiers>>,
62+ pub last_reported_capslock: Cell<Option<Capslock>>,
63+ pub hovered: Cell<bool>,
64+ pub last_visibility: Cell<Option<WindowVisibility>>,
65+ pub direct_manipulation: DirectManipulationHandler,
66+
67+ pub renderer: RefCell<DirectXRenderer>,
68+ /// Set when the next `draw_window` call must be treated as a forced
69+ /// render. Used after a GPU device-lost recovery, where the next frame
70+ /// must both re-enable drawing (via `mark_drawable`) and bypass the GPUI
71+ /// view cache (which would otherwise replay stale atlas tile references
72+ /// from the previous frame and panic in `DirectXAtlasTextures::texture`),
73+ /// and when a forced render was requested while another draw was in
74+ /// progress and had to be deferred.
75+ pub force_render_pending: Cell<bool>,
76+
77+ pub click_state: ClickState,
78+ pub current_cursor: Cell<Option<HCURSOR>>,
79+ /// Shared with [`WindowsPlatformState::cursor_visible`].
80+ pub cursor_visible: Arc<AtomicBool>,
81+ pub nc_button_pressed: Cell<Option<u32>>,
82+
83+ pub display: Cell<WindowsDisplay>,
84+ /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices
85+ /// as resizing them has failed, causing us to have lost at least the render target.
86+ pub invalidate_devices: Arc<AtomicBool>,
87+ /// Shared with [`WindowsPlatformState::draw_coordinator`] and every other window.
88+ pub(crate) draw_coordinator: Rc<DrawCoordinator>,
89+ fullscreen: Cell<Option<StyleAndBounds>>,
90+ initial_placement: Cell<Option<WindowOpenStatus>>,
91+ hwnd: HWND,
92+ pub(crate) a11y: RefCell<Option<A11yState>>,
93+ pub mouse_position: Cell<Point<Pixels>>,
94+}
95+
96+pub(crate) struct WindowsWindowInner {
97+ hwnd: HWND,
98+ pub(crate) dialog_owner: Rc<crate::dialog::DialogOwner>,
99+ drop_target_helper: IDropTargetHelper,
100+ pub(crate) state: WindowsWindowState,
101+ system_settings: WindowsSystemSettings,
102+ pub(crate) handle: AnyWindowHandle,
103+ pub(crate) hide_title_bar: bool,
104+ pub(crate) is_movable: bool,
105+ pub(crate) is_resizable: bool,
106+ pub(crate) is_minimizable: bool,
107+ pub(crate) executor: ForegroundExecutor,
108+ pub(crate) validation_number: usize,
109+ pub(crate) main_receiver: PriorityQueueReceiver<RunnableVariant>,
110+ pub(crate) platform_window_handle: HWND,
111+ pub(crate) parent_hwnd: Option<HWND>,
112+}
113+
114+impl WindowsWindowState {
115+ fn new(
116+ hwnd: HWND,
117+ directx_devices: &DirectXDevices,
118+ window_params: &CREATESTRUCTW,
119+ current_cursor: Option<HCURSOR>,
120+ cursor_visible: Arc<AtomicBool>,
121+ display: WindowsDisplay,
122+ min_size: Option<Size<Pixels>>,
123+ appearance: WindowAppearance,
124+ disable_direct_composition: bool,
125+ invalidate_devices: Arc<AtomicBool>,
126+ draw_coordinator: Rc<DrawCoordinator>,
127+ ) -> Result<Self> {
128+ let scale_factor = {
129+ let monitor_dpi = unsafe { GetDpiForWindow(hwnd) } as f32;
130+ monitor_dpi / USER_DEFAULT_SCREEN_DPI as f32
131+ };
132+ let origin = logical_point(window_params.x as f32, window_params.y as f32, scale_factor);
133+ let logical_size = {
134+ let physical_size = size(
135+ DevicePixels(window_params.cx),
136+ DevicePixels(window_params.cy),
137+ );
138+ physical_size.to_pixels(scale_factor)
139+ };
140+ let fullscreen_restore_bounds = Bounds {
141+ origin,
142+ size: logical_size,
143+ };
144+ let border_offset = WindowBorderOffset::default();
145+ let restore_from_minimized = None;
146+ let renderer = DirectXRenderer::new(hwnd, directx_devices, disable_direct_composition)
147+ .context("Creating DirectX renderer")?;
148+ let callbacks = Callbacks::default();
149+ let input_handler = None;
150+ let pending_surrogate = None;
151+ let last_reported_modifiers = None;
152+ let last_reported_capslock = None;
153+ let hovered = false;
154+ let click_state = ClickState::new();
155+ let nc_button_pressed = None;
156+ let fullscreen = None;
157+ let initial_placement = None;
158+
159+ let direct_manipulation = DirectManipulationHandler::new(hwnd, scale_factor)
160+ .context("initializing Direct Manipulation")?;
161+
162+ Ok(Self {
163+ origin: Cell::new(origin),
164+ logical_size: Cell::new(logical_size),
165+ fullscreen_restore_bounds: Cell::new(fullscreen_restore_bounds),
166+ border_offset,
167+ appearance: Cell::new(appearance),
168+ background_appearance: Cell::new(WindowBackgroundAppearance::Opaque),
169+ scale_factor: Cell::new(scale_factor),
170+ restore_from_minimized: Cell::new(restore_from_minimized),
171+ min_size,
172+ callbacks,
173+ frame_signal: Arc::new(PlatformFrameSignal::new()),
174+ input_handler: Cell::new(input_handler),
175+ ime_enabled: Cell::new(true),
176+ pending_surrogate: Cell::new(pending_surrogate),
177+ last_reported_modifiers: Cell::new(last_reported_modifiers),
178+ last_reported_capslock: Cell::new(last_reported_capslock),
179+ hovered: Cell::new(hovered),
180+ last_visibility: Cell::new(None),
181+ renderer: RefCell::new(renderer),
182+ force_render_pending: Cell::new(false),
183+ click_state,
184+ current_cursor: Cell::new(current_cursor),
185+ cursor_visible,
186+ nc_button_pressed: Cell::new(nc_button_pressed),
187+ display: Cell::new(display),
188+ fullscreen: Cell::new(fullscreen),
189+ initial_placement: Cell::new(initial_placement),
190+ hwnd,
191+ invalidate_devices,
192+ draw_coordinator,
193+ direct_manipulation,
194+ a11y: RefCell::new(None),
195+ mouse_position: Cell::new(Point::default()),
196+ })
197+ }
198+
199+ #[inline]
200+ pub(crate) fn is_fullscreen(&self) -> bool {
201+ self.fullscreen.get().is_some()
202+ }
203+
204+ pub(crate) fn is_maximized(&self) -> bool {
205+ !self.is_fullscreen() && unsafe { IsZoomed(self.hwnd) }.as_bool()
206+ }
207+
208+ fn bounds(&self) -> Bounds<Pixels> {
209+ Bounds {
210+ origin: self.origin.get(),
211+ size: self.logical_size.get(),
212+ }
213+ }
214+
215+ // Calculate the bounds used for saving and whether the window is maximized.
216+ fn calculate_window_bounds(&self) -> (Bounds<Pixels>, bool) {
217+ let placement = unsafe {
218+ let mut placement = WINDOWPLACEMENT {
219+ length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
220+ ..Default::default()
221+ };
222+ GetWindowPlacement(self.hwnd, &mut placement)
223+ .context("failed to get window placement")
224+ .log_err();
225+ placement
226+ };
227+ (
228+ calculate_client_rect(
229+ placement.rcNormalPosition,
230+ &self.border_offset,
231+ self.scale_factor.get(),
232+ ),
233+ placement.showCmd == SW_SHOWMAXIMIZED.0 as u32,
234+ )
235+ }
236+
237+ fn window_bounds(&self) -> WindowBounds {
238+ let (bounds, maximized) = self.calculate_window_bounds();
239+
240+ if self.is_fullscreen() {
241+ WindowBounds::Fullscreen(self.fullscreen_restore_bounds.get())
242+ } else if maximized {
243+ WindowBounds::Maximized(bounds)
244+ } else {
245+ WindowBounds::Windowed(bounds)
246+ }
247+ }
248+
249+ /// get the logical size of the app's drawable area.
250+ ///
251+ /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
252+ /// whether the mouse collides with other elements of GPUI).
253+ fn content_size(&self) -> Size<Pixels> {
254+ self.logical_size.get()
255+ }
256+}
257+
258+impl WindowsWindowInner {
259+ /// Whether the window is being presented: shown and not minimized. Windows
260+ /// has no notification for a window fully covered by other windows, so
261+ /// that case reports `Visible`.
262+ pub(crate) fn visibility(&self) -> WindowVisibility {
263+ let is_visible =
264+ unsafe { IsWindowVisible(self.hwnd).as_bool() && !IsIconic(self.hwnd).as_bool() };
265+ if is_visible {
266+ WindowVisibility::Visible
267+ } else {
268+ WindowVisibility::Hidden
269+ }
270+ }
271+
272+ fn new(context: &mut WindowCreateContext, hwnd: HWND, cs: &CREATESTRUCTW) -> Result<Rc<Self>> {
273+ let state = WindowsWindowState::new(
274+ hwnd,
275+ &context.directx_devices,
276+ cs,
277+ context.current_cursor,
278+ context.cursor_visible.clone(),
279+ context.display,
280+ context.min_size,
281+ context.appearance,
282+ context.disable_direct_composition,
283+ context.invalidate_devices.clone(),
284+ context.draw_coordinator.clone(),
285+ )?;
286+
287+ Ok(Rc::new(Self {
288+ hwnd,
289+ dialog_owner: crate::dialog::DialogOwner::new(hwnd),
290+ drop_target_helper: context.drop_target_helper.clone(),
291+ state,
292+ handle: context.handle,
293+ hide_title_bar: context.hide_title_bar,
294+ is_movable: context.is_movable,
295+ is_resizable: context.is_resizable,
296+ is_minimizable: context.is_minimizable,
297+ executor: context.executor.clone(),
298+ validation_number: context.validation_number,
299+ main_receiver: context.main_receiver.clone(),
300+ platform_window_handle: context.platform_window_handle,
301+ system_settings: WindowsSystemSettings::new(),
302+ parent_hwnd: context.parent_hwnd,
303+ }))
304+ }
305+
306+ fn toggle_fullscreen(self: &Rc<Self>) {
307+ let this = self.clone();
308+ self.executor
309+ .spawn(async move {
310+ let StyleAndBounds {
311+ style,
312+ x,
313+ y,
314+ cx,
315+ cy,
316+ } = match this.state.fullscreen.take() {
317+ Some(state) => state,
318+ None => {
319+ let (window_bounds, _) = this.state.calculate_window_bounds();
320+ this.state.fullscreen_restore_bounds.set(window_bounds);
321+
322+ let style =
323+ WINDOW_STYLE(unsafe { get_window_long(this.hwnd, GWL_STYLE) } as _);
324+ let mut rc = RECT::default();
325+ unsafe { GetWindowRect(this.hwnd, &mut rc) }
326+ .context("failed to get window rect")
327+ .log_err();
328+ let _ = this.state.fullscreen.set(Some(StyleAndBounds {
329+ style,
330+ x: rc.left,
331+ y: rc.top,
332+ cx: rc.right - rc.left,
333+ cy: rc.bottom - rc.top,
334+ }));
335+ let style = style
336+ & !(WS_THICKFRAME
337+ | WS_SYSMENU
338+ | WS_MAXIMIZEBOX
339+ | WS_MINIMIZEBOX
340+ | WS_CAPTION);
341+ let physical_bounds = this.state.display.get().physical_bounds();
342+ StyleAndBounds {
343+ style,
344+ x: physical_bounds.left().0,
345+ y: physical_bounds.top().0,
346+ cx: physical_bounds.size.width.0,
347+ cy: physical_bounds.size.height.0,
348+ }
349+ }
350+ };
351+ set_non_rude_hwnd(this.hwnd, !this.state.is_fullscreen());
352+ unsafe { set_window_long(this.hwnd, GWL_STYLE, style.0 as isize) };
353+ unsafe {
354+ SetWindowPos(
355+ this.hwnd,
356+ None,
357+ x,
358+ y,
359+ cx,
360+ cy,
361+ SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER,
362+ )
363+ }
364+ .log_err();
365+ })
366+ .detach();
367+ }
368+
369+ fn set_window_placement(self: &Rc<Self>) -> Result<()> {
370+ let Some(open_status) = self.state.initial_placement.take() else {
371+ return Ok(());
372+ };
373+ match open_status.state {
374+ WindowOpenState::Maximized => unsafe {
375+ SetWindowPlacement(self.hwnd, &open_status.placement)
376+ .context("failed to set window placement")?;
377+ ShowWindowAsync(self.hwnd, SW_MAXIMIZE).ok()?;
378+ },
379+ WindowOpenState::Fullscreen => {
380+ unsafe {
381+ SetWindowPlacement(self.hwnd, &open_status.placement)
382+ .context("failed to set window placement")?
383+ };
384+ self.toggle_fullscreen();
385+ }
386+ WindowOpenState::Windowed => unsafe {
387+ SetWindowPlacement(self.hwnd, &open_status.placement)
388+ .context("failed to set window placement")?;
389+ },
390+ }
391+ Ok(())
392+ }
393+
394+ pub(crate) fn system_settings(&self) -> &WindowsSystemSettings {
395+ &self.system_settings
396+ }
397+}
398+
399+#[derive(Default)]
400+pub(crate) struct Callbacks {
401+ pub(crate) request_frame: Cell<Option<Box<dyn FnMut(RequestFrameOptions)>>>,
402+ pub(crate) input: Cell<Option<Box<dyn FnMut(PlatformInput) -> DispatchEventResult>>>,
403+ pub(crate) active_status_change: Cell<Option<Box<dyn FnMut(bool)>>>,
404+ pub(crate) visibility_change: Cell<Option<Box<dyn FnMut(WindowVisibility)>>>,
405+ pub(crate) hovered_status_change: Cell<Option<Box<dyn FnMut(bool)>>>,
406+ pub(crate) resize: Cell<Option<Box<dyn FnMut(Size<Pixels>, f32)>>>,
407+ pub(crate) moved: Cell<Option<Box<dyn FnMut()>>>,
408+ pub(crate) display_changed: Cell<Option<Box<dyn FnMut()>>>,
409+ pub(crate) should_close: Cell<Option<Box<dyn FnMut() -> bool>>>,
410+ pub(crate) close: Cell<Option<Box<dyn FnOnce()>>>,
411+ pub(crate) hit_test_window_control: Cell<Option<Box<dyn FnMut() -> Option<WindowControlArea>>>>,
412+ pub(crate) appearance_changed: Cell<Option<Box<dyn FnMut()>>>,
413+}
414+
415+struct WindowCreateContext {
416+ inner: Option<Result<Rc<WindowsWindowInner>>>,
417+ handle: AnyWindowHandle,
418+ hide_title_bar: bool,
419+ display: WindowsDisplay,
420+ is_movable: bool,
421+ is_resizable: bool,
422+ is_minimizable: bool,
423+ min_size: Option<Size<Pixels>>,
424+ executor: ForegroundExecutor,
425+ current_cursor: Option<HCURSOR>,
426+ cursor_visible: Arc<AtomicBool>,
427+ drop_target_helper: IDropTargetHelper,
428+ validation_number: usize,
429+ main_receiver: PriorityQueueReceiver<RunnableVariant>,
430+ platform_window_handle: HWND,
431+ appearance: WindowAppearance,
432+ disable_direct_composition: bool,
433+ directx_devices: DirectXDevices,
434+ invalidate_devices: Arc<AtomicBool>,
435+ draw_coordinator: Rc<DrawCoordinator>,
436+ parent_hwnd: Option<HWND>,
437+}
438+
439+impl WindowsWindow {
440+ pub(crate) fn new(
441+ handle: AnyWindowHandle,
442+ params: WindowParams,
443+ creation_info: WindowCreationInfo,
444+ ) -> Result<Self> {
445+ // Native popups are not implemented on Windows yet. Rejecting lets callers fall back to
446+ // gpui's in-window popovers.
447+ if let WindowKind::AnchoredPopup(_) = params.kind {
448+ return Err(popup::PopupNotSupportedError.into());
449+ }
450+
451+ let WindowCreationInfo {
452+ icon,
453+ executor,
454+ current_cursor,
455+ cursor_visible,
456+ drop_target_helper,
457+ validation_number,
458+ main_receiver,
459+ platform_window_handle,
460+ disable_direct_composition,
461+ directx_devices,
462+ invalidate_devices,
463+ draw_coordinator,
464+ } = creation_info;
465+ register_window_class(icon);
466+ let parent_hwnd = if params.kind == WindowKind::Dialog {
467+ let parent_window = unsafe { GetActiveWindow() };
468+ if parent_window.is_invalid() {
469+ None
470+ } else {
471+ // Disable the parent window to make this dialog modal
472+ unsafe {
473+ EnableWindow(parent_window, false).as_bool();
474+ };
475+ Some(parent_window)
476+ }
477+ } else {
478+ None
479+ };
480+ let hide_title_bar = params
481+ .titlebar
482+ .as_ref()
483+ .map(|titlebar| titlebar.appears_transparent)
484+ .unwrap_or(true);
485+ let window_name = HSTRING::from(
486+ params
487+ .titlebar
488+ .as_ref()
489+ .and_then(|titlebar| titlebar.title.as_ref())
490+ .map(|title| title.as_ref())
491+ .unwrap_or(""),
492+ );
493+
494+ let (mut dwexstyle, dwstyle) = if params.kind == WindowKind::PopUp {
495+ (WS_EX_TOOLWINDOW | WS_EX_TOPMOST, WINDOW_STYLE(0x0))
496+ } else {
497+ let mut dwstyle = WS_SYSMENU;
498+
499+ if params.is_resizable {
500+ dwstyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
501+ }
502+
503+ if params.is_minimizable {
504+ dwstyle |= WS_MINIMIZEBOX;
505+ }
506+ let dwexstyle = if params.kind == WindowKind::Dialog {
507+ dwstyle |= WS_POPUP | WS_CAPTION;
508+ WS_EX_DLGMODALFRAME
509+ } else {
510+ WS_EX_APPWINDOW
511+ };
512+
513+ (dwexstyle, dwstyle)
514+ };
515+ if !disable_direct_composition {
516+ dwexstyle |= WS_EX_NOREDIRECTIONBITMAP;
517+ }
518+
519+ let hinstance = get_module_handle();
520+ let display = if let Some(display_id) = params.display_id {
521+ WindowsDisplay::new(display_id)
522+ } else {
523+ None
524+ }
525+ .or_else(WindowsDisplay::primary_monitor)
526+ .context("failed to find any monitor")?;
527+ let appearance = system_appearance().unwrap_or_default();
528+ let mut context = WindowCreateContext {
529+ inner: None,
530+ handle,
531+ hide_title_bar,
532+ display,
533+ is_movable: params.is_movable,
534+ is_resizable: params.is_resizable,
535+ is_minimizable: params.is_minimizable,
536+ min_size: params.window_min_size,
537+ executor,
538+ current_cursor,
539+ cursor_visible,
540+ drop_target_helper,
541+ validation_number,
542+ main_receiver,
543+ platform_window_handle,
544+ appearance,
545+ disable_direct_composition,
546+ directx_devices,
547+ invalidate_devices,
548+ draw_coordinator,
549+ parent_hwnd,
550+ };
551+ let creation_result = unsafe {
552+ CreateWindowExW(
553+ dwexstyle,
554+ WINDOW_CLASS_NAME,
555+ &window_name,
556+ dwstyle,
557+ CW_USEDEFAULT,
558+ CW_USEDEFAULT,
559+ CW_USEDEFAULT,
560+ CW_USEDEFAULT,
561+ parent_hwnd,
562+ None,
563+ Some(hinstance.into()),
564+ Some(&context as *const _ as *const _),
565+ )
566+ };
567+
568+ // Failure to create a `WindowsWindowState` can cause window creation to fail,
569+ // so check the inner result first.
570+ let this = context.inner.take().transpose()?;
571+ let hwnd = creation_result?;
572+ let this = this.unwrap();
573+
574+ register_drag_drop(&this)?;
575+ set_non_rude_hwnd(hwnd, true);
576+ configure_dwm_dark_mode(hwnd, appearance);
577+ this.state.border_offset.update(hwnd)?;
578+ let placement =
579+ retrieve_window_placement(hwnd, display, params.bounds, &this.state.border_offset)?;
580+ if params.show {
581+ let mut placement = placement;
582+ if !params.focus {
583+ placement.showCmd = SW_SHOWNOACTIVATE.0 as u32;
584+ }
585+ unsafe { SetWindowPlacement(hwnd, &placement)? };
586+ } else {
587+ this.state.initial_placement.set(Some(WindowOpenStatus {
588+ placement,
589+ state: WindowOpenState::Windowed,
590+ }));
591+ }
592+
593+ Ok(Self(this))
594+ }
595+}
596+
597+impl rwh::HasWindowHandle for WindowsWindow {
598+ fn window_handle(&self) -> std::result::Result<rwh::WindowHandle<'_>, rwh::HandleError> {
599+ let raw = rwh::Win32WindowHandle::new(unsafe {
600+ NonZeroIsize::new_unchecked(self.0.hwnd.0 as isize)
601+ })
602+ .into();
603+ Ok(unsafe { rwh::WindowHandle::borrow_raw(raw) })
604+ }
605+}
606+
607+impl rwh::HasDisplayHandle for WindowsWindow {
608+ fn display_handle(&self) -> std::result::Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
609+ Ok(rwh::DisplayHandle::windows())
610+ }
611+}
612+
613+impl Drop for WindowsWindow {
614+ fn drop(&mut self) {
615+ self.0.dialog_owner.close();
616+ unsafe { ShowWindowAsync(self.0.hwnd, SW_HIDE).ok().log_err() };
617+ // `DestroyWindow` below sends `WM_SHOWWINDOW`; without a callback the
618+ // resulting visibility report has nothing to notify.
619+ self.0.state.callbacks.visibility_change.take();
620+ // clone this `Rc` to prevent early release of the pointer
621+ let this = self.0.clone();
622+ self.0
623+ .executor
624+ .spawn(async move {
625+ this.dialog_owner.when_idle().await;
626+ let handle = this.hwnd;
627+ unsafe {
628+ RevokeDragDrop(handle).log_err();
629+ DestroyWindow(handle).log_err();
630+ }
631+ })
632+ .detach();
633+ }
634+}
635+
636+impl PlatformWindow for WindowsWindow {
637+ fn bounds(&self) -> Bounds<Pixels> {
638+ self.state.bounds()
639+ }
640+
641+ fn is_maximized(&self) -> bool {
642+ self.state.is_maximized()
643+ }
644+
645+ fn window_bounds(&self) -> WindowBounds {
646+ self.state.window_bounds()
647+ }
648+
649+ /// get the logical size of the app's drawable area.
650+ ///
651+ /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as
652+ /// whether the mouse collides with other elements of GPUI).
653+ fn content_size(&self) -> Size<Pixels> {
654+ self.state.content_size()
655+ }
656+
657+ fn resize(&mut self, size: Size<Pixels>) {
658+ let hwnd = self.0.hwnd;
659+ let bounds = gpui::bounds(self.bounds().origin, size).to_device_pixels(self.scale_factor());
660+ let rect = calculate_window_rect(bounds, &self.state.border_offset);
661+
662+ self.0
663+ .executor
664+ .spawn(async move {
665+ unsafe {
666+ SetWindowPos(
667+ hwnd,
668+ None,
669+ bounds.origin.x.0,
670+ bounds.origin.y.0,
671+ rect.right - rect.left,
672+ rect.bottom - rect.top,
673+ SWP_NOMOVE,
674+ )
675+ .context("unable to set window content size")
676+ .log_err();
677+ }
678+ })
679+ .detach();
680+ }
681+
682+ fn scale_factor(&self) -> f32 {
683+ self.state.scale_factor.get()
684+ }
685+
686+ fn appearance(&self) -> WindowAppearance {
687+ self.state.appearance.get()
688+ }
689+
690+ fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
691+ Some(Rc::new(self.state.display.get()))
692+ }
693+
694+ fn mouse_position(&self) -> Point<Pixels> {
695+ let scale_factor = self.scale_factor();
696+ let point = unsafe {
697+ let mut point: POINT = std::mem::zeroed();
698+ GetCursorPos(&mut point)
699+ .context("unable to get cursor position")
700+ .log_err();
701+ ScreenToClient(self.0.hwnd, &mut point).ok().log_err();
702+ point
703+ };
704+ logical_point(point.x as f32, point.y as f32, scale_factor)
705+ }
706+
707+ fn modifiers(&self) -> Modifiers {
708+ current_modifiers()
709+ }
710+
711+ fn capslock(&self) -> Capslock {
712+ current_capslock()
713+ }
714+
715+ fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
716+ self.state.input_handler.set(Some(input_handler));
717+ }
718+
719+ fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
720+ self.state.input_handler.take()
721+ }
722+
723+ fn prompt(
724+ &self,
725+ level: PromptLevel,
726+ msg: &str,
727+ detail: Option<&str>,
728+ answers: &[PromptButton],
729+ ) -> Option<Receiver<usize>> {
730+ let (mut done_tx, done_rx) = oneshot::channel();
731+ let msg = msg.to_string();
732+ let detail_string = detail.map(|detail| detail.to_string());
733+ let answers = answers.to_vec();
734+ let dialog = crate::dialog::show_dialog(
735+ Some(self.0.dialog_owner.clone()),
736+ &self.0.executor,
737+ move |handle| {
738+ unsafe {
739+ let mut config = TASKDIALOGCONFIG::default();
740+ config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;
741+ config.hwndParent = handle;
742+ config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION;
743+ let title;
744+ let main_icon;
745+ match level {
746+ PromptLevel::Info => {
747+ title = windows::core::w!("Info");
748+ main_icon = TD_INFORMATION_ICON;
749+ }
750+ PromptLevel::Warning => {
751+ title = windows::core::w!("Warning");
752+ main_icon = TD_WARNING_ICON;
753+ }
754+ PromptLevel::Critical => {
755+ title = windows::core::w!("Critical");
756+ main_icon = TD_ERROR_ICON;
757+ }
758+ };
759+ config.pszWindowTitle = title;
760+ config.Anonymous1.pszMainIcon = main_icon;
761+ let instruction = HSTRING::from(msg);
762+ config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());
763+ let hints_encoded;
764+ if let Some(ref hints) = detail_string {
765+ hints_encoded = HSTRING::from(hints);
766+ config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());
767+ };
768+ let mut button_id_map = Vec::with_capacity(answers.len());
769+ let mut buttons = Vec::new();
770+ let mut btn_encoded = Vec::new();
771+ for (index, btn) in answers.iter().enumerate() {
772+ let encoded = HSTRING::from(btn.label().as_ref());
773+ let button_id = match btn {
774+ PromptButton::Ok(_) => IDOK.0,
775+ PromptButton::Cancel(_) => IDCANCEL.0,
776+ // the first few low integer values are reserved for known buttons
777+ // so for simplicity we just go backwards from -1
778+ PromptButton::Other(_) => -(index as i32) - 1,
779+ };
780+ button_id_map.push(button_id);
781+ buttons.push(TASKDIALOG_BUTTON {
782+ nButtonID: button_id,
783+ pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),
784+ });
785+ btn_encoded.push(encoded);
786+ }
787+ config.cButtons = buttons.len() as _;
788+ config.pButtons = buttons.as_ptr();
789+
790+ config.pfCallback = Some(crate::dialog::task_dialog_callback);
791+ config.lpCallbackData = button_id_map.contains(&IDCANCEL.0) as isize;
792+ let mut res = std::mem::zeroed();
793+ TaskDialogIndirect(&config, Some(&mut res), None, None)
794+ .context("unable to create task dialog")?;
795+ Ok(button_id_map.iter().position(|&button_id| button_id == res))
796+ }
797+ },
798+ );
799+ self.0
800+ .executor
801+ .spawn(async move {
802+ if let futures::future::Either::Left((result, _)) =
803+ futures::future::select(dialog, done_tx.cancellation()).await
804+ && let Some(Some(clicked)) = result
805+ .context("native dialog thread stopped")
806+ .and_then(|result| result)
807+ .log_err()
808+ {
809+ done_tx.send(clicked).ok();
810+ }
811+ })
812+ .detach();
813+
814+ Some(done_rx)
815+ }
816+
817+ fn activate(&self) {
818+ let hwnd = self.0.hwnd;
819+ let this = self.0.clone();
820+ self.0
821+ .executor
822+ .spawn(async move {
823+ this.set_window_placement().log_err();
824+
825+ unsafe {
826+ // If the window is minimized, restore it.
827+ if IsIconic(hwnd).as_bool() {
828+ ShowWindowAsync(hwnd, SW_RESTORE).ok().log_err();
829+ }
830+
831+ SetActiveWindow(hwnd).ok();
832+ SetFocus(Some(hwnd)).ok();
833+ }
834+
835+ // premium ragebait by windows, this is needed because the window
836+ // must have received an input event to be able to set itself to foreground
837+ // so let's just simulate user input as that seems to be the most reliable way
838+ // some more info: https://gist.github.com/Aetopia/1581b40f00cc0cadc93a0e8ccb65dc8c
839+ // bonus: this bug also doesn't manifest if you have vs attached to the process
840+ let inputs = [
841+ INPUT {
842+ r#type: INPUT_KEYBOARD,
843+ Anonymous: INPUT_0 {
844+ ki: KEYBDINPUT {
845+ wVk: VK_MENU,
846+ dwFlags: KEYBD_EVENT_FLAGS(0),
847+ ..Default::default()
848+ },
849+ },
850+ },
851+ INPUT {
852+ r#type: INPUT_KEYBOARD,
853+ Anonymous: INPUT_0 {
854+ ki: KEYBDINPUT {
855+ wVk: VK_MENU,
856+ dwFlags: KEYEVENTF_KEYUP,
857+ ..Default::default()
858+ },
859+ },
860+ },
861+ ];
862+ unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };
863+
864+ // todo(windows)
865+ // crate `windows 0.56` reports true as Err
866+ unsafe { SetForegroundWindow(hwnd).as_bool() };
867+ })
868+ .detach();
869+ }
870+
871+ fn request_attention(&self) {
872+ if self.is_active() {
873+ return;
874+ }
875+
876+ let hwnd = self.0.hwnd;
877+ self.0
878+ .executor
879+ .spawn(async move {
880+ let info = FLASHWINFO {
881+ cbSize: std::mem::size_of::<FLASHWINFO>() as u32,
882+ hwnd,
883+ dwFlags: FLASHW_ALL,
884+ uCount: 1,
885+ dwTimeout: 0,
886+ };
887+ unsafe { FlashWindowEx(&info).ok().log_err() };
888+ })
889+ .detach();
890+ }
891+
892+ fn is_active(&self) -> bool {
893+ self.0.hwnd == unsafe { GetActiveWindow() }
894+ }
895+
896+ fn visibility(&self) -> WindowVisibility {
897+ self.0.visibility()
898+ }
899+
900+ fn is_hovered(&self) -> bool {
901+ self.state.hovered.get()
902+ }
903+
904+ fn background_appearance(&self) -> WindowBackgroundAppearance {
905+ self.state.background_appearance.get()
906+ }
907+
908+ fn is_subpixel_rendering_supported(&self) -> bool {
909+ true
910+ }
911+
912+ fn set_title(&mut self, title: &str) {
913+ unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }
914+ .inspect_err(|e| log::error!("Set title failed: {e}"))
915+ .ok();
916+ }
917+
918+ fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
919+ self.state.background_appearance.set(background_appearance);
920+ let hwnd = self.0.hwnd;
921+
922+ // using Dwm APIs for Mica and MicaAlt backdrops.
923+ // others follow the set_window_composition_attribute approach
924+ match background_appearance {
925+ WindowBackgroundAppearance::Opaque => {
926+ set_window_composition_attribute(hwnd, None, 0);
927+ }
928+ WindowBackgroundAppearance::Transparent => {
929+ set_window_composition_attribute(hwnd, None, 2);
930+ }
931+ WindowBackgroundAppearance::Blurred => {
932+ set_window_composition_attribute(hwnd, Some((0, 0, 0, 0)), 4);
933+ }
934+ WindowBackgroundAppearance::MicaBackdrop => {
935+ // DWMSBT_MAINWINDOW => MicaBase
936+ dwm_set_window_composition_attribute(hwnd, 2);
937+ }
938+ WindowBackgroundAppearance::MicaAltBackdrop => {
939+ // DWMSBT_TABBEDWINDOW => MicaAlt
940+ dwm_set_window_composition_attribute(hwnd, 4);
941+ }
942+ }
943+ }
944+
945+ fn minimize(&self) {
946+ unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };
947+ }
948+
949+ fn zoom(&self) {
950+ unsafe {
951+ if IsWindowVisible(self.0.hwnd).as_bool() {
952+ ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();
953+ } else if let Some(mut status) = self.state.initial_placement.take() {
954+ status.state = WindowOpenState::Maximized;
955+ self.state.initial_placement.set(Some(status));
956+ }
957+ }
958+ }
959+
960+ fn toggle_fullscreen(&self) {
961+ if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {
962+ self.0.toggle_fullscreen();
963+ } else if let Some(mut status) = self.state.initial_placement.take() {
964+ status.state = WindowOpenState::Fullscreen;
965+ self.state.initial_placement.set(Some(status));
966+ }
967+ }
968+
969+ fn is_fullscreen(&self) -> bool {
970+ self.state.is_fullscreen()
971+ }
972+
973+ fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
974+ self.state.callbacks.request_frame.set(Some(callback));
975+ }
976+
977+ fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
978+ self.state.callbacks.input.set(Some(callback));
979+ }
980+
981+ fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
982+ self.0
983+ .state
984+ .callbacks
985+ .active_status_change
986+ .set(Some(callback));
987+ }
988+
989+ fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>) {
990+ self.0.state.last_visibility.set(Some(self.0.visibility()));
991+ self.0.state.callbacks.visibility_change.set(Some(callback));
992+ }
993+
994+ fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
995+ self.0
996+ .state
997+ .callbacks
998+ .hovered_status_change
999+ .set(Some(callback));
1000+ }
1001+
1002+ fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1003+ self.state.callbacks.resize.set(Some(callback));
1004+ }
1005+
1006+ fn on_display_changed(&self, callback: Box<dyn FnMut()>) {
1007+ self.state.callbacks.display_changed.set(Some(callback));
1008+ }
1009+
1010+ fn on_moved(&self, callback: Box<dyn FnMut()>) {
1011+ self.state.callbacks.moved.set(Some(callback));
1012+ }
1013+
1014+ fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1015+ self.state.callbacks.should_close.set(Some(callback));
1016+ }
1017+
1018+ fn on_close(&self, callback: Box<dyn FnOnce()>) {
1019+ self.state.callbacks.close.set(Some(callback));
1020+ }
1021+
1022+ fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1023+ self.0
1024+ .state
1025+ .callbacks
1026+ .hit_test_window_control
1027+ .set(Some(callback));
1028+ }
1029+
1030+ fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1031+ self.0
1032+ .state
1033+ .callbacks
1034+ .appearance_changed
1035+ .set(Some(callback));
1036+ }
1037+
1038+ fn draw(&self, scene: &Scene) {
1039+ self.state
1040+ .renderer
1041+ .borrow_mut()
1042+ .draw(scene, self.state.background_appearance.get())
1043+ .log_err();
1044+ }
1045+
1046+ #[cfg(feature = "test-support")]
1047+ fn render_to_image(&self, scene: &Scene) -> anyhow::Result<image::RgbaImage> {
1048+ self.state
1049+ .renderer
1050+ .borrow_mut()
1051+ .render_to_image(scene, self.state.background_appearance.get())
1052+ }
1053+
1054+ fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1055+ self.state.renderer.borrow().sprite_atlas()
1056+ }
1057+
1058+ fn get_raw_handle(&self) -> HWND {
1059+ self.0.hwnd
1060+ }
1061+
1062+ fn gpu_specs(&self) -> Option<GpuSpecs> {
1063+ self.state.renderer.borrow().gpu_specs().log_err()
1064+ }
1065+
1066+ fn update_ime_position(&self, bounds: Bounds<Pixels>) {
1067+ let scale_factor = self.state.scale_factor.get();
1068+ let caret_position = POINT {
1069+ x: (bounds.origin.x.as_f32() * scale_factor) as i32,
1070+ y: (bounds.origin.y.as_f32() * scale_factor) as i32
1071+ + ((bounds.size.height.as_f32() * scale_factor) as i32 / 2),
1072+ };
1073+
1074+ self.0.update_ime_position(self.0.hwnd, caret_position);
1075+ }
1076+
1077+ fn play_system_bell(&self) {
1078+ // MB_OK: The sound specified as the Windows Default Beep sound.
1079+ let _ = unsafe { MessageBeep(MB_OK) };
1080+ }
1081+
1082+ fn a11y_init(&self, callbacks: gpui::A11yCallbacks) {
1083+ let action_handler = A11yActionHandler(callbacks.action);
1084+ let is_focused = unsafe { GetForegroundWindow() } == self.0.hwnd;
1085+
1086+ let adapter = accesskit_windows::Adapter::new(
1087+ accesskit_windows::HWND(self.0.hwnd.0),
1088+ is_focused,
1089+ action_handler,
1090+ );
1091+
1092+ let activation_handler = A11yActivationHandler {
1093+ callback: callbacks.activation,
1094+ };
1095+
1096+ *self.state.a11y.borrow_mut() = Some(A11yState {
1097+ adapter,
1098+ activation_handler,
1099+ });
1100+ }
1101+
1102+ fn a11y_tree_update(&self, tree_update: accesskit::TreeUpdate) {
1103+ let events = {
1104+ let mut a11y = self.state.a11y.borrow_mut();
1105+ a11y.as_mut()
1106+ .and_then(|a11y| a11y.adapter.update_if_active(|| tree_update))
1107+ };
1108+ // The borrow must be dropped before raising events, because
1109+ // `events.raise()` calls `UiaRaiseAutomationPropertyChangedEvent`
1110+ // which may send a nested `WM_GETOBJECT` back into this window
1111+ // procedure, re-entering `handle_wm_getobject` which also borrows
1112+ // `self.state.a11y`.
1113+ if let Some(events) = events {
1114+ events.raise();
1115+ }
1116+ }
1117+
1118+ fn a11y_update_window_bounds(&self) {
1119+ // Windows UIA handles window bounds tracking automatically.
1120+ }
1121+}
1122+
1123+pub(crate) struct A11yState {
1124+ pub(crate) adapter: accesskit_windows::Adapter,
1125+ pub(crate) activation_handler: A11yActivationHandler,
1126+}
1127+
1128+pub(crate) struct A11yActivationHandler {
1129+ callback: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,
1130+}
1131+
1132+impl accesskit::ActivationHandler for A11yActivationHandler {
1133+ fn request_initial_tree(&mut self) -> Option<accesskit::TreeUpdate> {
1134+ (self.callback)()
1135+ }
1136+}
1137+
1138+struct A11yActionHandler(Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>);
1139+
1140+impl accesskit::ActionHandler for A11yActionHandler {
1141+ fn do_action(&mut self, request: accesskit::ActionRequest) {
1142+ (self.0)(request);
1143+ }
1144+}
1145+
1146+#[implement(IDropTarget)]
1147+struct WindowsDragDropHandler(pub Rc<WindowsWindowInner>);
1148+
1149+impl WindowsDragDropHandler {
1150+ fn handle_drag_drop(&self, input: PlatformInput) {
1151+ if let Some(mut func) = self.0.state.callbacks.input.take() {
1152+ func(input);
1153+ self.0.state.callbacks.input.set(Some(func));
1154+ }
1155+ }
1156+}
1157+
1158+#[allow(non_snake_case)]
1159+impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
1160+ fn DragEnter(
1161+ &self,
1162+ pdataobj: windows::core::Ref<IDataObject>,
1163+ _grfkeystate: MODIFIERKEYS_FLAGS,
1164+ pt: &POINTL,
1165+ pdweffect: *mut DROPEFFECT,
1166+ ) -> windows::core::Result<()> {
1167+ unsafe {
1168+ let idata_obj = pdataobj.ok()?;
1169+ let config = FORMATETC {
1170+ cfFormat: CF_HDROP.0,
1171+ ptd: std::ptr::null_mut() as _,
1172+ dwAspect: DVASPECT_CONTENT.0,
1173+ lindex: -1,
1174+ tymed: TYMED_HGLOBAL.0 as _,
1175+ };
1176+ let cursor_position = POINT { x: pt.x, y: pt.y };
1177+ if idata_obj.QueryGetData(&config as _) == S_OK {
1178+ *pdweffect = DROPEFFECT_COPY;
1179+ let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {
1180+ return Ok(());
1181+ };
1182+ if idata.u.hGlobal.is_invalid() {
1183+ return Ok(());
1184+ }
1185+ let hdrop = HDROP(idata.u.hGlobal.0);
1186+ let mut paths = SmallVec::<[PathBuf; 2]>::new();
1187+ with_file_names(hdrop, |file_name| {
1188+ if let Some(path) = PathBuf::from_str(&file_name).log_err() {
1189+ paths.push(path);
1190+ }
1191+ });
1192+ ReleaseStgMedium(&mut idata);
1193+ let mut cursor_position = cursor_position;
1194+ ScreenToClient(self.0.hwnd, &mut cursor_position)
1195+ .ok()
1196+ .log_err();
1197+ let scale_factor = self.0.state.scale_factor.get();
1198+ let input = PlatformInput::FileDrop(FileDropEvent::Entered {
1199+ position: logical_point(
1200+ cursor_position.x as f32,
1201+ cursor_position.y as f32,
1202+ scale_factor,
1203+ ),
1204+ paths: ExternalPaths(paths),
1205+ });
1206+ self.handle_drag_drop(input);
1207+ } else {
1208+ *pdweffect = DROPEFFECT_NONE;
1209+ }
1210+ self.0
1211+ .drop_target_helper
1212+ .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)
1213+ .log_err();
1214+ }
1215+ Ok(())
1216+ }
1217+
1218+ fn DragOver(
1219+ &self,
1220+ _grfkeystate: MODIFIERKEYS_FLAGS,
1221+ pt: &POINTL,
1222+ pdweffect: *mut DROPEFFECT,
1223+ ) -> windows::core::Result<()> {
1224+ let mut cursor_position = POINT { x: pt.x, y: pt.y };
1225+ unsafe {
1226+ *pdweffect = DROPEFFECT_COPY;
1227+ self.0
1228+ .drop_target_helper
1229+ .DragOver(&cursor_position, *pdweffect)
1230+ .log_err();
1231+ ScreenToClient(self.0.hwnd, &mut cursor_position)
1232+ .ok()
1233+ .log_err();
1234+ }
1235+ let scale_factor = self.0.state.scale_factor.get();
1236+ let input = PlatformInput::FileDrop(FileDropEvent::Pending {
1237+ position: logical_point(
1238+ cursor_position.x as f32,
1239+ cursor_position.y as f32,
1240+ scale_factor,
1241+ ),
1242+ });
1243+ self.handle_drag_drop(input);
1244+
1245+ Ok(())
1246+ }
1247+
1248+ fn DragLeave(&self) -> windows::core::Result<()> {
1249+ unsafe {
1250+ self.0.drop_target_helper.DragLeave().log_err();
1251+ }
1252+ let input = PlatformInput::FileDrop(FileDropEvent::Exited);
1253+ self.handle_drag_drop(input);
1254+
1255+ Ok(())
1256+ }
1257+
1258+ fn Drop(
1259+ &self,
1260+ pdataobj: windows::core::Ref<IDataObject>,
1261+ _grfkeystate: MODIFIERKEYS_FLAGS,
1262+ pt: &POINTL,
1263+ pdweffect: *mut DROPEFFECT,
1264+ ) -> windows::core::Result<()> {
1265+ let idata_obj = pdataobj.ok()?;
1266+ let mut cursor_position = POINT { x: pt.x, y: pt.y };
1267+ unsafe {
1268+ *pdweffect = DROPEFFECT_COPY;
1269+ self.0
1270+ .drop_target_helper
1271+ .Drop(idata_obj, &cursor_position, *pdweffect)
1272+ .log_err();
1273+ ScreenToClient(self.0.hwnd, &mut cursor_position)
1274+ .ok()
1275+ .log_err();
1276+ }
1277+ let scale_factor = self.0.state.scale_factor.get();
1278+ let input = PlatformInput::FileDrop(FileDropEvent::Submit {
1279+ position: logical_point(
1280+ cursor_position.x as f32,
1281+ cursor_position.y as f32,
1282+ scale_factor,
1283+ ),
1284+ });
1285+ self.handle_drag_drop(input);
1286+
1287+ Ok(())
1288+ }
1289+}
1290+
1291+#[derive(Debug, Clone)]
1292+pub(crate) struct ClickState {
1293+ button: Cell<MouseButton>,
1294+ last_click: Cell<Instant>,
1295+ last_position: Cell<Point<DevicePixels>>,
1296+ double_click_spatial_tolerance_width: Cell<i32>,
1297+ double_click_spatial_tolerance_height: Cell<i32>,
1298+ double_click_interval: Cell<Duration>,
1299+ pub(crate) current_count: Cell<usize>,
1300+}
1301+
1302+impl ClickState {
1303+ pub fn new() -> Self {
1304+ let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };
1305+ let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };
1306+ let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);
1307+
1308+ ClickState {
1309+ button: Cell::new(MouseButton::Left),
1310+ last_click: Cell::new(Instant::now()),
1311+ last_position: Cell::new(Point::default()),
1312+ double_click_spatial_tolerance_width: Cell::new(double_click_spatial_tolerance_width),
1313+ double_click_spatial_tolerance_height: Cell::new(double_click_spatial_tolerance_height),
1314+ double_click_interval: Cell::new(double_click_interval),
1315+ current_count: Cell::new(0),
1316+ }
1317+ }
1318+
1319+ /// update self and return the needed click count
1320+ pub fn update(&self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {
1321+ if self.button.get() == button && self.is_double_click(new_position) {
1322+ self.current_count.update(|it| it + 1);
1323+ } else {
1324+ self.current_count.set(1);
1325+ }
1326+ self.last_click.set(Instant::now());
1327+ self.last_position.set(new_position);
1328+ self.button.set(button);
1329+
1330+ self.current_count.get()
1331+ }
1332+
1333+ pub fn system_update(&self, wparam: usize) {
1334+ match wparam {
1335+ // SPI_SETDOUBLECLKWIDTH
1336+ 29 => self
1337+ .double_click_spatial_tolerance_width
1338+ .set(unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }),
1339+ // SPI_SETDOUBLECLKHEIGHT
1340+ 30 => self
1341+ .double_click_spatial_tolerance_height
1342+ .set(unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }),
1343+ // SPI_SETDOUBLECLICKTIME
1344+ 32 => self
1345+ .double_click_interval
1346+ .set(Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)),
1347+ _ => {}
1348+ }
1349+ }
1350+
1351+ #[inline]
1352+ fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {
1353+ let diff = self.last_position.get() - new_position;
1354+
1355+ self.last_click.get().elapsed() < self.double_click_interval.get()
1356+ && diff.x.0.abs() <= self.double_click_spatial_tolerance_width.get()
1357+ && diff.y.0.abs() <= self.double_click_spatial_tolerance_height.get()
1358+ }
1359+}
1360+
1361+#[derive(Copy, Clone)]
1362+struct StyleAndBounds {
1363+ style: WINDOW_STYLE,
1364+ x: i32,
1365+ y: i32,
1366+ cx: i32,
1367+ cy: i32,
1368+}
1369+
1370+#[repr(C)]
1371+struct WINDOWCOMPOSITIONATTRIBDATA {
1372+ attrib: u32,
1373+ pv_data: *mut std::ffi::c_void,
1374+ cb_data: usize,
1375+}
1376+
1377+#[repr(C)]
1378+struct AccentPolicy {
1379+ accent_state: u32,
1380+ accent_flags: u32,
1381+ gradient_color: u32,
1382+ animation_id: u32,
1383+}
1384+
1385+type Color = (u8, u8, u8, u8);
1386+
1387+#[derive(Debug, Default, Clone)]
1388+pub(crate) struct WindowBorderOffset {
1389+ pub(crate) width_offset: Cell<i32>,
1390+ pub(crate) height_offset: Cell<i32>,
1391+}
1392+
1393+impl WindowBorderOffset {
1394+ pub(crate) fn update(&self, hwnd: HWND) -> anyhow::Result<()> {
1395+ let window_rect = unsafe {
1396+ let mut rect = std::mem::zeroed();
1397+ GetWindowRect(hwnd, &mut rect)?;
1398+ rect
1399+ };
1400+ let client_rect = unsafe {
1401+ let mut rect = std::mem::zeroed();
1402+ GetClientRect(hwnd, &mut rect)?;
1403+ rect
1404+ };
1405+ self.width_offset
1406+ .set((window_rect.right - window_rect.left) - (client_rect.right - client_rect.left));
1407+ self.height_offset
1408+ .set((window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top));
1409+ Ok(())
1410+ }
1411+}
1412+
1413+#[derive(Clone)]
1414+struct WindowOpenStatus {
1415+ placement: WINDOWPLACEMENT,
1416+ state: WindowOpenState,
1417+}
1418+
1419+#[derive(Clone, Copy)]
1420+enum WindowOpenState {
1421+ Maximized,
1422+ Fullscreen,
1423+ Windowed,
1424+}
1425+
1426+const WINDOW_CLASS_NAME: PCWSTR = w!("Zed::Window");
1427+
1428+fn register_window_class(icon_handle: HICON) {
1429+ static ONCE: Once = Once::new();
1430+ ONCE.call_once(|| {
1431+ let wc = WNDCLASSW {
1432+ lpfnWndProc: Some(window_procedure),
1433+ hIcon: icon_handle,
1434+ lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
1435+ style: CS_HREDRAW | CS_VREDRAW,
1436+ hInstance: get_module_handle().into(),
1437+ hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },
1438+ ..Default::default()
1439+ };
1440+ unsafe { RegisterClassW(&wc) };
1441+ });
1442+}
1443+
1444+unsafe extern "system" fn window_procedure(
1445+ hwnd: HWND,
1446+ msg: u32,
1447+ wparam: WPARAM,
1448+ lparam: LPARAM,
1449+) -> LRESULT {
1450+ if msg == WM_NCCREATE {
1451+ let window_params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };
1452+ let window_creation_context = window_params.lpCreateParams as *mut WindowCreateContext;
1453+ let window_creation_context = unsafe { &mut *window_creation_context };
1454+ return match WindowsWindowInner::new(window_creation_context, hwnd, window_params) {
1455+ Ok(window_state) => {
1456+ let weak = Box::new(Rc::downgrade(&window_state));
1457+ unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };
1458+ window_creation_context.inner = Some(Ok(window_state));
1459+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1460+ }
1461+ Err(error) => {
1462+ window_creation_context.inner = Some(Err(error));
1463+ LRESULT(0)
1464+ }
1465+ };
1466+ }
1467+
1468+ let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1469+ if ptr.is_null() {
1470+ return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
1471+ }
1472+ let inner = unsafe { &*ptr };
1473+ let result = if let Some(inner) = inner.upgrade() {
1474+ if msg == WM_NCDESTROY {
1475+ inner.dialog_owner.close();
1476+ }
1477+ inner.handle_msg(hwnd, msg, wparam, lparam)
1478+ } else {
1479+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
1480+ };
1481+
1482+ if msg == WM_NCDESTROY {
1483+ unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };
1484+ unsafe { drop(Box::from_raw(ptr)) };
1485+ }
1486+
1487+ result
1488+}
1489+
1490+pub(crate) fn window_from_hwnd(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {
1491+ if hwnd.is_invalid() {
1492+ return None;
1493+ }
1494+
1495+ let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;
1496+ if !ptr.is_null() {
1497+ let inner = unsafe { &*ptr };
1498+ inner.upgrade()
1499+ } else {
1500+ None
1501+ }
1502+}
1503+
1504+fn get_module_handle() -> HMODULE {
1505+ unsafe {
1506+ let mut h_module = std::mem::zeroed();
1507+ GetModuleHandleExW(
1508+ GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
1509+ windows::core::w!("ZedModule"),
1510+ &mut h_module,
1511+ )
1512+ .expect("Unable to get module handle"); // this should never fail
1513+
1514+ h_module
1515+ }
1516+}
1517+
1518+fn register_drag_drop(window: &Rc<WindowsWindowInner>) -> Result<()> {
1519+ let window_handle = window.hwnd;
1520+ let handler = WindowsDragDropHandler(window.clone());
1521+ // The lifetime of `IDropTarget` is handled by Windows, it won't release until
1522+ // we call `RevokeDragDrop`.
1523+ // So, it's safe to drop it here.
1524+ let drag_drop_handler: IDropTarget = handler.into();
1525+ unsafe {
1526+ RegisterDragDrop(window_handle, &drag_drop_handler)
1527+ .context("unable to register drag-drop event")?;
1528+ }
1529+ Ok(())
1530+}
1531+
1532+fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: &WindowBorderOffset) -> RECT {
1533+ // NOTE:
1534+ // The reason we're not using `AdjustWindowRectEx()` here is
1535+ // that the size reported by this function is incorrect.
1536+ // You can test it, and there are similar discussions online.
1537+ // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi
1538+ //
1539+ // So we manually calculate these values here.
1540+ let mut rect = RECT {
1541+ left: bounds.left().0,
1542+ top: bounds.top().0,
1543+ right: bounds.right().0,
1544+ bottom: bounds.bottom().0,
1545+ };
1546+ let left_offset = border_offset.width_offset.get() / 2;
1547+ let top_offset = border_offset.height_offset.get() / 2;
1548+ let right_offset = border_offset.width_offset.get() - left_offset;
1549+ let bottom_offset = border_offset.height_offset.get() - top_offset;
1550+ rect.left -= left_offset;
1551+ rect.top -= top_offset;
1552+ rect.right += right_offset;
1553+ rect.bottom += bottom_offset;
1554+ rect
1555+}
1556+
1557+fn calculate_client_rect(
1558+ rect: RECT,
1559+ border_offset: &WindowBorderOffset,
1560+ scale_factor: f32,
1561+) -> Bounds<Pixels> {
1562+ let left_offset = border_offset.width_offset.get() / 2;
1563+ let top_offset = border_offset.height_offset.get() / 2;
1564+ let right_offset = border_offset.width_offset.get() - left_offset;
1565+ let bottom_offset = border_offset.height_offset.get() - top_offset;
1566+ let left = rect.left + left_offset;
1567+ let top = rect.top + top_offset;
1568+ let right = rect.right - right_offset;
1569+ let bottom = rect.bottom - bottom_offset;
1570+ let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));
1571+ Bounds {
1572+ origin: logical_point(left as f32, top as f32, scale_factor),
1573+ size: physical_size.to_pixels(scale_factor),
1574+ }
1575+}
1576+
1577+fn retrieve_window_placement(
1578+ hwnd: HWND,
1579+ display: WindowsDisplay,
1580+ initial_bounds: Bounds<Pixels>,
1581+ border_offset: &WindowBorderOffset,
1582+) -> Result<WINDOWPLACEMENT> {
1583+ let mut placement = WINDOWPLACEMENT {
1584+ length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
1585+ ..Default::default()
1586+ };
1587+ unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1588+ // the bounds may be not inside the display
1589+ let bounds = if display.check_given_bounds(initial_bounds) {
1590+ initial_bounds
1591+ } else {
1592+ display.default_bounds()
1593+ };
1594+ // `bounds` is expressed in logical pixels for `display`, so it must be converted
1595+ // to device pixels using that display's own scale factor. The window's current
1596+ // scale factor can't be used here: `CreateWindowExW` was called with
1597+ // `CW_USEDEFAULT`, so at this point the window may still be sitting on whichever
1598+ // monitor Windows picked by default, which can have a different DPI than `display`
1599+ // and would otherwise throw off the physical position (e.g. leaving the window
1600+ // partially off-screen when moved to a monitor with a different scale factor).
1601+ let bounds = bounds.to_device_pixels(display.scale_factor());
1602+ placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
1603+ Ok(placement)
1604+}
1605+
1606+fn dwm_set_window_composition_attribute(hwnd: HWND, backdrop_type: u32) {
1607+ let mut version = unsafe { std::mem::zeroed() };
1608+ let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1609+
1610+ // DWMWA_SYSTEMBACKDROP_TYPE is available only on version 22621 or later
1611+ // using SetWindowCompositionAttributeType as a fallback
1612+ if !status.is_ok() || version.dwBuildNumber < 22621 {
1613+ return;
1614+ }
1615+
1616+ unsafe {
1617+ let result = DwmSetWindowAttribute(
1618+ hwnd,
1619+ DWMWA_SYSTEMBACKDROP_TYPE,
1620+ &backdrop_type as *const _ as *const _,
1621+ std::mem::size_of_val(&backdrop_type) as u32,
1622+ );
1623+
1624+ if !result.is_ok() {
1625+ return;
1626+ }
1627+ }
1628+}
1629+
1630+fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {
1631+ let mut version = unsafe { std::mem::zeroed() };
1632+ let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };
1633+
1634+ if !status.is_ok() || version.dwBuildNumber < 17763 {
1635+ return;
1636+ }
1637+
1638+ unsafe {
1639+ type SetWindowCompositionAttributeType =
1640+ unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;
1641+ let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);
1642+ if let Some(user32) = GetModuleHandleA(module_name)
1643+ .context("Unable to get user32.dll handle")
1644+ .log_err()
1645+ {
1646+ let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);
1647+ let Some(raw_set_window_composition_attribute) = GetProcAddress(user32, func_name)
1648+ else {
1649+ return;
1650+ };
1651+ let set_window_composition_attribute: SetWindowCompositionAttributeType =
1652+ std::mem::transmute(raw_set_window_composition_attribute);
1653+ let mut color = color.unwrap_or_default();
1654+ let is_acrylic = state == 4;
1655+ if is_acrylic && color.3 == 0 {
1656+ color.3 = 1;
1657+ }
1658+ let accent = AccentPolicy {
1659+ accent_state: state,
1660+ accent_flags: if is_acrylic { 0 } else { 2 },
1661+ gradient_color: (color.0 as u32)
1662+ | ((color.1 as u32) << 8)
1663+ | ((color.2 as u32) << 16)
1664+ | ((color.3 as u32) << 24),
1665+ animation_id: 0,
1666+ };
1667+ let mut data = WINDOWCOMPOSITIONATTRIBDATA {
1668+ attrib: 0x13,
1669+ pv_data: &accent as *const _ as *mut _,
1670+ cb_data: std::mem::size_of::<AccentPolicy>(),
1671+ };
1672+ let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);
1673+ }
1674+ }
1675+}
1676+
1677+// When the platform title bar is hidden, Windows may think that our application is meant to appear 'fullscreen'
1678+// and will stop the taskbar from appearing on top of our window. Prevent this.
1679+// https://devblogs.microsoft.com/oldnewthing/20250522-00/?p=111211
1680+fn set_non_rude_hwnd(hwnd: HWND, non_rude: bool) {
1681+ if non_rude {
1682+ unsafe { SetPropW(hwnd, w!("NonRudeHWND"), Some(HANDLE(1 as _))) }.log_err();
1683+ } else {
1684+ unsafe { RemovePropW(hwnd, w!("NonRudeHWND")) }.log_err();
1685+ }
1686+}
1687+
1688+#[cfg(test)]
1689+mod tests {
1690+ use super::ClickState;
1691+ use gpui::{DevicePixels, MouseButton, point};
1692+ use std::time::Duration;
1693+
1694+ #[test]
1695+ fn test_double_click_interval() {
1696+ let state = ClickState::new();
1697+ assert_eq!(
1698+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1699+ 1
1700+ );
1701+ assert_eq!(
1702+ state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),
1703+ 1
1704+ );
1705+ assert_eq!(
1706+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1707+ 1
1708+ );
1709+ assert_eq!(
1710+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1711+ 2
1712+ );
1713+ state
1714+ .last_click
1715+ .update(|it| it - Duration::from_millis(700));
1716+ assert_eq!(
1717+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),
1718+ 1
1719+ );
1720+ }
1721+
1722+ #[test]
1723+ fn test_double_click_spatial_tolerance() {
1724+ let state = ClickState::new();
1725+ assert_eq!(
1726+ state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),
1727+ 1
1728+ );
1729+ assert_eq!(
1730+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),
1731+ 2
1732+ );
1733+ assert_eq!(
1734+ state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),
1735+ 1
1736+ );
1737+ assert_eq!(
1738+ state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),
1739+ 1
1740+ );
1741+ }
1742+}
vendor/gpui-pre-windows/src/wrapper.rsadded+53 -0
@@ -0,0 +1,53 @@
1+use std::ops::Deref;
2+
3+use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::HCURSOR};
4+
5+#[derive(Debug, Clone, Copy)]
6+pub(crate) struct SafeCursor {
7+ raw: HCURSOR,
8+}
9+
10+unsafe impl Send for SafeCursor {}
11+unsafe impl Sync for SafeCursor {}
12+
13+impl From<HCURSOR> for SafeCursor {
14+ fn from(value: HCURSOR) -> Self {
15+ SafeCursor { raw: value }
16+ }
17+}
18+
19+impl Deref for SafeCursor {
20+ type Target = HCURSOR;
21+
22+ fn deref(&self) -> &Self::Target {
23+ &self.raw
24+ }
25+}
26+
27+#[derive(Debug, Clone, Copy)]
28+pub(crate) struct SafeHwnd {
29+ raw: HWND,
30+}
31+
32+impl SafeHwnd {
33+ pub(crate) fn as_raw(&self) -> HWND {
34+ self.raw
35+ }
36+}
37+
38+unsafe impl Send for SafeHwnd {}
39+unsafe impl Sync for SafeHwnd {}
40+
41+impl From<HWND> for SafeHwnd {
42+ fn from(value: HWND) -> Self {
43+ SafeHwnd { raw: value }
44+ }
45+}
46+
47+impl Deref for SafeHwnd {
48+ type Target = HWND;
49+
50+ fn deref(&self) -> &Self::Target {
51+ &self.raw
52+ }
53+}