Compare commits

...

678 Commits
v1.1.2 ... main

Author SHA1 Message Date
Mitchell Hashimoto
4e10f972df macOS: Do not send control characters as UTF8 keyboard text (#7136)
Fixes a regression where `ctrl+enter` was not encoding properly since
our input stack changes.
2025-04-19 07:06:39 -07:00
Mitchell Hashimoto
9beaed45f8 Revert "apprt/gtk: add menu to new tab button to create splits (#7127)"
This reverts commit 14134d61fb4b1bbf4ce80bb9b3ed849908bf9344, reversing
changes made to 6a876ef8ec3e2aeb3d15df0dfb0e07677e49ff03.

This causes translation failures, this should be reintroduced when the
CI check passes.
2025-04-19 07:05:38 -07:00
Mitchell Hashimoto
31b2ac4b79 macOS: Do not send control characters as UTF8 keyboard text
Fixes a regression where `ctrl+enter` was not encoding properly since
our input stack changes.
2025-04-19 06:54:36 -07:00
Tristan Partin
14134d61fb apprt/gtk: add menu to new tab button to create splits (#7127)
Closes: https://github.com/ghostty-org/ghostty/discussions/6828
2025-04-19 01:23:18 -05:00
Tristan Partin
410761d4e3 apprt/gtk: add menu to new tab button to create splits
Closes: https://github.com/ghostty-org/ghostty/discussions/6828
Co-authored-by: Leah Amelia Chen <github@acc.pluie.me>
Signed-off-by: Tristan Partin <tristan@partin.io>
2025-04-19 01:04:57 -05:00
Mitchell Hashimoto
6a876ef8ec macOS: A couple input regressions from 7121 (#7132)
Fixes #7131 

See individual commit messages.

I'm running them through the same tests as #7121 to verify manually that
behavior.
2025-04-18 15:35:12 -07:00
Mitchell Hashimoto
e4a37dd383 macOS: only set unshifted codepoint on keyDown/Up events
Other event types trigger an AppKit assertion that doesn't crash the app
but logs some nasty stuff.
2025-04-18 15:14:38 -07:00
Mitchell Hashimoto
18d6faf597 macOS: translation mods should never have "control"
This also lets us get rid of our `C-/` special handling to prevent a
system beep.
2025-04-18 15:10:57 -07:00
Mitchell Hashimoto
edb8616341 macos: translationMods should be used for consumed mods calculation
Fixes #7131
Regression from #7121

Our consumed mods should not include "alt" if `macos-option-as-alt` is
set. To do this, we need to calculate our consumed mods based on the
actual translation event mods (if available, only available during
keyDown).
2025-04-18 14:28:26 -07:00
Mitchell Hashimoto
65356c25da macOS/libghostty: rework keyboard input handling (#7121)
This is a large refactor of the keyboard input handling code in
libghostty and macOS. Previously, libghostty did a lot of things that
felt out of scope or was repeated work due to lacking context. For
example, libghostty would do full key translation from key event to
character (including unshifted translation) as well as managing dead key
states and setting the proper preedit text.

This is all information the apprt can and should have on its own.
NSEvent on macOS already provides us with all of this information,
there's no need to redo the work. The reason we did in the first place
is mostly historical: libghostty powered our initial macOS port years
ago when we didn't have an AppKit runtime yet.

This cruft has already practically been the source of numerous issues,
e.g.
https://github.com/ghostty-org/ghostty/issues/5558, but many other hacks
along the way, too.

This commit pushes all preedit (e.g. dead key) handling and key
translation
including unshifted keys up into the caller of libghostty.

Besides code cleanup, a practical benefit of this is that key event
handling on macOS is now about 10x faster on average. That's because
we're avoiding repeated key translations as well as other unnecessary
work. This should have a meaningful impact on input latency but I didn't
measure the full end-to-end latency.

A scarier part of this commit is that key handling is not well tested
since its a GUI component. I suspect we'll have some fallout for certain
keyboard layouts or input methods, but I did my best to run through
everything I could think of.

This also fixes one bug where preedit state didn't properly clear when
changing keyboard layouts. This now does and matches the behavior
of native apps like TextEdit and Terminal.app
2025-04-18 12:06:32 -07:00
Tristan Partin
85268d4f82 apprt/gtk: refactor action callbacks to reduce code duplication (#7126)
It was getting very monotonous reading the code.
2025-04-18 13:11:12 -05:00
Tristan Partin
793c727986 apprt/gtk: refactor action callbacks to reduce code duplication
It was getting very monotonous reading the code.

Signed-off-by: Tristan Partin <tristan@partin.io>
2025-04-18 12:54:36 -05:00
Leah Amelia Chen
773506fe82 Improve Chinese (zh_CN) Translations for Natural Phrasing (#7125) 2025-04-18 23:56:12 +08:00
Bryan Lee
34ddd3d9e5 Refine Chinese translations for daily usage consistency 2025-04-18 23:34:18 +08:00
Mitchell Hashimoto
03a1c04a6e i18n: fix spelling inconsistencies for Japanese Translations (#7122)
This pr fix spelling inconsistencies for Japanese Translations
2025-04-18 07:17:46 -07:00
Mitchell Hashimoto
b63fa7dfa1 vim: fix syntax highlight on scratch buffer (#7119)
Sometimes we need detect ghostty filetype on scratch buffer.
In this case `set iskeyword` in ftplugin is not loaded.

Screenshot:
https://github.com/ibhagwan/fzf-lua/pull/1913#issuecomment-2813289819.

e.g.
```sh
nvim +'0r ~/.config/ghostty/config' +'se syntax=ghostty'
```
2025-04-18 07:17:30 -07:00
phanium
9bab900c75 vim: fix syntax highlight on scratch buffer 2025-04-18 21:50:24 +08:00
ekusiadadus
bef0d5d88e fix: spelling inconsistencies for Japanese Translations 2025-04-18 07:22:40 +09:00
Mitchell Hashimoto
ded9be39c0 macOS: handle preedit text changes outside of key event 2025-04-17 14:24:12 -07:00
Mitchell Hashimoto
b3cb38c3fa macOS/libghostty: rework keyboard input handling
This is a large refactor of the keyboard input handling code in
libghostty and macOS. Previously, libghostty did a lot of things that
felt out of scope or was repeated work due to lacking context. For
example, libghostty would do full key translation from key event to
character (including unshifted translation) as well as managing dead key
states and setting the proper preedit text.

This is all information the apprt can and should have on its own.
NSEvent on macOS already provides us with all of this information,
there's no need to redo the work. The reason we did in the first place
is mostly historical: libghostty powered our initial macOS port years
ago when we didn't have an AppKit runtime yet.

This cruft has already practically been the source of numerous issues, e.g.
#5558, but many other hacks along the way, too.

This commit pushes all preedit (e.g. dead key) handling and key translation
including unshifted keys up into the caller of libghostty.

Besides code cleanup, a practical benefit of this is that key event
handling on macOS is now about 10x faster on average. That's because
we're avoiding repeated key translations as well as other unnecessary
work. This should have a meaningful impact on input latency but I didn't
measure the full end-to-end latency.

A scarier part of this commit is that key handling is not well tested
since its a GUI component. I suspect we'll have some fallout for certain
keyboard layouts or input methods, but I did my best to run through
everything I could think of.
2025-04-17 14:24:12 -07:00
Mitchell Hashimoto
2bcd76c3d9 macOS: Implement basic bell features (no sound) (#7101)
Fixes #7099

This adds basic bell features to macOS to conceptually match the GTK
implementation. When a bell is triggered, macOS will do the following:

  1. Bounce the dock icon once, if the app isn't already in focus.
2. Add a bell emoji (🔔) to the title of the surface that triggered the
bell. This emoji will be removed after the surface is focused or a
keyboard event if the surface is already focused. This behavior matches
iTerm2.

Note that neither of these respect the `system` `bell-features` config
because they're both unobtrusive (the dock icon bounces only once, the
title change is silent and similar to GTK tab attention) and unrelated
to system settings.

This doesn't add an icon badge because macOS's dockTitle.badgeLabel API
wasn't doing anything for me and I wasn't able to fully figure out
why...
2025-04-15 13:24:20 -07:00
Mitchell Hashimoto
cc690eddb5 macOS: Implement basic bell features (no sound)
Fixes #7099

This adds basic bell features to macOS to conceptually match the GTK
implementation. When a bell is triggered, macOS will do the following:

  1. Bounce the dock icon once, if the app isn't already in focus.
  2. Add a bell emoji (🔔) to the title of the surface that triggered
     the bell. This emoji will be removed after the surface is focused
     or a keyboard event if the surface is already focused. This
     behavior matches iTerm2.

This doesn't add an icon badge because macOS's dockTitle.badgeLabel API
wasn't doing anything for me and I wasn't able to fully figure out
why...
2025-04-15 10:41:15 -07:00
Mitchell Hashimoto
392aab2e4a macos: quick terminal uses padded notch mode if notch is visible (#7098)
Fixes #6612
2025-04-15 09:04:44 -07:00
Mitchell Hashimoto
b77c5634f0 macos: quick terminal uses padded notch mode if notch is visible
Fixes #6612
2025-04-15 08:52:20 -07:00
Mitchell Hashimoto
62af0c0ec0 terminal: clear correct row on index operation in certain edge cases (#7093)
Fixes #7066

This fixes an issue where under certain conditions (expanded below), we
would not clear the correct row, leading to the screen having duplicate
data.

This was triggered by a page state of the following:

```
      +----------+ = PAGE 0
  ... :          :
 4305 |1ABCD00000|
 4306 |2EFGH00000|
      :^         : = PIN 0
     +-------------+ ACTIVE
 4307 |3IJKL00000| | 0
      +----------+ :
      +----------+ : = PAGE 1
    0 |          | | 1
    1 |          | | 2
      +----------+ :
     +-------------+
```

Namely, the cursor had to NOT be on the last row of the first page, but
somewhere on the first page. Then, when an `index` (LF) operation was
performed the result would look like this:

```
      +----------+ = PAGE 0
  ... :          :
 4305 |1ABCD00000|
 4306 |2EFGH00000|
     +-------------+ ACTIVE
 4307 |3IJKL00000| | 0
      :^         : : = PIN 0
      +----------+ :
      +----------+ : = PAGE 1
    0 |3IJKL00000| | 1
    1 |          | | 2
      +----------+ :
     +-------------+
```

The `3IJKL` line was duplicated. What was happening here is that we
performed the index operation correctly but failed to clear the cursor
line as expected.

This is because we were always clearing the first row in the page
instead of the row of the cursor.

Test added.
2025-04-15 07:09:18 -07:00
Mitchell Hashimoto
4aa875bbf6 ci: add logging to localization-review script (#7094)
An example of the new output (this very PR as an example):

<img
src="https://github.com/user-attachments/assets/0136238c-75d1-4bc6-8a3f-cb4b80daa512"
width="80%">

I also performed a couple of small refactors.
2025-04-14 15:56:15 -07:00
Mitchell Hashimoto
da6b478fbe terminal: clear correct row on index operation in certain edge cases
Fixes #7066

This fixes an issue where under certain conditions (expanded below), we
would not clear the correct row, leading to the screen having duplicate
data.

This was triggered by a page state of the following:

```
      +----------+ = PAGE 0
  ... :          :
 4305 |1ABCD00000|
 4306 |2EFGH00000|
      :^         : = PIN 0
     +-------------+ ACTIVE
 4307 |3IJKL00000| | 0
      +----------+ :
      +----------+ : = PAGE 1
    0 |          | | 1
    1 |          | | 2
      +----------+ :
     +-------------+
```

Namely, the cursor had to NOT be on the last row of the first page,
but somewhere on the first page. Then, when an `index` (LF) operation
was performed the result would look like this:

```
      +----------+ = PAGE 0
  ... :          :
 4305 |1ABCD00000|
 4306 |2EFGH00000|
     +-------------+ ACTIVE
 4307 |3IJKL00000| | 0
      :^         : : = PIN 0
      +----------+ :
      +----------+ : = PAGE 1
    0 |3IJKL00000| | 1
    1 |          | | 2
      +----------+ :
     +-------------+
```

The `3IJKL` line was duplicated. What was happening here is that we
performed the index operation correctly but failed to clear the cursor
line as expected.

This is because we were always clearing the first row in the page
instead of the row of the cursor.

Test added.
2025-04-14 15:54:00 -07:00
trag1c
8bc91933cd ci: add logging to localization-review script 2025-04-14 23:58:29 +02:00
Mitchell Hashimoto
8bab8f7d64 macOS: fix quick terminal fullscreen issues (#7091)
Supersedes #7075 
Fixes #7070 

This fixes a few separate fullscreen issues with the quick terminal:

1. If we're on a fullscreen space, we can't reliably set the
`autoHideMenuBar` presentation option because macOS itself is managing
it. The fix is to use private APIs to detect we're on a fullscreen space
and avoid this.

2. If our quick terminal is fullscreen when we move spaces, we must exit
and re-enter fullscreen because the frame may change (e.g. due to
menubar changes).

3. If we aren't the frontmost app, we must avoid hiding the menu because
it has no effect and our fullscreen frame would be wrong.
2025-04-14 11:29:04 -07:00
Mitchell Hashimoto
21d09fe2e0 i18: fix minor Norwegian grammar issues (#7085)
Changes the translation of 'clipboard' to definite singular form, and
removes a misplaced verb.
2025-04-14 11:22:40 -07:00
Mitchell Hashimoto
c23b389cf1 gtk: implement bell (#7087)
This PR implements a more lightweight alternative to #5326 that contains
features that I personally think Just Make Sense for the bell.

No configs, no GStreamer stuff, just sane defaults to get us started.
2025-04-14 11:19:19 -07:00
Mitchell Hashimoto
d1c15dbf07 macOS: quick terminal should retain menu if not frontmost
This is a bug I noticed in the following scenario:

  1. Open Ghostty
  2. Fullscreen normal terminal window (native fullscreen)
  3. Open quick terminal
  4. Move spaces, QT follows
  5. Fullscreen the quick terminal

The result was that the menu bar would not disappear since our app is
not frontmost but we set the fullscreen frame such that we expected it.
2025-04-14 11:17:11 -07:00
Mitchell Hashimoto
453e6590e8 macOS: non-native fullscreen should not hide menu on fullscreen space
Fixes #7075

We have to use private APIs for this, I couldn't find a reliable way
otherwise.
2025-04-14 10:38:54 -07:00
Leah Amelia Chen
3a973c692a gtk(bell): add bell-features config option
Co-authored-by: Jeffrey C. Ollie <jeff@ocjtech.us>
2025-04-15 00:18:05 +08:00
Leah Amelia Chen
abd7d9202b gtk(bell): mark tab as needing attention on bell 2025-04-14 23:44:13 +08:00
Leah Amelia Chen
10a591fba2 gtk(bell): use gdk.Surface.beep for bell
Co-authored-by: Jeffrey C. Ollie <jeff@ocjtech.us>
2025-04-14 23:44:13 +08:00
Leah Amelia Chen
a0760cabd6 gtk: implement bell
Co-authored-by: Jeffrey C. Ollie <jeff@ocjtech.us>
2025-04-14 23:44:13 +08:00
cryptocode
b932d35526 i18: fix minor Norwegian grammar issues
Changes the translation of 'clipboard' to definite singular form,
and removes a misplaced verb.
2025-04-14 16:29:59 +02:00
Mitchell Hashimoto
9d9d781a0b Mouse drag while clicked should cancel any mouse link actions (#7080)
Fixes #7077

This follows pretty standard behavior across native or popular
applications on both platforms macOS and Linux. The basic behavior is
that if you do a mouse down event and then drag the mouse beyond the
current character, then any mouse up actions are canceled (beyond
emiting the event itself).

This fixes a specific scenario where you could do the following:

  1. Click anywhere (mouse down)
  2. Drag over a valid link
  3. Press command/control (to activate the link)
  4. Release the mouse button (mouse up)
  5. The link is triggered

Now, step 3 and step 5 do not happen. Links are not even highlighted in
this scenario. This matches iTerm2 on macOS which has a similar
command-to-activate-links behavior.

## Demo


https://github.com/user-attachments/assets/f79767b1-78fd-432b-af46-28194b816747
2025-04-13 19:37:13 -07:00
Mitchell Hashimoto
f7394c00c1 macOS: only emit a mouse exited position if we're not dragging (#7077)
Fixes #7071

When the mouse is being actively dragged, AppKit continues to emit
mouseDragged events which will update our position appropriately. The
mouseExit event we were sending sends a synthetic (-1, -1) position
which was causing a scroll up.
2025-04-13 14:58:31 -07:00
Mitchell Hashimoto
6d3f97ec1e Mouse drag while clicked should cancel any mouse link actions
Fixes #7077

This follows pretty standard behavior across native or popular applications
on both platforms macOS and Linux. The basic behavior is that if you
do a mouse down event and then drag the mouse beyond the current
character, then any mouse up actions are canceled (beyond emiting the
event itself).

This fixes a specific scenario where you could do the following:

  1. Click anywhere (mouse down)
  2. Drag over a valid link
  3. Press command/control (to activate the link)
  4. Release the mouse button (mouse up)
  5. The link is triggered

Now, step 3 and step 5 do not happen. Links are not even highlighted in
this scenario. This matches iTerm2 on macOS which has a similar
command-to-activate-links behavior.
2025-04-13 14:56:40 -07:00
Mitchell Hashimoto
6d80388155 macOS: only emit a mouse exited position if we're not dragging
Fixes #7071

When the mouse is being actively dragged, AppKit continues to emit
mouseDragged events which will update our position appropriately. The
mouseExit event we were sending sends a synthetic (-1, -1) position
which was causing a scroll up.
2025-04-13 12:46:39 -07:00
Mitchell Hashimoto
66636195f1 Introduce Issue Triage Template (#7012)
The helper team has been discussing some common issues we see with
Discussion submissions (missing info, duplicates, etc.), and pluie's
#6937 has been a huge step forward - this PR introduces a template for
the Issue Triage Discussion type.

The template has gone through a few revisions prior to this PR, but I am
certain there are probably a few places to be cleaned up. You can test
it out by [opening a new "Issue Triage" Discussion in my
fork](https://github.com/taylrfnt/ghostty/discussions/new?category=issue-triage).

~~Creating this as a draft for now, since I may not be able to respond
to any review comments in a timely manner.~~
2025-04-11 14:17:41 -07:00
Mitchell Hashimoto
f777138590 mk_MK localization (#6902) 2025-04-11 12:52:51 -07:00
Mitchell Hashimoto
deed2707a5 CODEOWNERS 2025-04-11 12:50:12 -07:00
Andrej Daskalov
dcc2e9eaf8 Merge branch 'main' into mk-localization 2025-04-11 21:47:07 +02:00
Mitchell Hashimoto
74b17f68b5 i18n: add catalan translations (#6841)
Hi there!
This PR adds the Catalan translations (ca_ES.UTF-8).

Salut
2025-04-11 10:22:54 -07:00
Francesc Arpi Roca
d749e1b87e i18n: fix the "deny" catalan translation 2025-04-11 10:20:53 -07:00
Francesc Arpi Roca
e30feb3bfb i18n: fix string length 2025-04-11 10:20:44 -07:00
Francesc Arpi Roca
a092d7ae42 i18n: add catalan translations 2025-04-11 10:20:44 -07:00
Mitchell Hashimoto
9233413126 i18n: add pt-BR (Brazilian Portuguese) translation (#6966)
With this PR now it supports the brazilian portuguese language for
ghostty, native speaker and resident, want to bring this language to
this new terminal that is starting to become very fondly to me! Any
questions about it i am free to answer.
2025-04-11 10:14:47 -07:00
Mitchell Hashimoto
24847293f2 update CODEOWNERS 2025-04-11 10:12:19 -07:00
g
7e67312c61 grammar fix and correct form for some phrases 2025-04-11 10:12:06 -07:00
g
11f5797a91 fix in lower case when required 2025-04-11 10:12:06 -07:00
Gustavo
e31c8e09ed Update po/pt_BR.UTF-8.po
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-04-11 10:12:06 -07:00
g
f794afe2d8 standard file extension name 2025-04-11 10:12:06 -07:00
g
63ccdf2cff fix in capital letters 2025-04-11 10:12:06 -07:00
g
c19f2aa1bc Add pt-BR translations to ghostty 2025-04-11 10:12:06 -07:00
Mitchell Hashimoto
9751f43529 Add Spanish translations (419 = Latin America) (#6940)
Hi!
I have followed the instructions and added translations for Spanish,
Country Latin America 419 according to
[this](https://localizely.com/locale-code/es-419/) and other online
sources.
In the provided links there was no references to 419, but I created it
via the suggested command:
`msginit -i po/com.mitchellh.ghostty.pot -l es_419.UTF-8 -o
"po/es_419.UTF-8.po" `
Glad to be able to contribute to this excellent product!
Cheers!
2025-04-11 10:11:26 -07:00
MiguelElGallo
5bbed046f6 add Spanish (Bolivia) translations and locale support 2025-04-11 10:09:05 -07:00
MiguelElGallo
a9f9abd615 add Spanish (Latin America) locale support 2025-04-11 10:08:44 -07:00
MiguelElGallo
e5de000895 add Spanish translations (419 = Latin America) for com.mitchellh.ghostty package 2025-04-11 10:08:22 -07:00
Mitchell Hashimoto
9cd3d3826a feat: Add Turkish translations (#6898) 2025-04-11 10:01:29 -07:00
Emir SARI
913c6dc7df feat: Add Turkish translations 2025-04-11 09:57:19 -07:00
Mitchell Hashimoto
17b7920f65 Add nl_NL (Dutch) translations (#6894) 2025-04-11 09:52:33 -07:00
Mitchell Hashimoto
14cac67b98 CODEOWNERS 2025-04-11 09:51:18 -07:00
Nico Geesink
b0b09bf034 Fix spell errors 2025-04-11 09:51:04 -07:00
Nico Geesink
059caef118 Use informal 'you' and change verander to wijzig 2025-04-11 09:51:04 -07:00
Nico Geesink
960fcc275f Fix typos and make sentences more fluent 2025-04-11 09:51:04 -07:00
Nico Geesink
e415b6db42 Merge branch 'main' into main 2025-04-11 09:51:04 -07:00
Nico Geesink
cd6a8f6a65 Fix typo 2025-04-11 09:50:44 -07:00
Nico Geesink
7db64b8e34 Add name and don't use title case 2025-04-11 09:50:44 -07:00
Nico Geesink
e52aad5dea Add nl_NL (Dutch) translations 2025-04-11 09:50:44 -07:00
Mitchell Hashimoto
6899e9d984 Added Russian translation for Ghostty (#6889) 2025-04-11 09:48:50 -07:00
Mitchell Hashimoto
52ac670913 CODEOWNERS 2025-04-11 09:47:11 -07:00
blackzeshi
077ae6a098 Update po/ru_RU.UTF-8.po
Co-authored-by: TicClick <ya@ticclick.ch>
2025-04-11 09:45:55 -07:00
blackzeshi
0d226d139b Update po/ru_RU.UTF-8.po
Co-authored-by: TicClick <ya@ticclick.ch>
2025-04-11 09:45:55 -07:00
blackzeshi
d0403021a4 Update po/ru_RU.UTF-8.po
2 line fixed

Co-authored-by: TicClick <ya@ticclick.ch>
2025-04-11 09:45:55 -07:00
blackzeshi
f4054daf0d Update po/ru_RU.UTF-8.po
262 line about debug build fixed

Co-authored-by: TicClick <ya@ticclick.ch>
2025-04-11 09:45:55 -07:00
blackzeshi
0d23f7af31 Update po/ru_RU.UTF-8.po
248 line changed

Co-authored-by: TicClick <ya@ticclick.ch>
2025-04-11 09:45:55 -07:00
blackzeshi
2b0a81d982 Merge branch 'main' into add_russian 2025-04-11 09:45:55 -07:00
blackzeshi
91f9fdb1be some fixes to adding russian translation (i.e. emoji) 2025-04-11 09:45:37 -07:00
blackzeshi
df5dd1858a add russian translation 2025-04-11 09:45:37 -07:00
Mitchell Hashimoto
444352418c i18n: Add French translation (#6868)
Hi ! 
This is just to add a first version of a french translation !
2025-04-11 09:44:38 -07:00
Mitchell Hashimoto
5be4b0de6b CODEOWNERS 2025-04-11 09:42:48 -07:00
Nicolas G
ca336f5310 Merge branch 'main' into main 2025-04-11 09:42:12 -07:00
Kirwiisp
5ca5afb13d fix: spelling and typo 2025-04-11 09:41:49 -07:00
Kirwiisp
930079ca01 fix: spelling mistakes 2025-04-11 09:41:49 -07:00
Nicolas G
1aa16cdf6b Fix ponctuation and Warning translation
Fix: missing ponctuations on various lines.

Change "Warning" to "Attention", might change in the futur if it does not perfectly match  common practice.

Fix: Multiline on config errors dialog
2025-04-11 09:41:49 -07:00
Kirwiisp
e2a8a3243c i18n: Add French translation 2025-04-11 09:41:49 -07:00
Mitchell Hashimoto
8d1a57cde3 i18n: Add Japanese translations (#6866)
This pull request adds Japanese(ja_JP.UTF-8) translations.
2025-04-11 09:39:51 -07:00
Lon Sagisawa
10a90b5b67 fix: inconsistency around space 2025-04-11 09:38:37 -07:00
Lon Sagisawa
20ef2150de i18n: Add Japanese translations 2025-04-11 09:38:37 -07:00
Mitchell Hashimoto
028759e8f6 Add Indonesian id_ID translations. (#6836)
Add the Indonesian id_ID translations.
2025-04-11 09:33:40 -07:00
Mitchell Hashimoto
7adc2954c3 update CODEOWNERS 2025-04-11 09:27:04 -07:00
halosatrio
561a0e3897 i18n: fix capitalization and some translation 2025-04-11 09:26:00 -07:00
halosatrio
1222e80eb1 i18n: add id_ID code locale 2025-04-11 09:26:00 -07:00
halosatrio
d903cc9827 i18n: fix translation 2025-04-11 09:25:35 -07:00
halosatrio
02bb81ad44 i18n: add indonesian translation 2025-04-11 09:25:35 -07:00
Mitchell Hashimoto
b16324ef0b ci: add a script and workflow for requesting i18n review (#7053)
From #7052, but for some reason I couldn't push there:

> This helps get around the `CODEOWNERS` file requiring that
contributors need to have write access to the repo in order to be
requested for review. The mechanism is (for any new PR):
> 1. List the changed files
> 2. Fetch and parse the CODEOWNERS file to get a path:owner mapping
> 3. See if any changed file matches the CODEOWNERS mapping
> 4. Fetch team members for affected localization teams
> 5. Request review from individual accounts
2025-04-10 19:46:27 -04:00
trag1c
f0ade53fd2 ci: add a script and workflow for requesting i18n review 2025-04-10 16:40:28 -07:00
taylrfnt
49a97a589c fix typo - exiting to existing
Co-authored-by: Leah Amelia Chen <github@acc.pluie.me>
2025-04-10 17:45:35 -05:00
Mitchell Hashimoto
d7f75b348d config: allow commands to specify whether they shell expand or not (#7044)
Fixes #7032 

This introduces a syntax for `command` and `initial-command` that allows
the user to specify whether it should be run via `/bin/sh -c` or not.
The syntax is a prefix `direct:` or `shell:` prior to the command, with
no prefix implying a default behavior as documented.

Previously, we unconditionally ran commands via `/bin/sh -c`, primarily
to avoid having to do any shell expansion ourselves. We also leaned on
it as a crutch for PATH-expansion but this is an easy problem compared
to shell expansion.

For the principle of least surprise, this worked well for configurations
specified via the config file, and is still the default. However, these
configurations are also set via the `-e` special flag to the CLI, and it
is very much not the principle of least surprise to have the command run
via `/bin/sh -c` in that scenario since a shell has already expanded all
the arguments and given them to us in a nice separated format. But we
had no way to toggle this behavior.

This commit introduces the ability to do this, and changes the defaults
so that `-e` doesn't shell expand. Further, we also do PATH lookups
ourselves for the non-shell expanded case because thats easy (using
execvpe style extensions but implemented as part of the Zig stdlib). We
don't do path expansion (e.g. `~/`) because thats a shell expansion.

So to be clear, there are no two polar opposite behavioes here with
clear semantics:

1. Direct commands are passed to `execvpe` directly, space separated.
This will not handle quoted strings, environment variables, path
expansion (e.g. `~/`), command expansion (e.g. `$()`), etc.

2. Shell commands are passed to `/bin/sh -c` and will be shell expanded
as per the shell's rules. This will handle everything that `sh`
supports.

In doing this work, I also stumbled upon a variety of smaller
improvements that could be made:

- A number of allocations have been removed from the startup path that
only existed to add a null terminator to various strings. We now have
null terminators from the beginning since we are almost always on a
system that's going to need it anyways.

- For bash shell integration, we no longer wrap the new bash command in
a shell since we've formed a full parsed command line.

- The process of creating the command to execute by termio is now unit
tested, so we can test the various complex cases particularly on macOS
of wrapping commands in the login command.

- `xdg-terminal-exec` on Linux uses the `direct:` method by default
since it is also assumed to be executed via a shell environment.
2025-04-10 16:32:18 -04:00
Mitchell Hashimoto
d4a5e5f88e elvish: use kitty-shell-cwd:// to report pwd (#7033)
OSC 7's standard body is a percent-encoded file:// URL. There isn't an
easy way for us to percent-encode the path ($pwd) component here without
implementing a custom function.

Instead, switch to the kitty-shell-cwd:// scheme, which Kitty introduced
to ease this implementation challenge in shell scripts. It accepts the
path string verbatim, without an encoding.

In Ghostty, we accept both the file:// and kitty-shell-cwd:// schemes,
and we attempt to URI-decode them both, so in practice this is more
about the "correctness" of this protocol than a functional change. It's
also possible we might decide to treat these schemes differently in the
runtime, like Kitty does.

Also, fix the `platform:hostname` function call syntax.
2025-04-10 16:19:26 -04:00
Mitchell Hashimoto
722d41a359 config: allow commands to specify whether they shell expand or not
This introduces a syntax for `command` and `initial-command` that allows
the user to specify whether it should be run via `/bin/sh -c` or not.
The syntax is a prefix `direct:` or `shell:` prior to the command,
with no prefix implying a default behavior as documented.

Previously, we unconditionally ran commands via `/bin/sh -c`, primarily
to avoid having to do any shell expansion ourselves. We also leaned on
it as a crutch for PATH-expansion but this is an easy problem compared
to shell expansion.

For the principle of least surprise, this worked well for configurations
specified via the config file, and is still the default. However, these
configurations are also set via the `-e` special flag to the CLI, and it
is very much not the principle of least surprise to have the command run via
`/bin/sh -c` in that scenario since a shell has already expanded all the
arguments and given them to us in a nice separated format. But we had no
way to toggle this behavior.

This commit introduces the ability to do this, and changes the defaults
so that `-e` doesn't shell expand. Further, we also do PATH lookups
ourselves for the non-shell expanded case because thats easy (using
execvpe style extensions but implemented as part of the Zig stdlib). We don't
do path expansion (e.g. `~/`) because thats a shell expansion.

So to be clear, there are no two polar opposite behavioes here with
clear semantics:

  1. Direct commands are passed to `execvpe` directly, space separated.
     This will not handle quoted strings, environment variables, path
     expansion (e.g. `~/`), command expansion (e.g. `$()`), etc.

  2. Shell commands are passed to `/bin/sh -c` and will be shell expanded
     as per the shell's rules. This will handle everything that `sh`
     supports.

In doing this work, I also stumbled upon a variety of smaller
improvements that could be made:

  - A number of allocations have been removed from the startup path that
    only existed to add a null terminator to various strings. We now
    have null terminators from the beginning since we are almost always
    on a system that's going to need it anyways.

  - For bash shell integration, we no longer wrap the new bash command
    in a shell since we've formed a full parsed command line.

  - The process of creating the command to execute by termio is now unit
    tested, so we can test the various complex cases particularly on
    macOS of wrapping commands in the login command.

  - `xdg-terminal-exec` on Linux uses the `direct:` method by default
    since it is also assumed to be executed via a shell environment.
2025-04-10 13:15:14 -07:00
Leah Amelia Chen
046e92865b gtk: fix forcing the window theme to light or dark (#7039)
Fixes #7038
2025-04-09 08:32:50 +08:00
Jeffrey C. Ollie
cb1b447e8c gtk: fix forcing the window theme to light or dark
Fixes #7038
2025-04-08 18:33:12 -05:00
Jon Parise
5b4976f6ef elvish: fix platform:hostname function call syntax 2025-04-08 10:54:26 -04:00
Jon Parise
b213c157f0 elvish: use kitty-shell-cwd:// to report pwd
OSC 7's standard body is a percent-encoded file:// URL. There isn't an
easy way for us to percent-encode the path ($pwd) component here without
implementing a custom function.

Instead, switch to the kitty-shell-cwd:// scheme, which Kitty introduced
to ease this implementation challenge in shell scripts. It accepts the
path string verbatim, without an encoding.

In Ghostty, we accept both the file:// and kitty-shell-cwd:// schemes,
and we attempt to URI-decode them both, so in practice this is more
about the "correctness" of this protocol than a functional change. It's
also possible we might decide to treat these schemes differently in the
runtime, like Kitty does.
2025-04-08 10:38:57 -04:00
Mitchell Hashimoto
17ba0252e8 Update iTerm2 colorschemes (#7007)
Upstream revision:
4c57d8c11d
2025-04-07 20:31:54 -07:00
Mitchell Hashimoto
dc0b9a703d fix(kittygfx): accept commands with no control data (#7023)
This sort of command is treated as valid by Kitty so we should too. In
fact, it occurs with the example `send-png` script provided in the docs
for the protocol.
2025-04-07 20:31:41 -07:00
taylrfnt
6d36eeef3c add the verbosity
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-04-07 21:41:29 -05:00
taylrfnt
8a446b7776 remove the verbosity
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-04-07 21:41:09 -05:00
taylrfnt
279a6b6f58 fix typos & make it read more naturally 2025-04-07 21:27:01 -05:00
taylrfnt
9440dbba1a add notes abotu minimum config 2025-04-07 21:25:26 -05:00
taylrfnt
a6123c0447 fix trailing whitespace 2025-04-07 20:41:48 -05:00
taylrfnt
92959bc09c fix typo
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-04-07 20:39:22 -05:00
taylrfnt
b3c61d90f3 add note about commits 2025-04-07 20:37:57 -05:00
Jon Parise
f1472362af Use built-in functions for elvish (#7025)
Currently the elvish shell integration uses the `hostname` command, this
may not exist on all systems and is somewhat redundant to rely on when
elvish has an
[`platform:hostname`](https://elv.sh/ref/platform.html#platform:hostname)
function that can be used and will work across platform regardless of
command availability. On top of this instead of directly calling the
`pwd` function we can simply use the built-in
[`$pwd`](https://elv.sh/ref/builtin.html#$pwd) variable that elvish
gives us. This should prevent the shell integration from breaking due to
external function availability.
2025-04-07 18:09:09 -04:00
taylrfnt
d3b7fe3473 make following into these for better readability 2025-04-07 15:28:31 -05:00
taylrfnt
ddb85ca1b1 better discussion & issue callout in the important note
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-04-07 15:25:54 -05:00
taylrfnt
c7635d5f41 remove the please
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-04-07 15:19:38 -05:00
Hanna
a8f760c6d2 fix: undo accidental replace 2025-04-07 16:10:50 -04:00
Hanna
77f5fe2560 fix: parenthesis are unneeded around builtins 2025-04-07 16:09:43 -04:00
Hanna
9808c13796 refactor: use builtin hostname function 2025-04-07 16:02:53 -04:00
Jon Parise
e73970533a shell-integration: Fix condition for sudo (#7021)
A missing ";" meant the check for $TERMINFO was never executed.
2025-04-07 15:53:50 -04:00
Qwerasd
b64f49a0d7 fix(kittygfx): accept commands with no control data
This sort of command is treated as valid by Kitty so we should too. In
fact, it occurs with the example `send-png` script provided in the docs
for the protocol.
2025-04-07 13:31:51 -06:00
Fabian Boehm
df174a74f8 shell-integration: Fix condition for sudo
A missing ";" meant the check for $TERMINFO was never executed.
2025-04-07 21:20:21 +02:00
Mitchell Hashimoto
3878e46707 Fix macOS shortcut binding for close_window action (#7020)
Fixes #7003
2025-04-07 10:04:26 -07:00
Bryan Lee
9144f4db58 Fix macOS shortcut binding for close_window action 2025-04-08 00:44:53 +08:00
taylrfnt
9643e9c7a6 introduce issue triage template 2025-04-06 19:29:58 -05:00
mitchellh
f6ec39a5d8 deps: Update iTerm2 color schemes 2025-04-06 00:13:30 +00:00
Mitchell Hashimoto
6f7977fef1 macos: replay control+key events that go to doCommand (#7001)
Fixes #7000

Related to #6909, the same mechanism, but it turns out some control+keys
are also handled in this same way (namely control+esc leads to "cancel"
by default, which is not what we want).
2025-04-04 22:28:20 -04:00
Mitchell Hashimoto
fe0536aaaf macos: replay control+key events that go to doCommand
Fixes #7000

Related to #6909, the same mechanism, but it turns out some control+keys
are also handled in this same way (namely control+esc leads to "cancel"
by default, which is not what we want).
2025-04-04 22:09:04 -04:00
Mitchell Hashimoto
c0eaa4b158 macos: left mouse click while not focused doesn't encode to pty (#6998)
Fixes #2595

This fixes an issue where a left mouse click on a terminal while not
focused would subsequently be encoded to the pty as a mouse event. This
is atypical for macOS applications in general and wasn't something we
wanted to do.

We do, however, want to ensure our terminal gains focus when clicked
without focus. Specifically, a split. This matches iTerm2 behavior and
is rather nice. We had this behavior before but our logic to make this
work before caused the issue this commit is fixing.

I also tested this with command+click which is a common macOS shortcut
to emit a mouse event without raising the focus of the target window. In
this case, we will properly focus the split but will not encode the
mouse event to the pty. I think we actually do a _better job_ here tha
iTerm2 (but, subjective) because we do encode the pty event properly if
the split is focused whereas iTerm2 never does.
2025-04-04 19:31:22 -04:00
Mitchell Hashimoto
f228933955 macos: left mouse click while not focused doesn't encode to pty
Fixes #2595

This fixes an issue where a left mouse click on a terminal while not
focused would subsequently be encoded to the pty as a mouse event. This
is atypical for macOS applications in general and wasn't something we
wanted to do.

We do, however, want to ensure our terminal gains focus when clicked
without focus. Specifically, a split. This matches iTerm2 behavior and
is rather nice. We had this behavior before but our logic to make this
work before caused the issue this commit is fixing.

I also tested this with command+click which is a common macOS shortcut
to emit a mouse event without raising the focus of the target window. In
this case, we will properly focus the split but will not encode the
mouse event to the pty. I think we actually do a _better job_ here tha
iTerm2 (but, subjective) because we do encode the pty event properly if
the split is focused whereas iTerm2 never does.
2025-04-04 19:17:03 -04:00
Mitchell Hashimoto
60da3cf6a0 shell-integration: switch to $GHOSTTY_SHELL_FEATURES (#6871)
This change consolidates all three opt-out shell integration environment
variables into a single opt-in $GHOSTTY_SHELL_FEATURES variable. Its
value is a comma-delimited list of the enabled shell feature names (e.g.
"cursor,title").

$GHOSTTY_SHELL_FEATURES is set at runtime and automatically added to the
shell environment. Its value is based on the shell-integration-features
configuration option.

$GHOSTTY_SHELL_FEATURES is only set when at least one shell feature is
enabled. It won't be set when 'shell-integration-features = false'.

$GHOSTTY_SHELL_FEATURES lists only the enabled shell feature names. We
could have alternatively gone in the opposite direction and listed the
disabled features, letting the scripts assume each feature is on by
default like we did before, but I think this explicit approach is a
little safer and easier to reason about / debug.

It also doesn't support the "no-" negation prefix used by the config
system (e.g. "cursor,no-title"). This simplifies the implementation
requirements of our (multiple) shell integration scripts, and because
$GHOSTTY_SHELL_FEATURES is derived from shell-integration-features, the
user-facing configuration interface retains that expressiveness.

$GHOSTTY_SHELL_FEATURES is intended to primarily be an internal concern:
an interface between the runtime and our shell integration scripts. It
could be used by people with particular use cases who want to manually
source those scripts, but that isn't the intended audience.

... and because the previous $GHOSTTY_SHELL_INTEGRATION_NO_* variables
were also meant to be an internal concern, this change does not include
backwards compatibility support for those names.

One last advantage of a using a single $GHOSTTY_SHELL_FEATURES variable
is that it can be easily forwarded to e.g. ssh sessions or other shell
environments.

See: #5070
2025-04-04 17:05:37 -04:00
Mitchell Hashimoto
17a19e4837 docs: use Command instead of super for macOS (#6987)
Command is the name Apple uses for this key and that's printed on the
keyboard 😉
2025-04-03 21:31:05 -04:00
Mitchell Hashimoto
970fcdf671 libghostty: Action CValue should be untagged extern union (#6992)
Fixes #6962

I believe this is an upstream bug
(https://github.com/ziglang/zig/issues/23454), where Zig is allowing
extern unions to be tagged when created via type reification. This
results in a CValue that has an extra trailing byte (the tag).

This wasn't causing any noticeable issues for Ghostty for some reason
but others using our pattern were seeing issues. And I did confirm that
our CValue was indeed tagged and was the wrong byte size. I assume Swift
was just ignoring it because it was extra data. I don't know, but we
should fix this in general for libghostty.
2025-04-03 21:14:01 -04:00
Mitchell Hashimoto
e19b5a150a libghostty: Action CValue should be untagged extern union
Fixes #6962

I believe this is an upstream bug
(https://github.com/ziglang/zig/issues/23454), where Zig is allowing
extern unions to be tagged when created via type reification. This
results in a CValue that has an extra trailing byte (the tag).

This wasn't causing any noticeable issues for Ghostty for some reason
but others using our pattern were seeing issues. And I did confirm that
our CValue was indeed tagged and was the wrong byte size. I assume Swift
was just ignoring it because it was extra data. I don't know, but we
should fix this in general for libghostty.
2025-04-03 20:57:31 -04:00
Simon Olofsson
af0004eb52 docs: use Command instead of super for macOS
Command is the name Apple uses for this key and that's printed on the keyboard 😉
2025-04-03 11:03:48 +02:00
Leah Amelia Chen
6f1b22aca5 gtk(x11): fix blur regions when using >200% scaling (#6978)
See #6957

We were not considering GTK's internal scale factor that converts
between "surface coordinates" and actual device coordinates, and that
worked fine until the scale factor reached 2x (200%).

Since the code is now dependent on the scale factor (which could change
at any given moment), we also listen to scale factor changes and then
unconditionally call `winproto.syncAppearance`. Even though it's
somewhat overkill, I don't expect people to change their scale factor
dramatically all the time anyway...
2025-04-02 17:38:27 +02:00
Leah Amelia Chen
969839acf3 gtk(x11): fix blur regions when using >200% scaling
See #6957

We were not considering GTK's internal scale factor that converts between
"surface coordinates" and actual device coordinates, and that worked fine
until the scale factor reached 2x (200%).

Since the code is now dependent on the scale factor (which could change
at any given moment), we also listen to scale factor changes and then
unconditionally call `winproto.syncAppearance`. Even though it's somewhat
overkill, I don't expect people to change their scale factor dramatically
all the time anyway...
2025-04-02 17:21:28 +02:00
Jeffrey C. Ollie
1067cd3d8a core: update libvaxis and zf for transitive zigimg dependency (#6947) 2025-03-28 14:55:28 -05:00
Jeffrey C. Ollie
9f57a03926 core: update libvaxis and zf for transitive zigimg dependency 2025-03-28 14:31:57 -05:00
Mitchell Hashimoto
0afb922375 macos: reset the last command key state when keyDown event (#6933)
Fixes a regression from #6909
See #6887

In certain scenarios, the last command key state would linger around (I
could only see this happen with global keybinds for unknown reasons
yet). This state is only meant to have an effect within the cycle of a
single keybind and only so we can ensure an event reaches keyDown so it
should be reset if keyDown is ever sent (since, by definition at that
point, keyDown has been reached).

I'm still not happy that this is necessary and I suspect there is a
better root cause to resolve, but I'd rather get this fix in now and
figure out the root cause later.
2025-03-27 07:50:33 -07:00
Mitchell Hashimoto
99843cf54d macos: reset the last command key state when keyDown event
Fixes a regression from #6909
See #6887

In certain scenarios, the last command key state would linger around (I
could only see this happen with global keybinds for unknown reasons
yet). This state is only meant to have an effect within the cycle of a
single keybind and only so we can ensure an event reaches keyDown so it should
be reset if keyDown is ever sent (since, by definition at that point,
keyDown has been reached).

I'm still not happy that this is necessary and I suspect there is a
better root cause to resolve, but I'd rather get this fix in now and
figure out the root cause later.
2025-03-27 07:22:05 -07:00
Jeffrey C. Ollie
1c3693c383 version bump for development (#6928) 2025-03-26 23:46:59 -05:00
Jeffrey C. Ollie
27978ef4d0 version bump for development 2025-03-26 23:29:15 -05:00
Leah Amelia Chen
494279419a gtk: use up-to-date maximized & fullscreen state in syncAppearance (#6924)
DerivedConfig's maximize and fullscreen should only ever be used during
window creation and nowhere else.
2025-03-26 20:33:55 +01:00
Leah Amelia Chen
ae3e92a3fb gtk: use up-to-date maximized & fullscreen state in syncAppearance
DerivedConfig's maximize and fullscreen should only ever be used during
window creation and nowhere else.
2025-03-26 20:15:18 +01:00
Jeffrey C. Ollie
ed4260b3c2 fix: escape characters in shell escape test (#6925)
Fix the escape.

Sorry again for the inconveniences. Let's check if the test is now green
2025-03-26 14:14:38 -05:00
Ian den Hartog
18cc119ced fix: escape characters in shell escape test 2025-03-26 19:52:36 +01:00
Jeffrey C. Ollie
613857cf7e fix: add ( and ) to escape characters when dropping files in gtk (#6922)
Currently when dropping files in gtk with file names that include ( or )
will generate a bash error.

With this change ( and ) will be escaped.
2025-03-26 13:38:10 -05:00
Ian den Hartog
447a889559 fix: add ( and ) to escape characters when dropping files in gtk 2025-03-26 19:30:07 +01:00
Mitchell Hashimoto
837cdf0556 Metal: fix crunchy constrained glyphs (#6914)
Fixes problem pointed out in discussion #6895, as well as adjusting the
constraint logic to account for the offset, since I noticed it was
wrong; the constraint logic now accounts for the x offset, so that the
glyph does not exceed the right edge of the constraint width when the
offset is added, and the offset is zeroed if the glyph is resized down
to fit the constraint width.

|**Before**|**After**|
|-|-|
|<img width="84" alt="image"
src="https://github.com/user-attachments/assets/9561ca40-cfa0-4aed-b192-ee15042d8cbb"
/>|<img width="82" alt="image"
src="https://github.com/user-attachments/assets/9a77ac61-f46d-41de-a859-2b394024f7bc"
/>|

<sup>Zoom in to images for detail if you can't see the
crunchiness.</sup>

> [!NOTE]
> It may be an issue that that glyph is rendered with the constrained
text mode in the first place - Kitty doesn't seem to apply constraint
logic to it, and it seems a little over-eager to do so on our part. This
is something to look in to.
2025-03-26 11:20:14 -07:00
Qwerasd
e96f94d8d7 fix(Metal): improve constraint width logic to account for x offset 2025-03-25 21:14:38 -06:00
Qwerasd
6f9a362a4d fix(Metal): fix crunchy appearance of constrained glyphs
We can't use nearest neighbor filtering for sampling from the atlas
because we might not actually be doing pixel perfect sampling if the
glyph has been constrained. This will change in the future, but this
will have to be set to linear for now.
2025-03-25 20:57:08 -06:00
Mitchell Hashimoto
bcff4e18f4 macos: remove special-case cmd+period handling, redispatch unhandled doCommand (#6909)
Fixes #5522

This commit re-dispatches command inputs that are unhandled by our macOS
app so they can be encoded to the pty and handled by the core libghostty
key callback system.

We've had a special case `cmd+period` handling in Ghostty for a very
long time (since well into the private beta). `cmd+period` by default
binds to "cancel" in macOS, so it doesn't encode to the pty. We don't
handle "cancel" in any meaningful way in Ghostty, so we special-cased it
to encode properly to the pty.

However, as shown in #5522, if the user rebinds `cmd+period` at the
system level to some other operation, then this is ignored and we encode
it still. This isn't desirable, we just want to work around not caring
about "cancel."

The callback path that AppKit takes for key events is a bit convoluted.
For command keys, it first calls `performKeyEquivalent`. If this returns
false (we want to continue standard processing), then it calls EITHER
`keyDown` or `doCommand(by:)`. It calls the latter if there is a
standard system command that matches the key event. For `cmd+period` by
default, this is "cancel." Unfortunately, from `doCommand` we can't say
"oops, we don't want to handle this, please continue processing." Its
too late.

So, this commit stores the last command key event from
`performKeyEquivalent` and if we reach `doCommand` for it without having
called `keyDown`, we re-dispatch the event and send it to keyDown.

I'm honestly pretty sus about this whole logic but it is scoped to only
command-keys and I couldn't trigger any adverse behavior in my testing.
It also definitely fixed #5522 as far as I could reproduce it before.
2025-03-25 15:18:54 -07:00
Mitchell Hashimoto
67f47a6e22 macos: remove special-case cmd+period handling
Fixes #5522

This commit re-dispatches command inputs that are unhandled by our macOS
app so they can be encoded to the pty and handled by the core libghostty
key callback system.

We've had a special case `cmd+period` handling in Ghostty for a very
long time (since well into the private beta). `cmd+period` by default
binds to "cancel" in macOS, so it doesn't encode to the pty. We don't
handle "cancel" in any meaningful way in Ghostty, so we special-cased it
to encode properly to the pty.

However, as shown in #5522, if the user rebinds `cmd+period` at the
system level to some other operation, then this is ignored and we encode
it still. This isn't desirable, we just want to work around not caring
about "cancel."

The callback path that AppKit takes for key events is a bit convoluted.
For command keys, it first calls `performKeyEquivalent`. If this returns
false (we want to continue standard processing), then it calls EITHER
`keyDown` or `doCommand(by:)`. It calls the latter if there is a
standard system command that matches the key event. For `cmd+period` by
default, this is "cancel." Unfortunately, from `doCommand` we can't say
"oops, we don't want to handle this, please continue processing." Its
too late.

So, this commit stores the last command key event from
`performKeyEquivalent` and if we reach `doCommand` for it without having
called `keyDown`, we re-dispatch the event and send it to keyDown.

I'm honestly pretty sus about this whole logic but it is scoped to only
command-keys and I couldn't trigger any adverse behavior in my testing.
It also definitely fixed #5522 as far as I could reproduce it before.
2025-03-25 15:03:27 -07:00
Aaron Ruan
416b617de9 fix canonicalizing some zh locales (#6885)
resolve #6870

---------

Signed-off-by: Aaron Ruan <i@ar212.com>
2025-03-25 14:46:14 +00:00
Andrej Daskalov
6c3accede8 remove extra punctuation
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-03-25 09:53:18 +01:00
Andrej Daskalov
7915ef5661 moved mk locale to bottom of list 2025-03-25 09:48:51 +01:00
Andrej Daskalov
6e6689d825 Merge branch 'main' into mk-localization 2025-03-25 09:46:56 +01:00
Mitchell Hashimoto
5d9bee98e8 pl_PL translations (#6771)
The initial take on the `pl_PL` translation.
2025-03-24 10:43:47 -07:00
Bartosz Sokorski
bf179207a1 Add pl_PL translations
Co-authored-by: chupson <chupson@chupson.dev>
Co-authored-by: trag1c <dev@jakubr.me>
2025-03-24 10:41:29 -07:00
Mitchell Hashimoto
150b7bdad1 feat: add Ukrainian translations and locale support (#6759)
Added the Ukrainian `uk_UA` translations.
2025-03-24 10:39:34 -07:00
Danylo Zalizchuk
20111048a4 fead: add new Ukrainian translations 2025-03-24 10:36:25 -07:00
Danylo Zalizchuk
36c7fda40b Merge branch 'main' of github.com:danulqua/ghostty 2025-03-24 10:36:25 -07:00
Danylo Zalizchuk
99da99cb9c Merge branch 'main' into main 2025-03-24 10:35:36 -07:00
Danylo Zalizchuk
b8b5882c75 fix: removed words capitalization in the Ukrainian translations 2025-03-24 10:35:18 -07:00
Danylo Zalizchuk
e6b77cf008 fix: update "Reloaded the configuration" translation 2025-03-24 10:35:18 -07:00
Danylo Zalizchuk
90a3719275 fix: reorder locales to ensure they follow ASCII ordering 2025-03-24 10:35:18 -07:00
Danylo Zalizchuk
c1bf301bc7 feat: add Ukrainian translations and locale support 2025-03-24 10:34:53 -07:00
Mitchell Hashimoto
7200c87326 pkg/harfbuzz: update 8.4 => 11.0 (#6897)
This updates our bundled Harfbuzz from 8.4 to 11.0. The changes from 8
to 11 include a number of correctness and performance improvements.
Packaged releases tend to dynamically link so this won't affect existing
users, but build-from-source users hopefully get an improvement.
2025-03-24 10:26:59 -07:00
Mitchell Hashimoto
89728070e9 pkg/harfbuzz: update 8.4 => 11.0
This updates our bundled Harfbuzz from 8.4 to 11.0. The changes from 8
to 11 include a number of correctness and performance improvements.
Packaged releases tend to dynamically link so this won't affect
existing users, but build-from-source users hopefully get an
improvement.
2025-03-24 10:04:11 -07:00
Mitchell Hashimoto
c1ef0c0369 pkg/glfw: update to HEAD as of 2025-03-24 (#6896)
We have always tracked a post-3.4 release, this brings us up to date.
There's no real motivation beyond this other than keeping up to date
since we're already on non-release versions anyways. The diff is
dominated by auto-generated headers from Wayland-scanner.
2025-03-24 10:01:30 -07:00
Mitchell Hashimoto
8cc5ee39d0 pkg/glfw: update to HEAD as of 2025-03-24
We have always tracked a post-3.4 release, this brings us up to date.
There's no real motivation beyond this other than keeping up to date
since we're already on non-release versions anyways.
2025-03-24 09:56:55 -07:00
Andrej Daskalov
13b94d995c added macedonian translation file 2025-03-23 14:41:07 +01:00
Jeffrey C. Ollie
c58fe676ad gtk: a couple more C cleanups (#6876) 2025-03-22 23:07:19 -05:00
Mitchell Hashimoto
68b8ba12c7 Update iTerm2 colorschemes (#6878)
Upstream revision:
8650079de4
2025-03-22 20:46:03 -07:00
mitchellh
8aab16b6e6 deps: Update iTerm2 color schemes 2025-03-23 00:13:47 +00:00
Mitchell Hashimoto
b722f537e7 apprt/gtk: make GL context current in unrealize (#6877)
Fixes #6872

This commit explicitly acquires the GL context in the `unrealize` signal
handler of the GTK Surface prior to cleaning up GPU resources.

A GLArea only guarantees that the associated GdkContext is current for
the `render` signal (see the docs[1]). This is why our OpenGL renderer
"defers" various operations such as resize, font grid changing, etc.
(see the `deferred_`-prefix fields in `renderer/OpenGL.zig`). However,
we missed a spot.

The `gtk-widget::unrealize` signal is emitted when the widget is
destroyed, and it is the last chance we have to clean up our GPU
resources. But it is not guaranteed that the GL context is current at
that point, and we weren't making it current. On the NGL GTK renderer,
this was freeing GPU resources we didn't own.

As best I can understand, the old GL renderer only ever used a handful
of GL resources that were early in the ID space, so by coincidence we
were probably freeing nothing and everything was fine. But with the new
NGL renderer uses a LOT more GL resources (make a few splits and the ID
space is already in the thousands, from GTK!), so we were freeing real
resources that we didn't own, which caused rendering issues. :)

I suspect the above also resulted in VRAM memory leaks (which would be
RAM memory leaks for unified memory GPUs). This potentially relates to
#5491.

The fix is to explicitly make the GL context current in the `unrealize`
handler.

[1]: https://docs.gtk.org/gtk4/method.GLArea.make_current.html
2025-03-22 14:48:51 -07:00
Mitchell Hashimoto
9d5ce6e47d apprt/gtk: remove gtk-gsk-renderer config
This was a hack, and is no longer required since #6877. Users can
explicitly override the GTK GSK renderer by setting the standard GTK env
var `GSK_RENDERER`.
2025-03-22 14:29:22 -07:00
Mitchell Hashimoto
36f841ee80 apprt/gtk: make GL context current in unrealize
Fixes #6872

This commit explicitly acquires the GL context in the `unrealize`
signal handler of the GTK Surface prior to cleaning up GPU resources.

A GLArea only guarantees that the associated GdkContext is current for
the `render` signal (see the docs[1]). This is why our OpenGL renderer
"defers" various operations such as resize, font grid changing, etc.
(see the `deferred_`-prefix fields in `renderer/OpenGL.zig`).
However, we missed a spot.

The `gtk-widget::unrealize` signal is emitted when the widget is
destroyed, and it is the last chance we have to clean up our GPU
resources. But it is not guaranteed that the GL context is current at
that point, and we weren't making it current. On the NGL GTK renderer,
this was freeing GPU resources we didn't own.

As best I can understand, the old GL renderer only ever used a handful
of GL resources that were early in the ID space, so by coincidence we
were probably freeing nothing and everything was fine. But with the new
NGL renderer uses a LOT more GL resources (make a few splits and the ID
space is already in the thousands, from GTK!), so we were freeing real
resources that we didn't own, which caused rendering issues. :)

I suspect the above also resulted in VRAM memory leaks (which would be
RAM memory leaks for unified memory GPUs). This potentially relates to
#5491.

The fix is to explicitly make the GL context current in the `unrealize`
handler.

[1]: https://docs.gtk.org/gtk4/method.GLArea.make_current.html
2025-03-22 14:20:01 -07:00
Jeffrey C. Ollie
1317e62722 gtk: a couple more C cleanups 2025-03-22 16:13:08 -05:00
Jon Parise
cd6b850758 shell-integration: minor documentation updates 2025-03-22 15:57:55 -04:00
Jon Parise
0caba3e19f shell-integration: comptime buffer capacity 2025-03-22 15:56:05 -04:00
Jon Parise
36ff70eb7f shell-integration: use elvish's native list type
Instead of looking for individual substrings in $GHOSTTY_SHELL_FEATURES,
`str:split` it into a list of feature names and use `has-value` to
detect their presence.
2025-03-22 12:26:56 -04:00
Jon Parise
77dc5c9dd2 shell-integration: use fish's native list type
Instead of looking for individual substrings in $GHOSTTY_SHELL_FEATURES,
`string split` it into a list of feature names and use `contains` to
detect their presence.
2025-03-22 12:11:51 -04:00
Jon Parise
314d52ac3a shell-integration: switch to $GHOSTTY_SHELL_FEATURES
This change consolidates all three opt-out shell integration environment
variables into a single opt-in $GHOSTTY_SHELL_FEATURES variable. Its
value is a comma-delimited list of the enabled shell feature names (e.g.
"cursor,title").

$GHOSTTY_SHELL_FEATURES is set at runtime and automatically added to the
shell environment. Its value is based on the shell-integration-features
configuration option.

$GHOSTTY_SHELL_FEATURES is only set when at least one shell feature is
enabled. It won't be set when 'shell-integration-features = false'.

$GHOSTTY_SHELL_FEATURES lists only the enabled shell feature names. We
could have alternatively gone in the opposite direction and listed the
disabled features, letting the scripts assume each feature is on by
default like we did before, but I think this explicit approach is a
little safer and easier to reason about / debug.

It also doesn't support the "no-" negation prefix used by the config
system (e.g. "cursor,no-title"). This simplifies the implementation
requirements of our (multiple) shell integration scripts, and because
$GHOSTTY_SHELL_FEATURES is derived from shell-integration-features,
the user-facing configuration interface retains that expressiveness.

$GHOSTTY_SHELL_FEATURES is intended to primarily be an internal concern:
an interface between the runtime and our shell integration scripts. It
could be used by people with particular use cases who want to manually
source those scripts, but that isn't the intended audience.

... and because the previous $GHOSTTY_SHELL_INTEGRATION_NO_* variables
were also meant to be an internal concern, this change does not include
backwards compatibility support for those names.

One last advantage of a using a single $GHOSTTY_SHELL_FEATURES variable
is that it can be easily forwarded to e.g. ssh sessions or other shell
environments.
2025-03-22 10:16:59 -04:00
Leah Amelia Chen
747c43ffa0 gtk: clean up C remnants and @ptrCasts (#6862) 2025-03-21 21:35:11 +01:00
Leah Amelia Chen
f659e70938 gtk: clean up C remnants and @ptrCasts
Some `@ptrCast`s are unavoidable in the codebase but I've gotten rid of
every one that's unnecessary.
2025-03-21 20:15:59 +01:00
Mitchell Hashimoto
4a51643043 Mention macOS' open in the CLI help messages (#6848)
> 3. If you want to live dangerously, open a pull request and hope for
the best.

Sure, why not!

---

This is a *super common* ask in both the GitHub Discussions and on
Discord; I thus decided to add a small(ish) note to the help output
directing users to try the open command. I did not include a note to
check the man page, as the text was already getting a bit long, but I
can change that if requested. Strings open for bike-shedding, of course.

Of course, feel free to close this if this is not a desirable change for
the project; I would appreciate a note about that though, rather than a
random unexpected close without any reason, as that would prevent any
future PRs about this from others.

As I do not use macOS, I was unable to test the appearance of the string
I edited in `main_ghostty.zig`.

On a slightly related note: are there any plans to translate the CLI's
strings? I assume they're in the same boat as the configuration parsing
errors which were [discussed in #maintainers] on [the Ghostty Discord].

[discussed in #maintainers]:
https://discord.com/channels/1005603569187160125/1337443701403815999/1352390511553417327
[the Ghostty Discord]: https://discord.org/ghostty
2025-03-21 07:21:27 -07:00
Kat
9a9bc43a9b Mention macOS' open in the CLI help messages. 2025-03-21 19:16:30 +11:00
Mitchell Hashimoto
1980f9aed4 font/freetype: disable SVG glyphs, simplify color check (#6824)
We don't currently support rendering SVG glyphs so they should be
ignored when loading. Additionally, the check for whether a glyph is
colored has been simplified by just checking the pixel mode of the
rendered bitmap.

This commit also fixes a bug caused by calling the color check inside of
`renderGlyph`, which caused the bitmap to be freed creating a chance for
memory corruption and garbled glyphs. This bug was introduced by 40c1140
(#6602) and discussed in #6781.
2025-03-20 11:47:02 -07:00
Mitchell Hashimoto
141b697f9d apprt/embedded: utf8 encoding buffer lifetime must extend beyond call (#6834)
Fixes #6821

UTF8 translation using KeymapDarwin requires a buffer and the buffer was
stack allocated in the coreKeyEvent call and returned from the function.
We need the buffer to live longer than this.

Long term, we're removing KeymapDarwin (there is a whole TODO comment in
there about how to do it), but this fixes a real problem today.
2025-03-19 21:47:13 -07:00
Mitchell Hashimoto
f31f8bb782 apprt/embedded: utf8 encoding buffer lifetime must extend beyond call
Fixes #6821

UTF8 translation using KeymapDarwin requires a buffer and the buffer was
stack allocated in the coreKeyEvent call and returned from the function.
We need the buffer to live longer than this.

Long term, we're removing KeymapDarwin (there is a whole TODO comment in
there about how to do it), but this fixes a real problem today.
2025-03-19 21:36:39 -07:00
Qwerasd
f0080529c4 fix(font/shape): don't require emoji presentation for grapheme parts
Also update shaper test that fails because the run iterator can't apply
that logic since `testWriteString` doesn't do proper grpaheme clustering
so the parts are actually split across multiple cells.

Several other tests are technically incorrect for the same reason but
still pass, so I've decided not to fix them here.
2025-03-19 15:09:53 -06:00
Mitchell Hashimoto
88ff566e06 ci: simplify debian 12 check (#6825)
Debian 12 CI check now relies entirely on a source tarball.
2025-03-19 13:18:41 -07:00
Mitchell Hashimoto
75045d92b4 Tweak Norwegian Bokmål translation (#6812)
This tweak is minor and fixes some grammatical errors.

I did not change `kopier` to `kopiér`, even though that is a common way
to write the word. The language council of Norway suggest writing the
word as it is written here, without the accent, but it does read weird
and allows for misunderstanding. If this was my project I would have
added the accent. Let me know if you want the accent added.

What do you think regarding the accents @Uzaaft ?
2025-03-19 13:18:05 -07:00
Mitchell Hashimoto
41130ce25f fix: inconsistent behavior from legacy and kitty Key encoding (#5728)
this fix addresses issue occurring in nvim/vim where Backspace deletes
previous letter while in preedit state.

related to #1638

> same issue reproducible
> However, that only fixed for legacy encoding.

Unanswered Discussion
https://github.com/ghostty-org/ghostty/discussions/5312<div
type='discussions-op-text'> can be closed afterwards

tested on macos sequioa IME '2-set Korean', 'Japanese Romaji'
2025-03-19 13:03:32 -07:00
Christoffer Tønnessen
9b3bd146c6 Tweak Norwegian Bokmål translation
This tweak is minor and fixes some grammatical errors.

I did not change `kopier` to `kopiér`, even though that is a common way
to write the word. The language council of Norway suggest writing the
word as it is written here, without the accent, but it does read weird
and allows for misunderstanding. If this was my project I would have
added the accent. Let me know if you want the accent added.
2025-03-19 20:46:00 +01:00
Jeffrey C. Ollie
a7a57011f0 ci: simplify debian 12 check 2025-03-19 14:44:31 -05:00
Serim Son
d61e53d6d6 Kitty key encoding should not encode backspace if UTF-8 text is present
This applies the same logic from #1659 to Kitty encoding.
2025-03-19 12:43:42 -07:00
Mitchell Hashimoto
9c064216a2 build: distribute gresource c/h with source tarball (#6822)
Closes #6760 
Supersedes #6762

This introduces the concept of a "dist resource" (specifically a
`GhosttyDist.Resource` type). This is a resource that may be present in
dist tarballs but not in the source tree. If the resource is present and
we're not in a Git checkout, then we use it directly instead of
generating it. This is a generic concept we can apply to any
preprocessing we want to do that we don't want users/packagers to do.

This is used for the first time in this commit for the gresource c/h
files, which depend on a variety of external tools (blueprint-compiler,
glib-compile-resources, etc.) that we do not want to require downstream
users/packagers to have and we also do not want to worry about them
having the right versions.

This also adds a check for `distcheck` to ensure our distribution
contains all the expected files.

Note @jcollie that there may be elements of 6762 you'll want to bring
back after this.
2025-03-19 12:10:08 -07:00
Mitchell Hashimoto
7b8c2232d3 build: distribute gresource c/h with source tarball
This introduces the concept of a "dist resource" (specifically a
`GhosttyDist.Resource` type). This is a resource that may be present in
dist tarballs but not in the source tree. If the resource is present and
we're not in a Git checkout, then we use it directly instead of
generating it.

This is used for the first time in this commit for the gresource c/h
files, which depend on a variety of external tools (blueprint-compiler,
glib-compile-resources, etc.) that we do not want to require downstream
users/packagers to have and we also do not want to worry about them
having the right versions.

This also adds a check for `distcheck` to ensure our distribution
contains all the expected files.
2025-03-19 11:52:03 -07:00
Qwerasd
6f84a5d682 font/freetype: disable SVG glyphs, simplify color check
We don't currently support rendering SVG glyphs so they should be
ignored when loading. Additionally, the check for whether a glyph is
colored has been simplified by just checking the pixel mode of the
rendered bitmap.

This commit also fixes a bug caused by calling the color check inside of
`renderGlyph`, which caused the bitmap to be freed creating a chance for
memory corruption and garbled glyphs.
2025-03-19 12:43:18 -06:00
Mitchell Hashimoto
bd315c8394 os: Add extra sentinel for GHOSTTY_RESOURCES_DIR (#6814)
Discover resourcesdir with `terminfo/g/ghostty`
as well as existing `terminfo/x/xterm-ghostty`.
This allows either terminfo file to be installed,
notably ncurses only provides a `terminfo/g/ghostty`.

It was brought up that the `ncurses-term` package on Fedora 42 at
<https://packages.fedoraproject.org/pkgs/ncurses/ncurses-term/fedora-42.html>
now provides a `/g/ghostty` terminfo entry which conflicts with
installing the similarly named file from ghostty's build process.
However a build with `zig build -Demit-terminfo=false` won't work as the
`x/xterm-ghostty` terminfo entry is used as a sentinel to discover the
`GHOSTTY_RESOURCES_DIR` used as a reference path for finding locale and
theme files.

```
src/Surface.zig|546 col 43| .resources_dir = global_state.resources_dir,
src/cli/list_themes.zig|112 col 22| if (global_state.resources_dir == null)
src/global.zig|38 col 5| resources_dir: ?[]const u8,
src/global.zig|173 col 14| self.resources_dir = try internal_os.resourcesDir(self.alloc);
src/global.zig|174 col 27| errdefer if (self.resources_dir) |dir| self.alloc.free(dir);
src/global.zig|177 col 18| if (self.resources_dir) |v| internal_os.i18n.init(v) catch |err| {
src/global.zig|185 col 18| if (self.resources_dir) |dir| self.alloc.free(dir);
```

We also have some comments that intend to change how the terminfo
database is discovered.

https://github.com/ghostty-org/ghostty/blob/main/src/termio/Exec.zig#L776C1-L781C60
2025-03-19 09:04:17 -07:00
Mitchell Hashimoto
403b3617f7 update translations 2025-03-19 08:54:30 -07:00
Mitchell Hashimoto
39d4cc3702 update CODEOWNERS 2025-03-19 08:52:39 -07:00
Danylo Zalizchuk
55c221c572 Merge branch 'main' into main 2025-03-19 08:52:14 -07:00
Danylo Zalizchuk
15efb913bf fix: removed words capitalization in the Ukrainian translations 2025-03-19 08:51:53 -07:00
Danylo Zalizchuk
f412237106 fix: update "Reloaded the configuration" translation 2025-03-19 08:51:53 -07:00
Danylo Zalizchuk
cb7180ef77 fix: reorder locales to ensure they follow ASCII ordering 2025-03-19 08:51:53 -07:00
Danylo Zalizchuk
e93be23f68 feat: add Ukrainian translations and locale support 2025-03-19 08:51:11 -07:00
Mitchell Hashimoto
bfec219510 Regenerate translations to fix CI (#6820)
I don't see any actual changes here, just reordering. It's using the Nix
environment so I'm not sure why this happened but it seemed to stem from
the Norwegian work originally. Fixing it back.
2025-03-19 08:39:00 -07:00
Mitchell Hashimoto
e56002e149 Regenerate translations.
I don't see any actual changes here, just reordering. It's using the Nix
environment so I'm not sure why this happened but it seemed to stem from
the Norwegian work originally. Fixing it back.
2025-03-19 08:35:39 -07:00
Leah Amelia Chen
907e62aa29 Fix typo: Alejanda → Alejandra in README.md (#6817) 2025-03-19 14:03:38 +01:00
CKay9
dc21ea9998 Fix typo: Alejanda → Alejandra in README.md 2025-03-19 13:38:38 +01:00
azhn
c5b1961c6b os: Add extra sentinel for GHOSTTY_RESOURCES_DIR
Discover resourcesdir with `terminfo/g/ghostty`
as well as existing `terminfo/x/xterm-ghostty`.
This allows either terminfo file to be installed,
notably ncurses only provides a `terminfo/g/ghostty`.
2025-03-19 20:49:02 +11:00
Mitchell Hashimoto
bd7c5cc95f Add Norwegian Bokmål Translations (#6731)
Pull request to add Norwegian Bokmål translations.
Asking assistance from @Uzaaft for review and help.
2025-03-18 16:04:41 -07:00
hanna
02bfa946d5 i18n: add norwegian bokmal translations 2025-03-18 15:44:46 -07:00
Mitchell Hashimoto
f7999444eb ci: zig fmt check (#6802)
This adds a CI test to ensure that all Zig files are properly formatted.
This avoids unrelated diff noise in future PRs.

This also runs `zig fmt` once to clean up all formatting issues for
future PRs.

I also introduced a new `xsm` (extra small) runner profile to use less
resources for our tiny tasks.
2025-03-18 14:39:34 -07:00
Jeffrey C. Ollie
07ec421cd3 CI: Add checks for blueprint compiler / Nix refactors (#6801)
1. Refactored Nix devshell/package to make it easier to keep
LD_LIBRARY_PATH & buildInputs in sync (plus make it easier to re-use in
other Nix environment).
2. Added a CI job to ensure that Blueprints are formatted correctly and
that they will compile using `blueprint-compiler` 0.16.0.
3. Reformatted all Blueprints with `blueprint-compiler format`.
2025-03-18 16:37:34 -05:00
Jeffrey C. Ollie
648e0a06ab CI: Add checks for blueprint compiler / Nix refactors
1. Refactored Nix devshell/package to make it easier to keep
   LD_LIBRARY_PATH & buildInputs in sync (plus make it easier to re-use
   in other Nix environment).
2. Added a CI job to ensure that Blueprints are formatted correctly and
   that they will compile using `blueprint-compiler` 0.16.0.
3. Reformatted all Blueprints with `blueprint-compiler format`.
2025-03-18 16:12:49 -05:00
Mitchell Hashimoto
4d0bf303c6 ci: zig fmt check
This adds a CI test to ensure that all Zig files are properly formatted.
This avoids unrelated diff noise in future PRs.
2025-03-18 13:58:49 -07:00
Mitchell Hashimoto
c0f5f913c9 zig build dist and distcheck for source tarballs (#6800)
This moves the source tarball creation process into the Zig build system
and follows the autotools-standard naming conventions of `dist` and
`distcheck`.

This doesn't change any of our build process otherwise. This is the
foundation for #6760 along with other source tarball tasks I have
planned (i.e. gobject bindings too).

The `dist` target creates a source tarball in the `PREFIX/dist`
directory. The tarball is named `ghostty-VERSION.tar.gz` as expected by
standard source tarball conventions.

The `distcheck` target does the same as `dist`, but also takes the
resulting tarball, extracts it, and runs tests on the extracted source
to verify the source tarball works as expected. Distcheck currently only
runs `zig build test` but in the future we can add additional checks to
run.

This commit also updates CI:

  1. Tagged releases now use the new `zig build distcheck` command.
  2. Tip releases now use the new `zig build dist` command.
3. A new test build tests that source tarball generation works on every
commit.
2025-03-18 13:21:24 -07:00
Mitchell Hashimoto
bab8c28c8b zig build dist and distcheck for source tarballs
This moves the source tarball creation process into the Zig build system
and follows the autotools-standard naming conventions of `dist` and
`distcheck`.

The `dist` target creates a source tarball in the `PREFIX/dist`
directory. The tarball is named `ghostty-VERSION.tar.gz` as expected by
standard source tarball conventions.

The `distcheck` target does the same as `dist`, but also takes the
resulting tarball, extracts it, and runs tests on the extracted source
to verify the source tarball works as expected.

This commit also updates CI:

  1. Tagged releases now use the new `zig build distcheck` command.
  2. Tip releases now use the new `zig build dist` command.
  3. A new test build tests that source tarball generation works on
     every commit.
2025-03-18 12:41:55 -07:00
Leah Amelia Chen
69590c80a1 gtk: unify gtk/adwaita version checks, use std.SemanticVersion in all cases (#6797) 2025-03-18 20:35:34 +01:00
Jeffrey C. Ollie
5bf10dce12 c804cd3dbb0274f3271736e0b8f279795bdff394 2025-03-18 14:14:50 -05:00
Jeffrey C. Ollie
0f2f0ab69f Update Adwaita version check for Box unref (#6796)
As of Adwaita 1.5.0, the GTK Box is not being properly unref'd when the
parent window is closed. Update the conditional to account for this.

Also add a couple of missing unref()s in errdefers.

This fixes an issue where Ghostty would not properly quit after closing
the last surface.
https://github.com/ghostty-org/ghostty/discussions/3807 is related
(though I'm not sure it's the exact same problem).
2025-03-18 10:42:00 -05:00
Gregory Anders
946c0c370f Update Adwaita version check for Box unref
As of Adwaita 1.5.0, the GTK Box is not being properly unref'd when the
parent window is closed. Update the conditional to account for this.

Also add a couple of missing unref()s in errdefers.
2025-03-18 10:24:42 -05:00
Jeffrey C. Ollie
ee78a3d345 gtk: remove c.zig (#6792)
It has been done.
2025-03-18 09:59:23 -05:00
Leah Amelia Chen
72017ea4d8 translations(zh_CN): update 2025-03-18 12:35:41 +01:00
Leah Amelia Chen
8c0ccfc5b3 translations: update 2025-03-18 12:35:41 +01:00
Leah Amelia Chen
a773588c99 gtk: remove c.zig
It has been done.
2025-03-18 12:35:41 +01:00
Leah Amelia Chen
73341b052b gtk: port ConfigErrorsWindow to dialogs 2025-03-18 12:35:41 +01:00
Leah Amelia Chen
1ee9c85954 gtk: port inspector & key handling to zig-gobject 2025-03-18 12:35:41 +01:00
Leah Amelia Chen
e3fbbe8fe3 ci(test/translations): ignore untranslated entries 2025-03-18 12:32:55 +01:00
Leah Amelia Chen
d75c5ec038 gtk: convert App to zig-gobject (#6787) 2025-03-18 09:14:19 +01:00
Jeffrey C. Ollie
ee95a5f3e0 gtk: convert App to zig-gobject 2025-03-17 23:39:45 -05:00
Leah Amelia Chen
742bca713d gtk: convert Window (and some related files) to zig-gobject (#6775) 2025-03-17 21:19:17 +01:00
Mitchell Hashimoto
899ab302e1 apprt/gtk: any preedit change should note a composing state (#6779)
Fixes #6772

When typing Korean with the fcitx5-hangful input method, moving between
graphemes does not trigger a preedit end/start cycle and instead just
clears the preexisting preedit and reuses the started state.

Every other input method we've tested up until now doesn't do this. We
need to mark composing set to "false" in "commit" because some input
methods on the contrary fail to ever call END.

What is the point of start/end events if they are just ignored depending
on the whim of the input method? Nothing. That's what. Its all a mess
that GTK should be protecting us from but it doesn't and now its the app
developer's problem. I'm frustrated because I feel like the point of an
app framework is to mask this kind of complexity from the app developer
and I'm playing whack-a-mole with input methods.

Well, here's another whack. Let's see if it works.
2025-03-17 11:59:33 -07:00
Mitchell Hashimoto
590eb60759 apprt/gtk: any preedit change should note a composing state
Fixes #6772

When typing Korean with the fcitx5-hangful input method, moving between
graphemes does not trigger a preedit end/start cycle and instead just
clears the preexisting preedit and reuses the started state.

Every other input method we've tested up until now doesn't do this. We
need to mark composing set to "false" in "commit" because some input
methods on the contrary fail to ever call END.

What is the point of start/end events if they are just ignored depending
on the whim of the input method? Nothing. That's what. Its all a mess
that GTK should be protecting us from but it doesn't and now its the app
developer's problem. I'm frustrated because I feel like the point of an
app framework is to mask this kind of complexity from the app developer
and I'm playing whack-a-mole with input methods.

Well, here's another whack. Let's see if it works.
2025-03-17 11:44:39 -07:00
Jeffrey C. Ollie
daa79c3598 gtk: address review comments
1. Remove usage of C header imports for gtk x11/wayland.
2. Move X11 C header imports to winproto_x11.zig
3. Clean up long line by breaking it up into multiple steps.
2025-03-17 12:35:31 -05:00
Jeffrey C. Ollie
29322535a5 gtk: convert Window (and some related files) to zig-gobject 2025-03-17 12:06:57 -05:00
Jeffrey C. Ollie
e0fe12cc05 Update Debian 12 Dockerfile (#6776)
1. Automatically detect the required Zig version rather than using a
hardcoded value.
2. Run `ghostty +version` after the build as a sanity check.
2025-03-17 11:09:47 -05:00
Jeffrey C. Ollie
1d040dd17d debian workflow: remove unused ZIG_VERSION arg 2025-03-17 10:54:44 -05:00
Jeffrey C. Ollie
7f7191dfec Update Debian 12 Dockerfile
1. Automatically detect the required Zig version rather than
using a hardcoded value.
2. Run `ghostty +version` after the build as a sanity check.
2025-03-17 10:41:17 -05:00
Jeffrey C. Ollie
a2df8e4b86 gtk: update Tab to use zig-gobject (#6729) 2025-03-17 10:39:13 -05:00
Mitchell Hashimoto
c344c320eb Update iTerm2 colorschemes (#6755)
Upstream revision:
e348884a00
2025-03-16 07:18:30 -07:00
mitchellh
291c2f541c deps: Update iTerm2 color schemes 2025-03-16 14:17:59 +00:00
Mitchell Hashimoto
f8590ce44f scroll: translate non-precision to precision (#6750)
Some wheel mice are capable of reporting fractional wheel ticks. These
mice don't necessarily report a corresponding precision scroll start
event, at least in Wayland + GTK. We can treat all discrete (ie
non-precision) events as the number of wheel ticks - for wheel mice,
yoff will be "1.0" per tick, while precision wheel mice may report
fractional values. This unifies handling of scroll events by normalizing
all events to "pixels to scroll".

We now report `mouse-scroll-multiplier` wheel or arrow events per wheel
tick (or per accumulated cell height). This means that applications
which subscribe to mouse button events will receive (by default) three
wheel events per wheel tick. For precision scrolls, they will receive
one wheel tick per line of scroll. In my opinion, this provides the best
user experience while also allowing customization of how much a
wheel tick should scroll

Reference: https://github.com/ghostty-org/ghostty/discussions/6677
2025-03-16 07:15:34 -07:00
Mitchell Hashimoto
d3424a922a update zon2nix (#6728)
Upstream is now mostly pure Zig and the build.zig.zon.* files are
generated directly by zon2nix. The JSON file is no longer used as an
intermediate file but is retained for downstream packager usage.
2025-03-16 07:13:24 -07:00
Jeffrey C. Ollie
5cd8ebdafd update zon2nix
Upstream is now mostly pure Zig and the build.zig.zon.* files are
generated directly by zon2nix. The JSON file is no longer used as an
intermediate file but is retained for downstream packager usage.
2025-03-16 01:09:52 -05:00
Jeffrey C. Ollie
3bc2b02303 build: update libvaxis and zf (#6752)
Fixes #6734
2025-03-15 23:42:49 -05:00
Jeffrey C. Ollie
ec4d110251 build: update libvaxis and zf
Fixes #6734
2025-03-15 22:06:18 -05:00
Tim Culverhouse
2018a8fd3c scroll: translate non-precision to precision
Some wheel mice are capable of reporting fractional wheel ticks. These
mice don't necessarily report a corresponding precision scroll start
event, at least in Wayland + GTK. We can treat all discrete (ie
non-precision) events as the number of wheel ticks - for wheel mice,
yoff will be "1.0" per tick, while precision wheel mice may report
fractional values. This unifies handling of scroll events by normalizing
all events to "pixels to scroll".

We now report `mouse-scroll-multiplier` wheel or arrow events per wheel
tick (or per accumulated cell height). This means that applications
which subscribe to mouse button events will receive (by default) three
wheel events per wheel tick. For precision scrolls, they will receive
one wheel tick per line of scroll. In my opinion, this provides the best
user experience while also allowing customization of how much a
wheel tick should scroll

Reference: https://github.com/ghostty-org/ghostty/discussions/6677
2025-03-15 21:35:39 -05:00
Jeffrey C. Ollie
4b1d1e0ed4 gtk: update Tab to use zig-gobject 2025-03-15 14:19:59 -05:00
Mitchell Hashimoto
644acdacdc termio, flatpak: implement process watcher with xev (#6658)
This allows `termio.Exec` to track processes spawned via
`FlatpakHostCommand`, finally allowing Ghostty to function as a Flatpak.

Alongside this is a few bug fixes:

* Don't add ghostty to PATH when running in flatpak mode since it's
unreachable.
* Correctly handle exit status returned by Flatpak. Previously this was
not processed and contains extra status bits.
* Use correct type for PID returned by Flatpak.
2025-03-15 08:09:54 -07:00
Mitchell Hashimoto
791d332a25 pkg/macos: clean up for Zig 0.14, consolidate C imports into one decl (#6736)
Fixes #6727

The major change in this commit is to consolidate all the C imports in a
single decl in main.zig. This is required for Zig 0.14. Without it, the
problem in #6727 will happen. I was never able to minimize why this
happens in order to open a Zig bug.

Beyond this, I fixed the build.zig and build.zig.zon to work with Zig
0.14 so that we can test building `pkg/macos` in isolation. There are no
downstream impacting changes in the build.zig files.
2025-03-15 07:30:05 -07:00
Leorize
009b53c45e termio, flatpak: implement process watcher with xev
This allows `termio.Exec` to track processes spawned via
`FlatpakHostCommand`, finally allowing Ghostty to function as a
Flatpak.

Alongside this is a few bug fixes:

* Don't add ghostty to PATH when running in flatpak mode since it's
  unreachable.
* Correctly handle exit status returned by Flatpak. Previously this was
  not processed and contains extra status bits.
* Use correct type for PID returned by Flatpak.
2025-03-15 07:29:13 -07:00
Mitchell Hashimoto
5ad8ea6b22 pkg/macos: clean up for Zig 0.14, consolidate C imports into one decl
Fixes #6727

The major change in this commit is to consolidate all the C imports in
a single decl in main.zig. This is required for Zig 0.14. Without it,
the problem in #6727 will happen. I was never able to minimize why this
happens in order to open a Zig bug.

Beyond this, I fixed the build.zig and build.zig.zon to work with Zig
0.14 so that we can test building `pkg/macos` in isolation. There are no
downstream impacting changes in the build.zig files.
2025-03-15 07:02:53 -07:00
Leah Amelia Chen
f8f9f7041a os: fix use of deprecated splitBackwards for Flatpak (#6733) 2025-03-15 08:02:41 +01:00
Leorize
2e6a2a148f os: fix use of deprecated splitBackwards for Flatpak 2025-03-14 23:48:59 -05:00
Mitchell Hashimoto
550edd4262 build: mark most dependencies as lazy (#6726)
Closes #6703 

Lazy dependencies are only fetched if the build script would actually
reach a usage of that dependency at runtime (when the `lazyDependency`
function is called). This can save a lot of network traffic, disk uage,
and time because we don't have to fetch and build dependencies that we
don't actually need.

Prior to this commit, Ghostty fetched almost everything for all
platforms and configurations all the time. This commit reverses that to
fetching almost nothing until it's actually needed.

There are very little downsides to doing this[1]. One downside is `zig
build --fetch` doesn't fetch lazy dependencies, but we don't rely on
this command for packaging and suggest using our custom shell script
that downloads a cached list of URLs (`build.zig.zon.txt`).

This commit doesn't cover 100% of dependencies, since some provide no
benefit to make lazy while the complexity to make them lazy is higher
(in code style typically).

Conversely, some simple dependencies are marked lazy even if they're
almost always needed if they don't introduce any real complexity to the
code, because there is very little downside to do so.

[1]: https://ziggit.dev/t/lazy-dependencies-best-dependencies/5509/5
2025-03-14 18:33:32 -07:00
Mitchell Hashimoto
cfea2ea12c build: mark most dependencies as lazy
Lazy dependencies are only fetched if the build script would actually
reach a usage of that dependency at runtime (when the `lazyDependency`
function is called). This can save a lot of network traffic, disk uage,
and time because we don't have to fetch and build dependencies that we
don't actually need.

Prior to this commit, Ghostty fetched almost everything for all
platforms and configurations all the time. This commit reverses that to
fetching almost nothing until it's actually needed.

There are very little downsides to doing this[1]. One downside is `zig
build --fetch` doesn't fetch lazy dependencies, but we don't rely on
this command for packaging and suggest using our custom shell script
that downloads a cached list of URLs (`build.zig.zon.txt`).

This commit doesn't cover 100% of dependencies, since some provide no
benefit to make lazy while the complexity to make them lazy is higher
(in code style typically).

Conversely, some simple dependencies are marked lazy even if they're
almost always needed if they don't introduce any real complexity to the
code, because there is very little downside to do so.

[1]: https://ziggit.dev/t/lazy-dependencies-best-dependencies/5509/5
2025-03-14 13:32:19 -07:00
Leah Amelia Chen
234b804872 contributing: fix link to Translator's Guide (#6712) 2025-03-14 17:29:10 +01:00
Jeffrey C. Ollie
f37d1fd7ed gtk: convert Surface to zig-gobject (#6634)
Marking this is as draft because I want to test this further before
saying that it's ready, but putting it out there for feedback.
2025-03-14 10:14:33 -05:00
Leah Amelia Chen
c2aac45848 fix: Use builtin source_env_if_exists for sourcing .envrc.local (#6717) 2025-03-14 13:33:37 +01:00
Uzair Aftab
b497400be6 fix: ignore .envrc.local 2025-03-14 13:15:29 +01:00
Uzair Aftab
ec5066988e fix: Use builtin source_env_if_exists for sourcing .envrc.local 2025-03-14 13:11:05 +01:00
Leah Amelia Chen
4ab3754a59 feat: source local .envrc if it exists (#6715) 2025-03-14 12:14:19 +01:00
Uzair Aftab
b9ea32b8ce Update .envrc
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-03-14 12:08:37 +01:00
Uzair Aftab
69dfc8870d fix: use bashism in .envrc
Co-authored-by: Leah Amelia Chen <github@acc.pluie.me>
2025-03-14 12:00:25 +01:00
Uzair Aftab
09d538b620 feat: source .envrc.local if it exists
Co-authored-by: Kat <65649991+00-kat@users.noreply.github.com>
2025-03-14 11:50:56 +01:00
Leah Amelia Chen
07b653bd71 contributing: link to po/README_CONTRIBUTORS.md 2025-03-14 08:46:06 +01:00
Leah Amelia Chen
e8101c1136 contributing: fix link to Translator's Guide
For some reason it pointed to the Contributor's Guide instead...
2025-03-14 08:44:04 +01:00
Mitchell Hashimoto
8eacde92e6 Replace mach-glfw with pkg/glfw (#6708)
Closes #6702

This removes our mach-glfw dependency and replaces it with an in-tree
pkg/glfw that includes both the source for compiling glfw as well as the
Zig bindings. This matches the pattern from our other packages.

This is based on the upstream mach-glfw work and therefore includes the
original license and copyright information.

The reasoning is stated in the issue but to summarize for the commit:

  - mach-glfw is no longer maintained, so we have to take ownership
- mach-glfw depended on some large blobs of header files to enable
cross-compilation but this isn't something we actually care about, so we
can (and do) drop the blobs
- mach-glfw blobs were hosted on mach hosts. given mach-glfw is
unmaintained, we can't rely on this hosting
- mach-glfw relied on a "glfw" package which was owned by another person
to be Zig 0.14 compatible, but we no longer need to rely on this
  - mach-glfw builds were outdated based on latest Zig practices
2025-03-13 21:18:41 -07:00
Mitchell Hashimoto
221f905a1c pkg/glfw
Closes #6702

This removes our mach-glfw dependency and replaces it with an in-tree
pkg/glfw that includes both the source for compiling glfw as well as the
Zig bindings. This matches the pattern from our other packages.

This is based on the upstream mach-glfw work and therefore includes the
original license and copyright information.

The reasoning is stated in the issue but to summarize for the commit:

  - mach-glfw is no longer maintained, so we have to take ownership
  - mach-glfw depended on some large blobs of header files to enable
    cross-compilation but this isn't something we actually care about,
    so we can (and do) drop the blobs
  - mach-glfw blobs were hosted on mach hosts. given mach-glfw is
    unmaintained, we can't rely on this hosting
  - mach-glfw relied on a "glfw" package which was owned by another
    person to be Zig 0.14 compatible, but we no longer need to rely on
    this
  - mach-glfw builds were outdated based on latest Zig practices
2025-03-13 20:52:33 -07:00
Mitchell Hashimoto
73c7943fff CODEOWNERS: add localization teams (#6704) 2025-03-13 10:19:29 -07:00
Mitchell Hashimoto
d8497d9b16 CODEOWNERS: add localization teams 2025-03-13 10:07:27 -07:00
Mitchell Hashimoto
ef0ff94c75 translations: add German translation (#6601)
This PR adds a translation for German `de_DE`.

Additionally it excludes all `*.po` files from the typos CI action.

Some comments on the decisions I made (open to discuss them):

- I choosed to use `du` instead of `Sie` as this seems appropriate
  to me.
- I added `Window` (`Fenster` in German) to all split commands
  as it appears more naturally to me.
2025-03-13 10:05:27 -07:00
Jeffrey C. Ollie
572fc8b5d7 gtk: convert Surface to zig-gobject 2025-03-13 12:04:10 -05:00
Mitchell Hashimoto
1f6b1d75eb Fix aspect ratio when rendering images with kitty protocol (#6675)
Fixes https://github.com/ghostty-org/ghostty/issues/6673

<img width="914" alt="image"
src="https://github.com/user-attachments/assets/010a1304-0d46-46ec-9a82-87a8d8fbea1b"
/>
2025-03-13 09:50:19 -07:00
Mitchell Hashimoto
aeada3f1a8 Zig 0.14 (#6699)
Closes #5744 

This gets Ghostty onto Zig 0.14. The goal of this PR is to focus only on
Zig 0.14 _compatibility_. I plan to open a number of subsequent issues
for future improvements I'd like to tackle, as noted in #5744.

I did run some basic benchmarks on a Zig 0.13 vs 0.14 build and didn't
notice any statistically significant changes. All our scrolling
benchmarks on vtebench got consistently 1 or 2ms faster but that may
just be noise. The good news is nothing got consistently slower (nothing
got slower at all on any runs!).

The Git history here is kind of nasty, I'm going to squash it.
2025-03-13 09:36:09 -07:00
Mitchell Hashimoto
f1f9db8b96 Update PACKAGING to note Zig 0.14 requirement 2025-03-13 09:18:34 -07:00
Mitchell Hashimoto
a542e63582 pkg/gtk4-layer-shell: disable ubsan 2025-03-13 09:14:37 -07:00
Mitchell Hashimoto
bdb66984b6 for iOS simulator builds for apple M1 as base CPU model 2025-03-13 07:13:13 -07:00
Mitchell Hashimoto
6613a695f0 nix 2025-03-12 16:30:22 -07:00
Mitchell Hashimoto
b96a5d702b fix mach-glfw on windows 2025-03-12 16:29:17 -07:00
Mitchell Hashimoto
66c83648c8 ci: debian 12 build should use zig 0.14 2025-03-12 16:29:17 -07:00
Mitchell Hashimoto
1dbeba7065 ci: update snap to Zig 0.14 2025-03-12 16:29:17 -07:00
Mitchell Hashimoto
fc21444f2d fix windows 2025-03-12 16:29:17 -07:00
Mitchell Hashimoto
907ed239a1 update typos 2025-03-12 16:29:17 -07:00
Mitchell Hashimoto
b123b14686 update zig2nix 2025-03-12 15:56:24 -07:00
Mitchell Hashimoto
99bde549af fix /usr/lib issues 2025-03-12 15:46:15 -07:00
Mitchell Hashimoto
1f6aa0e90d apprt/glfw: move darwin enabled const out to top-level 2025-03-12 12:53:15 -07:00
Mitchell Hashimoto
18084a3e61 update gobject, fix compiler errors 2025-03-12 12:32:50 -07:00
Mitchell Hashimoto
816ff8cef0 fix tests building on Linux 2025-03-12 11:29:13 -07:00
Mitchell Hashimoto
2e45a4c7a3 fix typos 2025-03-12 11:23:11 -07:00
Mitchell Hashimoto
3116a1b92c bundle ubsan rt 2025-03-12 11:07:15 -07:00
Mitchell Hashimoto
601acf4059 pkg/highway: upgrade to fix compilation issues on LLVM18 2025-03-12 11:03:54 -07:00
Mitchell Hashimoto
7e9be00924 working on macos 2025-03-12 10:15:14 -07:00
Mitchell Hashimoto
43467690f3 test 2025-03-12 10:04:17 -07:00
Mitchell Hashimoto
2408d4c6a9 more fixes 2025-03-12 09:59:24 -07:00
Mitchell Hashimoto
0f4d2bb237 Lots of 0.14 changes 2025-03-12 09:55:52 -07:00
Mitchell Hashimoto
86d3f18707 pkg/oniguruma: fix build 2025-03-12 09:10:17 -07:00
Bryan Lee
2f814b37e8 Add unit tests for kitty image aspect ratio calculation 2025-03-12 22:44:17 +08:00
Mitchell Hashimoto
bd848a27d2 update all packages to new hash for caching 2025-03-12 07:30:01 -07:00
Bryan Lee
f091a69790 Fix aspect ratio when rendering images with kitty protocol 2025-03-12 15:06:06 +08:00
Mitchell Hashimoto
2466de4556 pkg: update to new build.zig.zon format and hash values 2025-03-11 15:00:47 -07:00
Mitchell Hashimoto
251caeb22a Zig 0.14 fixes 2025-03-11 14:53:30 -07:00
Mitchell Hashimoto
3abbe6d3ba nix: must not inject xcrun into PATH on macOS 2025-03-11 14:49:01 -07:00
Mitchell Hashimoto
7e2286eb8c Zig 0.14 2025-03-11 14:39:04 -07:00
Leah Amelia Chen
95daca616d core: refactor RepeatablePath into separate files and add Path (#6622)
Slims down `Config.zig` and makes some of the code reusable in Path.
2025-03-10 09:14:25 +01:00
Leah Amelia Chen
14b66e93d1 pkg(gtk4-layer-shell): Enable using system-installed headers for dynamic linking (#6624)
I noticed we weren't doing system-integration against the pkgconfig for
gtk4-layer-shell. This behaviour differed from how we handled system
integration for existing deps in `pkg/` (oniguruma, fontconfig).

Refactored `pkg/gtk4-layer-shell/build.zig` referencing
`pkg/oniguruma/build.zig` to use pkgconfig names in system integration.
Previously we used to libname `libgtk4-layer-shell.so`
(`gtk4-layer-shell`) instead of pkgconfig name `gtk4-layer-shell-0.pc`
which meant system integration still relied on fetching the C-headers
via `zig fetch` instead of system C-headers.

I've tested this with a `--system` build where the relevant
`.zig-cache/p/<hash of gtk4-layer-shell>` is stubbed to an empty
directory and `pkgconfig(gtk4-layer-shell-0)` is installed instead on
fedora linux.
2025-03-10 09:11:42 +01:00
Mitchell Hashimoto
0ecee3ee92 Fix passing EnvMap for Flatpak builds (#6647)
When using -Dflatpak=true the EnvMap was passed as the incorrect type.
2025-03-09 18:39:54 -07:00
Mitchell Hashimoto
57d0a4d2e7 font(freetype): constrain emoji to cell width (#6602)
When scaling emoji (with freetype), we would unilaterally scale the
bitmap to fit within the `cell_height`. For narrow fonts, this would
result in a horizontal overflow:


![image](https://github.com/user-attachments/assets/87b9f952-6f12-40b2-bbed-5bfe948f45b4)

Modify the glyph rendering such that we scale to fit within the cell
width. After doing so, the above image looks like:


![image](https://github.com/user-attachments/assets/c75bfa51-4730-4179-b032-c3afa7840d65)

The emoji glyph is noticeably smaller because we have constrained the
height further than before, but fits perfectly within two cells. I am
using Victor Mono as my font, which is pretty narrow. The effect would
be even more pronounced on something like Iosevka.
2025-03-09 18:34:34 -07:00
Mitchell Hashimoto
480b1a9805 macOS: only set LANGUAGE for app bundle, do not inherit in termio env (#6648)
Fixes #6633

For macOS, we set LANGUAGE to the priority list of preferred languages
for the app bundle, using the GNU gettext priority list format (colon
separated list of language codes).

This previously was inherited by the termio env. At first, this was by
design, but this has inherent flaws. Namely, the priority list format is
a GNU gettext specific format, and programs that use alternate gettext
implementations (like musl or Python) do not understand it and actually
do the wrong thing (not their fault!).

This change removes the inheritance of LANGUAGE in the termio env. To
make it extra safe, we only do set and unset LANGUAGE when we know we
launch from an app bundle. That was always the desired behavior but this
makes it more explicit.
2025-03-09 17:08:55 -07:00
Mitchell Hashimoto
ebffe299ce macOS: only set LANGUAGE for app bundle, do not inherit in termio env
Fixes #6633

For macOS, we set LANGUAGE to the priority list of preferred languages
for the app bundle, using the GNU gettext priority list format (colon
separated list of language codes).

This previously was inherited by the termio env. At first, this was by
design, but this has inherent flaws. Namely, the priority list format is
a GNU gettext specific format, and programs that use alternate gettext
implementations (like musl or Python) do not understand it and actually
do the wrong thing (not their fault!).

This change removes the inheritance of LANGUAGE in the termio env. To
make it extra safe, we only do set and unset LANGUAGE when we know we
launch from an app bundle. That was always the desired behavior but this
makes it more explicit.
2025-03-09 18:17:38 -05:00
Yorick Peterse
300f4544ef Fix passing EnvMap for Flatpak builds
When using -Dflatpak=true the EnvMap was passed as the incorrect type.
2025-03-09 23:46:24 +01:00
Jeffrey C. Ollie
843cc83f42 gtk: implement quick-terminal-size (#6629)
Fixes #2384 on GTK

I'm not exactly sure how to deal with centered quick terminals so I
opted to make them similar to either top/bottom or left/right quick
terminals based on the monitor's orientation (portrait/landscape). This
may not be the right approach, so I'd like to hear more thoughts about
this.
2025-03-09 09:51:04 -05:00
Mitchell Hashimoto
78f16d040d macOS: disable setting LANGUAGE for now until bug is fixed
See: https://github.com/ghostty-org/ghostty/discussions/6633

This is temporary while we figure this out.
2025-03-09 07:25:55 -07:00
Jeffrey C. Ollie
6767493428 core: move RepeatablePath to separate file and enable Path as config type
Slim down Config.zig by moving RepeatablePath to a separate file and
enable the use of Path as it's own config type.
2025-03-09 09:18:01 -05:00
Jeffrey C. Ollie
bb3dad1309 core: all paths referenced from the CLI must be expanded 2025-03-09 09:17:57 -05:00
Mitchell Hashimoto
d3fd2b02e7 terminal: remove redundant assertIntegrity from clearPrompt (#6630)
clearCells() always asserts its page's integrity after finishing its
work (via a `defer`). We don't need to re-assert the page's integrity
immediately thereafter.
2025-03-08 14:37:23 -08:00
Mitchell Hashimoto
5efa2a6ca1 macOS: Set LANGUAGE env var based on macOS preferred language list (#6628)
Sets the LANGUAGE environment variable based on the preferred languages
as reported by NSLocale.

macOS has a concept of preferred languages separate from the system
locale. The set of preferred languages is a list in priority order of
what translations the user prefers. A user can have, for example,
"fr_FR" as their locale but "en" as their preferred language. This would
mean that they want to use French units, date formats, etc. but they
prefer English translations.

gettext uses the LANGUAGE environment variable to override only
translations and a priority order can be specified by separating the
languages with colons. For example, "en:fr" would mean that English
translations are preferred but if they are not available then French
translations should be used.

To further complicate things, Apple reports the languages in BCP-47
format which is not compatible with gettext's POSIX locale format so we
have to canonicalize them. To canonicalize the languages we use an
internal function from libintl. This isn't normally available but since
we compile from source on macOS we can use it. This isn't necessary for
other platforms.

This logic is only run if the user didn't explicitly request a specific
locale, so it should really only affect macOS app launches. From the CLI
the environment will have a locale unless the user really explicitly
clears it out.
2025-03-08 14:36:58 -08:00
Leah Amelia Chen
a0080ddad7 gtk: implement quick-terminal-size
Fixes #2384 on GTK

I'm not exactly sure how to deal with centered quick terminals so I opted
to make them similar to either top/bottom or left/right quick terminals
based on the monitor's orientation (portrait/landscape). This may not be
the right approach, so I'd like to hear more thoughts about this.
2025-03-08 22:36:24 +01:00
Jon Parise
b0b2de01f5 terminal: remove redundant assertIntegrity from clearPrompt
clearCells() always asserts its page's integrity after finishing its
work (via a `defer`). We don't need to re-assert the page's integrity
immediately thereafter.
2025-03-08 16:36:14 -05:00
Mitchell Hashimoto
b48fcf33f7 macOS: Set LANGUAGE env var based on macOS preferred language list
Sets the LANGUAGE environment variable based on the preferred languages
as reported by NSLocale.

macOS has a concept of preferred languages separate from the system
locale. The set of preferred languages is a list in priority order
of what translations the user prefers. A user can have, for example,
"fr_FR" as their locale but "en" as their preferred language. This would
mean that they want to use French units, date formats, etc. but they
prefer English translations.

gettext uses the LANGUAGE environment variable to override only
translations and a priority order can be specified by separating
the languages with colons. For example, "en:fr" would mean that
English translations are preferred but if they are not available
then French translations should be used.

To further complicate things, Apple reports the languages in BCP-47
format which is not compatible with gettext's POSIX locale format so
we have to canonicalize them. To canonicalize the languages we use
an internal function from libintl. This isn't normally available but
since we compile from source on macOS we can use it. This isn't
necessary for other platforms.
2025-03-08 12:54:39 -08:00
azhn
35aab1a302 build: use pkgconfig name for gtk4-layer-shell system integration
By linking using the pkg-config name we gain the compiler flags in pkgconf
for linking, specifically the -I <headers> to include system-installed
headers. This allows the gtk4-layer-shell pkg to not require the source
files specified in the `pkg/gtk4-layer-shell/build.zig.zon`.

pkg(gtk4-layer-shell): Refactor to allow dynamic linking

Refactored `pkg/gtk4-layer-shell/build.zig` to have similar structure
to `pkg/oniguruma/build.zig`.

Now dynamic link using pkgconfig, this adds pkgconfig compiler flags.
So we are now using system-installed headers to resolve @cInclude().
2025-03-09 02:46:33 +11:00
Robin Pfäffle
c67c7da582 translations(german): fix fuzzy translations 2025-03-08 09:24:54 +01:00
Robin Pfäffle
9d86bdfe72 translations: add de_DE to locales 2025-03-08 08:23:33 +01:00
Robin Pfäffle
abb97fa574 translations(german): update de_DE strings 2025-03-08 08:11:43 +01:00
Robin Pfäffle
7e268b9a43 ci: typos ignore *.po files 2025-03-08 08:11:43 +01:00
Robin Pfäffle
d2931b5d8f translations(german): address review comments 2025-03-08 08:11:41 +01:00
Robin Pfäffle
2ef11fb65f translations(german): add missing warning indicator 2025-03-08 08:08:51 +01:00
Robin Pfäffle
d511b3601d translations: add German translation 2025-03-08 08:08:51 +01:00
Mitchell Hashimoto
e03e98e106 Groundwork for cross-platform i18n with libintl for libghostty/macOS (#6619)
This builds on @pluiedev's excellent #6004.

## Background: The macOS (and libghostty consumer) Plan

Broadly, the decision I've come to is that for cross-platform
translations (i.e. strings shared across libghostty), we will be using
gettext and libghostty will export helper methods to call those (e.g.
`ghostty_translate` in this PR for singular forms). To be clear, **this
only applies to strings owned by libghostty**. For application-level
strings such as macOS-specific menu items and so on, we still have
choice but will likely using native features.

The reason for this is because converting gettext translations (`po`) to
native formats (Xcode String Catalog, `.strings`/`.stringsdict`) is
nightmare level, in particular for plural forms. I don't see a robust
path to doing it. And if we don't convert and don't use gettext, then
translators would have to maintain an identical translation in multiple
locations. To make matters worse, the macOS translation formats require
Apple-tooling for now unless you want to edit raw JSON.

Leveraging gettext lets us share translations across platforms and take
advantage of proven tech.

## PR Contents

**`pkg/libintl` builds and statically links libintl for macOS.** macOS
doesn't ship libintl with the system while Linux generally does with
libc, so we need to build this ourselves. This makes gettext available
to macOS. libintl is LGPL and we remain in compliance with that despite
static linking because our build process is fully open source, so
downstream consumers can modify our build scripts to replace it if they
wanted to.

~~**`src/os/locale.zig` now sets the `LANGUAGE` environment variable on
macOS based on the app's preferred languages.** macOS lets you configure
the system locale separate from preferred language. We previously relied
solely on `NSLocale.currentLocale`, but this only represents the system
locale. We now also look at `NSLocale.preferredLanguages` (a list in
priority order) and if we support a given language we set `LANGUAGE` so
gettext translates properly. Notably, the above lets us debug
translations in Xcode by setting alternate languages for debug builds
only.~~ Removed this for a future PR since it was problematic.

**`build.zig` unconditionally builds binary `mo` files** since they're
required for all apprts now.

**The macOS app bundles the translation strings.** This includes our
GTK-specific translation strings but the size of these is so small it
isn't worth the complexity of splitting up into multiple `pot`s at this
time, I think.

**i18n APIs moved to `src/os` from `src/apprt/gtk`.** Since these are
now cross-platform/cross-apprt, they're a core API. The only notable
change here is that `_` now maps to `dgettext` and explicitly specifies
our domain so that it's library-friendly. The GTK apprt calls
`initGlobalDomain` so that blueprint translations still work.

## Next Steps

This PR is all groundwork. The macOS app doesn't leverage any of this
yet, although I've verified it all works (e.g. calling the
`ghostty_translate` API from Swift).

For next steps, we need to have a use case for cross-platform
translations and the first one I was looking at was configuration error
messages and other core strings.
2025-03-07 14:51:12 -08:00
Mitchell Hashimoto
dcb8440b52 os: remove the preferredLanguages lookup 2025-03-07 13:43:00 -08:00
Mitchell Hashimoto
7eddf98269 Fix typos 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
da731e6caa typo i81n -> i18n 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
79a9ddf66f build: pure libghostty builds need to build translations 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
e8a988f6d3 os: i18n unsupported on windows 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
c7681e8fd7 apprt/gtk: use the new global i18n API 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
cff092f4c6 nix: update hashes 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
3ebd5b839f update translating readme 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
be839cb681 update our gitattributes with new generated files 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
3c49bc5086 os: locale automatically sets LANGUAGE based on macOS preferred 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
edf619205c add ghostty_translate C API 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
238573d42e i18n: export proper _ function 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
4cf127a064 build: i18n should emit mo on every platform 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
e8c20b5501 pkg/libintl: fix missing symbols 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
cb8085ab72 global state initializes i18n 2025-03-07 13:42:00 -08:00
Mitchell Hashimoto
dd95f727ec build: add libintl for macOS builds 2025-03-07 13:41:59 -08:00
Mitchell Hashimoto
67488754d5 pkg/libintl 2025-03-07 13:41:59 -08:00
Leah Amelia Chen
4a215a9518 gtk: use AdwAlertDialog for close dialogs, fix incorrect close dialogs (#5741)
AdwAlertDialog is the recommended way to do alert/message dialogs
starting from libadwaita 1.5, and is much easier to manage than
GtkMessageDialog. (The latter is also deprecated since GTK 4.10, but
this PR does not migrate it to use GtkAlertDialog, mostly because of its
obtuse interface and that we'll remove the GtkMessageDialog code anyway
in 1.2 when we remove non-Adwaita builds.)

We also had two bugs where tabs with only one split would display the
"close surface" confirmation dialog, and windows would do the same when
closed via the "Close Window" menu item or by the `close_window` keybind
action. (The "close window" dialog only appears when the user clicks on
the close button on the titlebar.) Initially I was very confused by
this, but it turns out that we don't have any apprt action related to
closing a window, and it was simply closing surfaces...
2025-03-07 20:46:23 +01:00
Leah Amelia Chen
b25da6b9c4 core: update zig2nix to use explicit Zig version from Nix (#6617)
This will avoid build breakage in the near future as Zig 0.14 is coming
to Nix.
2025-03-07 20:42:13 +01:00
Jeffrey C. Ollie
3ba4864f6c core: update zig2nix to use explicit Zig version from Nix
This will avoid build breakage in the near future as Zig 0.14 is coming
to Nix.
2025-03-07 11:46:30 -06:00
Leah Amelia Chen
77e16770cc gtk: build gtk4-layer-shell ourselves (#6614)
As of now `gtk4-layer-shell` is unavailable on recent, stable releases
of many distros (Debian 12, Ubuntu 24.04, openSUSE Leap & Tumbleweed,
etc.) and outdated on many others (Nixpkgs 24.11/unstable, Fedora 41,
etc.) This is inconvenient for our users and severely limits where the
quick terminal can be used. As a result we then build gtk4-layer-shell
ourselves by default unless `--system` or `-fsys=gtk4-layer-shell` are
specified. This also allows me to add an idiomatic Zig API on top of the
library and avoiding adding even more raw C code in the GTK apprt.

Since we now build gtk4-layer-shell it should be theoretically available
on all Linux systems we target. As such, the `-Dgtk-layer-shell` build
option has been removed. This is somewhat of an experimental change as I
don't know if gtk4-layer-shell works perfectly across all distros, and
we can always add the option back if need be.
2025-03-07 18:19:49 +01:00
Leah Amelia Chen
cd442eb9e2 gtk: build gtk4-layer-shell ourselves
As of now `gtk4-layer-shell` is unavailable on recent, stable releases
of many distros (Debian 12, Ubuntu 24.04, openSUSE Leap & Tumbleweed, etc.)
and outdated on many others (Nixpkgs 24.11/unstable, Fedora 41, etc.)
This is inconvenient for our users and severely limits where the quick
terminal can be used. As a result we then build gtk4-layer-shell ourselves
by default unless `--system` or `-fsys=gtk4-layer-shell` are specified.
This also allows me to add an idiomatic Zig API on top of the library
and avoiding adding even more raw C code in the GTK apprt.

Since we now build gtk4-layer-shell it should be theoretically available
on all Linux systems we target. As such, the `-Dgtk-layer-shell` build
option has been removed. This is somewhat of an experimental change as
I don't know if gtk4-layer-shell works perfectly across all distros, and
we can always add the option back if need be.
2025-03-07 17:52:06 +01:00
Leah Amelia Chen
6c00c36d62 config: make quick-terminal-autohide=false on Linux (#6613)
See diff for explanation
2025-03-07 17:36:05 +01:00
Leah Amelia Chen
9ed76729ab gtk: add separate close_window apprt action
For *some* reason we have a binding for close_window but it merely closes
the surface and not the entire window. That is not only misleading but
also just wrong. Now we make a separate apprt action for close_window
that would make it show a close confirmation prompt identical to as if
the user had clicked the (X) button on the window titlebar.
2025-03-06 20:32:38 +01:00
Leah Amelia Chen
b4bfdb2c44 translation: update template & zh_CN strings 2025-03-06 20:32:30 +01:00
Leah Amelia Chen
23d2d4ec70 gtk: use AdwAlertDialog for close dialogs 2025-03-06 20:32:30 +01:00
Tim Culverhouse
40c1140f7d font(freetype): constrain emoji to 2 cells wide
When scaling emoji, scale so that they entirely fit within 2 cells. The
previous behavior was to scale to fill vertically, however with fonts
which are narrow this would result in horizontal overflow.
2025-03-06 10:46:58 -06:00
Tim Culverhouse
27c4fd76f3 renderer(OpenGL): pass cell_width to glyph renderer
When adding a glyph, we didn't pass the expected width to the glyph
renderer. This can be helpful when scaling emoji, as will happen in the
next commit.
2025-03-06 09:59:24 -06:00
Tim Culverhouse
22ed08cfd8 chore: zig fmt 2025-03-06 09:59:24 -06:00
Leah Amelia Chen
260a90cbf0 config: make quick-terminal-autohide=false on Linux
See diff for explanation
2025-03-06 12:38:23 +01:00
Leah Amelia Chen
e07b6fdf6b gtk: implement quick terminal slide & autohide (#6090) 2025-03-05 23:20:03 +01:00
Leah Amelia Chen
44d4990eb2 gtk: implement quick-terminal-autohide 2025-03-05 21:51:35 +01:00
Leah Amelia Chen
58b0434092 docs: update information about quick terminal support on Linux 2025-03-05 21:37:49 +01:00
Jeffrey C. Ollie
d6bd7b56b3 gtk: implement sensitive content reveal on paste confirmation (#6054)
Fixes https://github.com/ghostty-org/ghostty/issues/4947 for gtk
This PR implements the senstive content hiding when displaying the paste
confirmation dialog in secure input mode.

Following changes are implemented:
- in the blueprint for each dialog add a show/hide button that is not
visible by default, and a Revealer that is revealed by default
- save the `secure_input` action value for each surface in the GTK apprt
- pass the value when initializing the paste confirmation dialog
- in the dialog code, alter the visibility of the content and
reveal/hide buttons based on secure input flag value

Demo:


https://github.com/user-attachments/assets/c91cbd3d-ed3b-464d-b4cf-e51fe7aa23b7

I feel like this is already a nearly full implementation, but I'm
leaving this as a draft for now, since i need to look into blueprints
for Adwaita 1.2, and verify if it behaves properly when the dialog is in
not-sensitive input mode and in OSC52 mode.
2025-03-05 14:27:13 -06:00
Leah Amelia Chen
8f7425f78c gtk: implement quick terminal slide animation
Yet another protocol that as far as I know only KWin implements.
Oh well, might as well let KDE users such as myself enjoy it OOTB
2025-03-05 21:13:13 +01:00
Maciej Bartczak
bd617c52e9 code review:
- implement blueprints for Adwaita 1.2
- use postifx notation for casting gtk widgets
- fix formatting
2025-03-05 21:03:02 +01:00
Maciej Bartczak
f71b294697 gtk: new approach to reveal/hide buttons 2025-03-05 21:03:02 +01:00
Maciej Bartczak
7123d4e055 gtk: blur the content view instead of using a Revealer widget 2025-03-05 21:03:02 +01:00
Maciej Bartczak
1f695c2646 gtk: implement sensitive content reveal mechanism when showing paste confirmation in secure input mode 2025-03-05 21:02:58 +01:00
Jeffrey C. Ollie
58adaffcb9 gtk: don't modify horizontal alignment on menus that have arrows (#6087)
Setting the horizontal alignment to start on popover menus that have
arrows results in visual anomalies:


![image](https://github.com/user-attachments/assets/fef279a3-73cf-4717-9b32-605ccd48c934)

From Discord:

https://discord.com/channels/1005603569187160125/1346819853612482571
2025-03-05 13:42:50 -06:00
Jeffrey C. Ollie
8f62901218 gtk: don't modify horizontal alignment on menus that have arrows 2025-03-05 13:28:57 -06:00
Leah Amelia Chen
2f65f01fc8 gtk: add localization support, take 3 (#6004)
This is my third (!) attempt at implementing localization support. By
leveraging GTK builder to do most of the `gettext` calls, I can avoid
the whole mess about missing symbols on non-glibc platforms.

Added some documentation too for contributors and translators, just for
good measure.

Supersedes #5214, resolves the GTK half of #2357
2025-03-05 20:12:52 +01:00
Mitchell Hashimoto
66e8d91957 Make equalize_splits action only affect current window (#6080)
Fixes #6064 


https://github.com/user-attachments/assets/bbf393be-de98-41eb-aaad-3a185705ed4c
2025-03-04 07:36:00 -08:00
Ken VanDine
fd6e4fd615 fix: Generate pixbuf loader cache on start if needed, fixes #6066 (#6079)
This fix ensures the correct pixbuf loaders are used, not mixing in
libraries from the host.
2025-03-04 09:38:23 -05:00
Bryan Lee
423bc1971b Make equalize_splits action only affect current window 2025-03-04 22:37:32 +08:00
Ken VanDine
2c6e6ad680 fix: Generate pixbuf loader cache on start if needed, fixes #6066 2025-03-04 08:50:11 -05:00
Leah Amelia Chen
6373399e59 os: deprioritize GHOSTTY_RESOURCES_DIR for debug builds
When one develops Ghostty while using Ghostty it could lead to an
interesting conundrum: the freshly built Ghostty would use the parent
Ghostty's resources, which would be stale and not reflect any new
changes to resources. This is especially bad for translators, since
their translations would not be reflected in the newly built Ghostty
if they happen to run it under older Ghostty, which is not only
counterintuitive and also painful in terms of workflow.

Now, on debug builds we always try to use the terminfo detection method
first in order to locate the zig-out/share/ghostty folder, and only fall
back to GHOSTTY_RESOURCES_DIR if the executable is for some reason no
longer in zig-out. You can test this behavior by manually moving the
Ghostty executable out of zig-out, and then launching it with and without
Ghostty.
2025-03-03 10:19:58 +01:00
Mitchell Hashimoto
6b1a017a86 build: some style changes, namely we should create steps only in root 2025-03-03 10:19:58 +01:00
Leah Amelia Chen
e252932bde translations: add basic Chinese translation 2025-03-03 10:19:58 +01:00
Leah Amelia Chen
9c97084ad0 gtk: extract translations from Zig source code 2025-03-03 10:19:58 +01:00
Leah Amelia Chen
5851bad4a0 ci: add check that ensures POT files are up to date 2025-03-03 10:19:58 +01:00
Leah Amelia Chen
9360afd29f gtk: add localization support, take 3
This is my third (!) attempt at implementing localization support.
By leveraging GTK builder to do most of the `gettext` calls, I
can avoid the whole mess about missing symbols on non-glibc platforms.

Added some documentation too for contributors and translators,
just for good measure.
2025-03-03 10:19:58 +01:00
Tim Culverhouse
ee8ae196ee input: legacy encoding never encodes text for command mods on macOS (#6057)
Fixes #5929
Replaces #5984

On macOS, native applications typically never encode any text for key
events that use the command key. This is because the command key is used
for key equivalents and "commands" and should not be used for text
input.

This can be verified with apps like TextEdit but also terminals like
Terminal.app officially but also iTerm2 unofficially. Anything such as
`Cmd+b` or `Cmd+Shift+b` will not produce any text input.

Cross-platform terminals generally don't follow this, for example Kitty
performs CSI-u encoding and Alacritty and WezTerm encode the text as-is
(i.e. `Cmd+b` will produce `b`).

On Linux, the super key (command-equivalent) does produce text input.
For example, `Super+b` will produce `b` in Gnome Console, Foot, and all
the cross-platform terminals mentioned above.

In the interest of matching the behavior of native macOS applications,
we should not encode text for command key events on macOS. We continue
to encode text for the super key on non-macOS platforms. This matches
the behaviors appropriately on each platform.
2025-03-02 16:21:02 -06:00
Mitchell Hashimoto
a646aee6bd CODEOWNERS: terminal team should own input encoding (#6058) 2025-03-02 13:56:37 -08:00
Mitchell Hashimoto
28e20f3015 CODEOWNERS: terminal team should own input encoding 2025-03-02 13:54:35 -08:00
Mitchell Hashimoto
f93eb0b27f input: legacy encoding never encodes text for command mods on macOS
Fixes #5929
Replaces #5984

On macOS, native applications typically never encode any text for
key events that use the command key. This is because the command key
is used for key equivalents and "commands" and should not be used
for text input.

This can be verified with apps like TextEdit but also terminals like
Terminal.app officially but also iTerm2 unofficially. Anything such as
`Cmd+b` or `Cmd+Shift+b` will not produce any text input.

Cross-platform terminals generally don't follow this, for example Kitty
performs CSI-u encoding and Alacritty and WezTerm encode the text as-is
(i.e. `Cmd+b` will produce `b`).

On Linux, the super key (command-equivalent) does produce text input.
For example, `Super+b` will produce `b` in Gnome Console, Foot, and
all the cross-platform terminals mentioned above.

In the interest of matching the behavior of native macOS applications,
we should not encode text for command key events on macOS. We continue
to encode text for the super key on non-macOS platforms.
2025-03-02 13:53:20 -08:00
Mitchell Hashimoto
82326508b1 macos: set title of terminal window immediately if configured (#6056)
Fixes #5934 for macOS

If a `title` config is set, this change sets the title immediately on
windowDidLoad to ensure that the window appears with the correct title
right away.

If there is any reason to set another title, the `set_title` apprt
action will come on another event loop tick (due to our usage of
notifications) but that's okay since that's already how it works. This
is just to say that setting this here won't break any shell integration
or anything.
2025-03-02 13:48:33 -08:00
Mitchell Hashimoto
8d395c094b macos: set title of terminal window immediately if configured
Fixes #5934 for macOS

If a `title` config is set, this change sets the title immediately on
windowDidLoad to ensure that the window appears with the correct title
right away.

If there is any reason to set another title, the `set_title` apprt
action will come on another event loop tick (due to our usage of
notifications) but that's okay since that's already how it works. This
is just to say that setting this here won't break any shell integration
or anything.
2025-03-02 13:27:40 -08:00
Mitchell Hashimoto
fc893ae7e3 core!: modify scroll behavior (#6052)
Modify the scroll behavior to better match other terminals, as well as
provide a
better overall experience. Before this PR, ghostty would scale
non-precision
scroll events dependent on the screen size. This is in line with kitty,
but no
other terminal. Ghostty also was the only terminal to send *more than
one* wheel
event.

```
 # 50% Screen height
| terminal   | arrows keys sent| wheels events sent|
|------------|-----------------|-------------------|
| alacritty  |        3        |          1        |
| foot       |        3        |          1        |
| xterm      |        5        |          1        |
| kitty      |        3        |          1        |
| ghostty    |        2        |          2        |

 # 100% Screen height
| terminal   | arrows keys sent| wheels events sent|
|------------|-----------------|-------------------|
| alacritty  |        3        |          1        |
| foot       |        3        |          1        |
| xterm      |        5        |          1        |
| kitty      |        5        |          1        |
| ghostty    |        3        |          3        |
```

This PR modifies Ghostty to behave like foot and alacritty.

For an improved user experience, we only use the configured multiplier
for
non-precision scrolls. This multiplier now *only applies* to viewport
scrolling
and alternate scroll mode. The default value has been updated to 3.0.

GTK also now supports precision scrolling.
2025-03-02 13:15:45 -08:00
Tim Culverhouse
30a49d0458 fixup! config: default mouse-scroll-multiplier to 3.0 2025-03-02 08:46:11 -06:00
Tim Culverhouse
68a2478317 gtk: enable non-discrete scrolling
Remove the flag which reports all scrolls as discrete scrolls. This
enables precision scrolling in GTK. We have to track a flag between
continuous scroll events.
2025-03-02 08:36:47 -06:00
Tim Culverhouse
c1e87e7122 scroll: only use multiplier for non-precision scrolls
Precision scrolls don't require a multiplier to behave nicely. However,
wheel scrolls feel extremely slow without one. We apply the multiplier
to wheel scrolls only
2025-03-02 08:35:25 -06:00
Tim Culverhouse
6e751d2d7e config: default mouse-scroll-multiplier to 3.0
Make Ghostty behave like other terminals by multiplying scrolls by 3.0.
This only affects when we are reporting arrow keys (alternate scroll
mode) or when we are scrolling the scrollback.
2025-03-02 08:03:09 -06:00
Tim Culverhouse
dbba3f1a60 scroll: don't use multiplier for wheel events
When we report mouse scroll wheel events, they should not be multiplied.
Refactor the scrollCallback to only use a multiplier for viewport or
alternate scroll reports.
2025-03-02 08:02:47 -06:00
Tim Culverhouse
34388ab5df surface: calculate scroll amount directly from yoff/xoff for non-precision scrolls
Calculate the scroll amount for non-precision scrolls as a direct
multiple of yoff. This fixes an issue where Ghostty sends scroll wheel
events (or arrow keys if in alternate scroll mode) that are variable,
dependent on the screen size. I checked multiple terminals, and each
responds to a single wheel click by sending only a single wheel / arrow
key - independent of screen size.

```sh
printf "\x1b[?1049h"
printf "\x1b[?1007h"

cat -v

```

Using the above procedure, with varying screen sizes:

```
 # 50% Screen height
| terminal   | arrows keys sent| wheels events sent|
|------------|-----------------|-------------------|
| alacritty  |        3        |          1        |
| foot       |        3        |          1        |
| xterm      |        5        |          1        |
| kitty      |        3        |          1        |
| ghostty    |        2        |          2        |

 # 100% Screen height
| terminal   | arrows keys sent| wheels events sent|
|------------|-----------------|-------------------|
| alacritty  |        3        |          1        |
| foot       |        3        |          1        |
| xterm      |        5        |          1        |
| kitty      |        5        |          1        |
| ghostty    |        3        |          3        |
```

Both ghostty and kitty scale the number of arrow keys sent in proportion
to the screen size. However, when mouse reporting is on, only ghostty
does this.

This commit makes Ghostty behave like foot, and more generally removes
the dependence on screen size.
2025-03-02 08:02:47 -06:00
Mitchell Hashimoto
8721f2ae51 Update iTerm2 colorschemes (#6047)
Upstream revision:
e21d5ffd19
2025-03-01 20:42:22 -08:00
mitchellh
29447b60b3 deps: Update iTerm2 color schemes 2025-03-02 00:13:13 +00:00
Mitchell Hashimoto
e2b5584a8d Add note to configuration that some settings might require a restart (#6033)
This adds a note in the default config to note that may require a
restart. Also adds a note with the window-padding-x and window-padding-y
to indicate a restart will be required to update existing windows.

I ran into this while updating one of the existing values in the default
config file. `window-padding-x` The value defaulted to 2 so figured it
was safe to assume and just uncomment it and try reloading the config.

Doing that doesn't work only restarting will make it take effect for the
main window ( or of course more tricky opening new windows and killing
off the old one )

https://github.com/ghostty-org/ghostty/discussions/6022
2025-03-01 13:57:25 -08:00
Aaron Ogle
e7a9d6a81d Update config template with a note about a restart possibly being required 2025-03-01 13:55:10 -08:00
Jeffrey C. Ollie
b342909e10 GTK: do not check for terminal area focus when setting window title (#6032)
Fixes https://github.com/ghostty-org/ghostty/issues/5940
The mentioned problem occurs because when creating a new tab through the
tab overview we do not have focus on the terminal area widget, it does
not matter if we have a custom title set or not.
I think it is just safe to remove this check from the code. I've tested
the change and I don't really see a valid use case in which we would not
want to set the window title even if we don't have focus on the terminal
area.
2025-03-01 12:10:13 -06:00
Leah Amelia Chen
df62d45b36 gtk: update URLWidget to use zig-gobject (#6042) 2025-03-01 18:40:27 +01:00
Jeffrey C. Ollie
5d5a632a89 gtk: update URLWidget to use zig-gobject
Also move URLWidget to a separate file to cut down on the size of
Surface.zig.
2025-03-01 10:02:16 -06:00
Jeffrey C. Ollie
ed647caa2e apprt/gtk: remove non-ascii characters from resize overlay (#6040)
It is possible that fonts people are using don't contain these
characters as evidenced by users in the Discord.
2025-03-01 08:54:31 -06:00
Maciej Bartczak
a3cd7c6f02 gtk: update the window title when grabbing tab focus 2025-03-01 13:25:25 +01:00
Tristan Partin
0e6c26bbfe apprt/gtk: remove non-ascii characters from resize overlay
It is possible that fonts people are using don't contain these
characters as evidenced by users in the Discord.

Signed-off-by: Tristan Partin <tristan@partin.io>
2025-03-01 00:37:01 -06:00
Mitchell Hashimoto
efc1b10bfd Introduce reset_window_size keybinding and apprt action (#6038)
Related to #6035

This implements the keybind/action portion of #5974 so that this can
have a binding and so that other apprts can respond to this and
implement it this way.
2025-02-28 19:02:10 -08:00
Mitchell Hashimoto
17cae57f51 Introduce reset_window_size keybinding and apprt action
Related to #6035

This implements the keybind/action portion of #5974 so that this can
have a binding and so that other apprts can respond to this and
implement it this way.
2025-02-28 15:31:17 -08:00
Mitchell Hashimoto
c6485b9fd5 "Return to Default Size" implementation (#5974)
## Added Support for "Return To Default Size"

This update introduces support for the **"Return To Default Size"**
feature.

### Fixes  
- Resolves [#1328](https://github.com/ghostty-org/ghostty/issues/1328)

### Screenshots  

| Description | Screenshot |
|------------|------------|
| **Ghostty** | <img width="1084" alt="Screenshot 2025-02-24 at 21 15
38"
src="https://github.com/user-attachments/assets/4657ccdb-9c7a-4884-873c-bbe0f30f9400"
/> |
| **After changing window size** | <img width="1155" alt="Screenshot
2025-02-24 at 21 16 00"
src="https://github.com/user-attachments/assets/9b3931f2-1c4b-4f86-8d56-8892bd5675cc"
/> |
| **Native Terminal App (for reference)** | <img width="630"
alt="Screenshot 2025-02-24 at 21 16 20"
src="https://github.com/user-attachments/assets/ae049931-b74d-4246-a9e7-d9be079b1a24"
/> |
2025-02-28 15:06:24 -08:00
Mitchell Hashimoto
afb154ee5d macos: store default size as computed property 2025-02-28 14:51:56 -08:00
Leah Amelia Chen
5accc069fb gtk: implement quick terminal (#6027) 2025-02-28 23:31:39 +01:00
Mikhail Borisov
8838ebf02a Refactor to use height/width from ghostty configuration 2025-02-28 14:17:46 -08:00
Mikhail Borisov
f73c1a2c59 "Return to Default Size" implementation
Added support for "Return To Default Size"
2025-02-28 14:17:46 -08:00
Mitchell Hashimoto
9681009650 apprt initial_size is sent whenever the grid size changes (#6034)
As noted in the comments, this is so that apprt's can always know what
the default size of a window would be so they can utilize this for
"return to default size" actions.

The initial size shouldn't be treated as a "resize" event and was
already documented as such. Prior to this commit the docs already noted
that the initial size may be sent multiple times but only the first time
during initialization should be used as a resize.

Therefore, this shouldn't impact prior behavior. I've verified this with
the apprts.
2025-02-28 10:43:55 -08:00
Mitchell Hashimoto
b0f1f19da0 apprt initial_size is sent whenever the grid size changes
As noted in the comments, this is so that apprt's can always know what
the default size of a window would be so they can utilize this for
"return to default size" actions.

The initial size shouldn't be treated as a "resize" event and was
already documented as such. Prior to this commit the docs already noted
that the initial size may be sent multiple times but only the first time
during initialization should be used as a resize.

Therefore, this shouldn't impact prior behavior. I've verified this with
the apprts.
2025-02-28 10:07:36 -08:00
Leah Amelia Chen
a85651fe4f gtk: implement quick terminal
Using `gtk4-layer-shell` still seems like the path of least resistance,
and to my delight it pretty much Just Works. Hurrah!

This implementation could do with some further polish (e.g. animations,
which can be implemented via libadwaita's animations API, and global
shortcuts), but as a MVP it works well enough.

It even supports tabs!

Fixes #4624.
2025-02-28 18:04:42 +01:00
Mitchell Hashimoto
1cfe7027e5 Fix Terminal Inspector option turns inactive if toggled in the Quick Terminal (#6024)
Fixed: [2475](https://github.com/ghostty-org/ghostty/issues/2475)

The problem actually existed because of the responder chain, as
previously pointed out in the report (thanks to @mitchellh).

When we first click on Toggle Terminal Inspector:
* the responder chain goes to _toggleTerminalInspector_
(_SurfaceView_AppKit_ implementation).
When we click the second toggleTerminalInspector:
* it tries to find the next responder, but the one available is
_TerminalController_. (if we remove this method from there, the bug will
reproduce even without quick mode)

**Problem**:
TerminalController not available during quick terminal, so there's no
way to toggle inspector
**Solution**:
We add toggleTerminalInspector to the _QuickTerminalController_:
selector, as we did with other similar methods.
2025-02-28 07:09:00 -08:00
Mikhail Borisov
744240c009 Fix Terminal Inspector option turns inactive if toggled in the Quick Terminal 2025-02-28 00:38:29 +01:00
Mitchell Hashimoto
ef88d1cba9 feat: respect maximize config on macOS (#5962)
Resolve #5928
2025-02-27 15:25:17 -08:00
Aaron Ruan
5a5478abe1 feat: respect maximize config on macOS
Signed-off-by: Aaron Ruan <i@ar212.com>
2025-02-27 15:10:39 -08:00
Qwerasd
a1437e5579 fix(Metal): force a full rebuild in setFontGrid (#6008)
This was causing garbled text due to a non-rebuilt rows referencing an
outdated atlas when the DPI changed but not the grid dimensions, which
could be caused by a variety of things such as the quick terminal
slide-in, dpi scaling changes on sleep/wake, moving windows between
displays because of closing/opening the laptop lid, etc.

Fixes #2731
2025-02-27 09:43:47 -05:00
Jeffrey C. Ollie
31df9d5576 gtk: work around oversized drag handle for GtkPaned (#6000)
Improves #3020.

Based on recommendation from upstream Gtk issue:
https://gitlab.gnome.org/GNOME/gtk/-/issues/4484#note_2362002

Without this, it's not possible to select the first character on the
right-hand side of a split.
2025-02-27 08:42:17 -06:00
Jeffrey C. Ollie
ef7f8cb3da gtk: use language-neutral arrows for resize overlays (#6013)
The meaning of "c" and "r" can be somewhat cryptic to non-native English
speakers as it may not be immediately obvious that "c" stands for
"columns", and "r" stands for "rows". I propose replacing them with
left-right and up-down double-headed arrows that convey the same
meaning, but in a truly language-neutral manner.

Related to #2357
2025-02-27 08:25:12 -06:00
David Wales
63ea1ab32e gtk: work around oversized drag handle for GtkPaned
Improves #3020.

Based on recommendation from upstream Gtk issue:
https://gitlab.gnome.org/GNOME/gtk/-/issues/4484#note_2362002

Without this, it's not possible to select the first character on the
right-hand side of a split.
2025-02-27 19:17:37 +11:00
Leah Amelia Chen
cdfa028521 gtk: use language-neutral arrows for resize overlays
The meaning of "c" and "r" can be somewhat cryptic to non-native English
speakers as it may not be immediately obvious that "c" stands for "columns",
and "r" stands for "rows". I propose replacing them with left-right and
up-down double-headed arrows that convey the same meaning, but in a
truly language-neutral manner.

Related to #2357
2025-02-27 08:38:06 +01:00
Jeffrey C. Ollie
c7938af7be gtk: convert Split.zig to gobject (#6012) 2025-02-26 22:38:51 -06:00
Jeffrey C. Ollie
78a98e01fc gtk: convert Split.zig to gobject 2025-02-26 19:22:02 -06:00
Jeffrey C. Ollie
d85ed8275e gtk: convert cgroup operations to gobject (#6009) 2025-02-26 18:28:53 -06:00
Jeffrey C. Ollie
6581b9cf41 gtk: convert cgroup operations to gobject 2025-02-26 16:26:44 -06:00
Leah Amelia Chen
12ba5d89f0 apprt/gtk: subscribe to AdwStyleManager::dark for ColorScheme (#6007) 2025-02-26 20:38:50 +01:00
Qwerasd
16a61c43dd fix(Metal): force a full rebuild in setFontGrid
This was causing garbled text due to a non-rebuilt rows referencing an
outdated atlas when the DPI changed but not the grid dimensions, which
could be caused by a variety of things such as the quick terminal
slide-in, dpi scaling changes on sleep/wake, moving windows between
displays because of closing/opening the laptop lid, etc.
2025-02-26 14:11:05 -05:00
Tristan Partin
acbb1d3bd4 apprt/gtk: subscribe to AdwStyleManager::dark for ColorScheme
Signed-off-by: Tristan Partin <tristan@partin.io>
2025-02-26 13:03:12 -06:00
Jeffrey C. Ollie
dec14f3096 gtk: switch dbus operations in src/apprt/gtk/App.zig to zig-gobject (#5996) 2025-02-26 11:17:47 -06:00
Jeffrey C. Ollie
5fdb732798 gtk: switch dbus operations in src/apprt/gtk/App.zig to zig-gobject 2025-02-25 22:52:57 -06:00
Leah Amelia Chen
4e5e4a7c2f gtk: switch clipboard confirmation to zig-gobject and blueprints (#5968) 2025-02-25 23:28:56 +01:00
Mitchell Hashimoto
c068390634 Fix elvish sudo integration and update documentation (#5992)
Elvish integration is broken when running `sudo`, because the function
`sudo-with-terminfo` uses `command` command, which is not implemented in
Elvish. Changing it to `external` command should fix possible error when
bypassing aliases, functions and builtins, like `command` does in Bash.
Discussion about this issue: #5979 

Also I updated documentation about Elvish integration to provide fix
when using `use ghostty-integration` outside of Ghostty with `rc.elv`.
2025-02-25 13:57:31 -08:00
Yappaholic
3cac06a70a Fix elvish sudo integration and update documentation 2025-02-25 23:17:00 +03:00
Jeffrey C. Ollie
62dcddb315 gtk: fix missing defer 2025-02-25 13:46:50 -06:00
Jeffrey C. Ollie
0638eca633 gtk: use versioned directories to store blueprint files 2025-02-25 13:30:44 -06:00
Jeffrey C. Ollie
c6b049b12b gtk: fix properties on close confirmation text view 2025-02-25 13:30:44 -06:00
Jeffrey C. Ollie
3f847de964 gtk: switch clipboard confirmation to zig-gobject and blueprints
Note that for Debian 12, the blueprints must be compiled on a distro
with a newer version of `blueprint-compiler` and the raw UI XML
committed to git. Debian 12 includes `blueprint-compiler` 0.6.0 which
doesn't support compiling `adw.MessageDialog` even though the version of
`libadwaita` supports it.
2025-02-25 13:30:44 -06:00
Mitchell Hashimoto
9972eeb673 Create a snap packaging subsystem (#5987)
This team is responsible for snap packaging.
2025-02-25 10:54:29 -08:00
Mitchell Hashimoto
166362d349 Create a snap packaging subsystem
This team is responsible for snap packaging.
2025-02-25 10:21:55 -08:00
Mitchell Hashimoto
0b7df7511a Fix empty keybind setting (#5977)
Fixes https://github.com/ghostty-org/ghostty/issues/5936.

Extracts the default keybind setting to an `init` function. Add logic to
call `init` in `parseIntoField` if it is defined for the type.
2025-02-25 09:06:11 -08:00
David Mo
df9de1523c fix test 2025-02-25 11:53:01 -05:00
Leah Amelia Chen
22f3e60dcf gtk: convert window actions to use zig-gobject (#5978) 2025-02-25 16:44:09 +01:00
David Mo
af2d710000 rename setToDefault to init 2025-02-25 10:15:58 -05:00
Jeffrey C. Ollie
3d08b1c4aa gtk: cast to application window 2025-02-25 08:19:52 -06:00
David Mo
22d99f2533 add test for setToDefault 2025-02-24 23:39:01 -05:00
David Mo
8fadb54e65 set default keybinds when parsing empty keybind config 2025-02-24 23:31:49 -05:00
David Mo
0321aec68f create default keybinds function 2025-02-24 23:27:49 -05:00
Jeffrey C. Ollie
d284146621 gtk: convert window actions to use zig-gobject 2025-02-24 22:07:16 -06:00
Mitchell Hashimoto
92340f8fb0 fix(macos): prevent performing newTab shortcut on QuickTerminalWindow… (#5955)
Fixes #5939
2025-02-24 15:32:39 -08:00
McNight
b4349d3226 fix(macos): make showNoNewTabAlert method private #5939 2025-02-25 00:18:02 +01:00
McNight
1254c6b981 fix(macos): address MR feedback #5939 2025-02-25 00:17:01 +01:00
Mitchell Hashimoto
ce8bfe45ed Docs change: Note instead of simple text and Removing two times showing info. (#5920)
In docs option reference, for macos-icon info. It is showing two times
similar thing. And Note looks good instead of just text because it wont
work without `custom-style`. So a Big Note is a good highlight.
2025-02-24 09:41:26 -08:00
Jeffrey C. Ollie
e1e1539e4f kitty: delete stray log line (#5969) 2025-02-24 11:30:22 -06:00
Jeffrey C. Ollie
9bcf554139 gtk: instruct users to install blueprint-compiler (#5970)
There's been *far* too many people who aren't aware of the new
dependency, and that is partly our fault: a "FileNotFound" error is
quite obtuse, unless you religiously follow every PR and every commit
made to the repository. Instead of shepherding everyone who runs into
this manually, we should offer better signposting.
2025-02-24 11:25:56 -06:00
Leah Amelia Chen
1dc375dd0e gtk: instruct users to install blueprint-compiler
There's been *far* too many people who aren't aware of the new dependency,
and that is partly our fault: a "FileNotFound" error is quite obtuse,
unless you religiously follow every PR and every commit made to the
repository. Instead of shepherding everyone who runs into this manually,
we should offer better signposting.
2025-02-24 18:10:18 +01:00
Jeffrey C. Ollie
f4f36a9a98 kitty: delete stray log line 2025-02-24 11:05:37 -06:00
Mitchell Hashimoto
71ae51b4b3 kitty images: add delete by range operations (#5957)
Fixes #5937

Implement [deleting Kitty image
ranges](https://sw.kovidgoyal.net/kitty/graphics-protocol/#deleting-images).
2025-02-24 07:14:11 -08:00
Jeffrey C. Ollie
61f41e5c01 nix: include libxml2 in nativeBuildInputs for xmllint (#5959) 2025-02-23 15:56:08 -06:00
Jeffrey C. Ollie
2ef042978d nix: include libxml2 in nativeBuildInputs for xmllint 2025-02-23 15:17:18 -06:00
Leah Amelia Chen
a52c603f16 gtk: ensure that the content scale is always positive (#5954) 2025-02-23 21:27:09 +01:00
Jeffrey C. Ollie
da10269d3f gtk: handle other nonsensical values returned by gtk_widget_get_scale_factor 2025-02-23 13:18:00 -06:00
Jeffrey C. Ollie
ac7029256a gtk: better document what to do if gtk-xft-dpi <= 0 2025-02-23 13:04:47 -06:00
Jeffrey C. Ollie
995959dce4 kitty images: add delete by range operations
Fixes #5937

Implement [deleting Kitty image ranges](https://sw.kovidgoyal.net/kitty/graphics-protocol/#deleting-images).
2025-02-23 12:57:24 -06:00
McNight
aa4aaa200f fix(macos): prevent performing newTab shortcut on QuickTerminalWindow #5939 2025-02-23 19:34:27 +01:00
Jeffrey C. Ollie
bc2acdd060 gtk: ensure that the content scale is always positive
Fixes #5927

This doesn't fix the underlying reason that GTK sometimes reports
content scales as negative. If GTK reports a negative scale, we ignore
that and use 1.0 for the scale.
2025-02-23 11:02:59 -06:00
Mitchell Hashimoto
2f63f840de terminal: increase CSI max params to 24 to accept Kakoune sequence (#5949)
See #5930

Kakoune sends a real SGR sequence with 17 parameters. Our previous max
was 16 so we threw away the entire sequence. This commit increases the
max rather than fundamentally addressing limitations.

Practically, it took us this long to witness a real world sequence that
exceeded our previous limit. We may need to revisit this in the future,
but this is an easy fix for now.

In the future, as the comment states in this diff, we should probably
look into a rare slow path where we heap allocate to accept up to some
larger size (but still would need a cap to avoid DoS). For now,
increasing to 24 slightly increases our memory usage but shouldn't
result in any real world issues.
2025-02-23 07:12:38 -08:00
Tristan Partin
eaeb6a620f gtk: switch menus to use blueprints instead of raw builder ui (#5944) 2025-02-22 23:30:56 -06:00
Tristan Partin
65c65b9c97 gtk: fix menu separator colors (again) (#5945) 2025-02-22 23:30:30 -06:00
Mitchell Hashimoto
dad2cf887b add macos default config path to manpages (#5942)
This should resolve #5938.

I tested this locally using `zig build -D=emit-docs=true` and confirmed
that the mdgen process provided the new manpages in
`zig-out/share/man/man*`, respectively.

Let me know if this needs any changes, I tried to keep this as similar
as possible to the existing manpages (both format and content).
2025-02-22 20:53:34 -08:00
Mitchell Hashimoto
22c506b03e terminal: increase CSI max params to 24 to accept Kakoune sequence
See #5930

Kakoune sends a real SGR sequence with 17 parameters. Our previous max
was 16 so we through away the entire sequence. This commit increases the
max rather than fundamentally addressing limitations.

Practically, it took us this long to witness a real world sequence that
exceeded our previous limit. We may need to revisit this in the future,
but this is an easy fix for now.

In the future, as the comment states in this diff, we should probably
look into a rare slow path where we heap allocate to accept up to some
larger size (but still would need a cap to avoid DoS). For now,
increasing to 24 slightly increases our memory usage but shouldn't
result in any real world issues.
2025-02-22 20:43:44 -08:00
Jeffrey C. Ollie
427da79a02 gtk: fix menu separator colors (again) 2025-02-22 20:23:16 -06:00
Jeffrey C. Ollie
a8b6b96fbd gtk: switch menus to use blueprints instead of raw builder ui 2025-02-22 20:21:41 -06:00
Tristan Partin
e7cbb7fd16 gtk: update ResizeOverlay for zig-gobject (#5941)
Also switch to a "DerivedConfig" model so that we aren't referring to a
global copy of the config.
2025-02-22 20:07:20 -06:00
Jeffrey C. Ollie
bdf0f27d1a gtk: fix the alignment of the context menu (#5943)
This aligns the top left of the context menu with the right-click
location, rather than the top center.
2025-02-22 18:37:41 -06:00
Jeffrey C. Ollie
0af256b57a gtk: fix the alignment of the context menu
This aligns the top left of the context menu with the right-click
location, rather than the top center.
2025-02-22 18:23:30 -06:00
taylrfnt
398add17f1 actually change it in both places 2025-02-22 18:00:37 -06:00
taylrfnt
eec150d4cd mention default loc precendence over XDG 2025-02-22 17:58:05 -06:00
taylrfnt
573fe7348b add macos default config path to manpages 2025-02-22 17:46:30 -06:00
Jeffrey C. Ollie
f1134640c5 gtk: update ResizeOverlay for zig-gobject
Also switch to a "DerivedConfig" model so that we aren't referring to a
global copy of the config.
2025-02-22 17:42:09 -06:00
Jeffrey C. Ollie
5131f8a71c GTK: propagate config updates to the GTK apprt surfaces (#5866)
This will be needed to the convert GTK apprt surfaces to a DerivedConfig
model rather than accessing the global config stored in the app. It's a
no-op for now, but I have a PR in the works to update the resize overlay
that will take advantage of this.
2025-02-22 17:19:13 -06:00
Jeffrey C. Ollie
867982a2ff Gtk: change title prompt (#5905)
This PR implements the title change functionality for the GTK app and
closes https://github.com/ghostty-org/ghostty/issues/5769

Demo:


https://github.com/user-attachments/assets/cad611b3-b7bf-40ac-8d0f-11d2095fe525

For now I came up with a basic UI that i believe is sufficient, but I'm
open to feedback and happy to iterate on it further.

https://github.com/ghostty-org/ghostty/issues/5769#issuecomment-2660341107
- Regarding Mitchell's comment I checked Gnome Console and I could not
find a similar feature.
2025-02-22 17:00:40 -06:00
Jeffrey C. Ollie
bde5b963d0 gtk: fix Builder api changes 2025-02-22 16:39:12 -06:00
Maciej Bartczak
5d80db2ef8 code review: fix log format 2025-02-22 16:39:12 -06:00
Jeffrey C. Ollie
32a62ff862 snap: add libxml2-utils (for xmllint) to snap 2025-02-22 16:33:22 -06:00
Jeffrey C. Ollie
d4bcac0150 snap: add blueprint-compiler to snap 2025-02-22 16:33:22 -06:00
Jeffrey C. Ollie
51dc1e2e8c gtk: fix typos 2025-02-22 16:33:22 -06:00
Jeffrey C. Ollie
4f3c4037aa gtk: get 'Change Title' working with older distros 2025-02-22 16:33:20 -06:00
Maciej Bartczak
7c19dd5a33 format the blueprint file using blueprint-compiler format 2025-02-22 16:32:52 -06:00
Maciej Bartczak
8758295647 code review:
- move responses definition to the blueprint, use translatable strings
- minor changes in the response callback
2025-02-22 16:32:52 -06:00
Maciej Bartczak
1ee8dfc99c code review:
- remove unnecessary @ptrCast
- set the default focus to the text entry field
2025-02-22 16:32:52 -06:00
Maciej Bartczak
cd287b4161 - remove the unused dialog context struct
- set the current title in the input buffer
- fix formatting
2025-02-22 16:32:50 -06:00
Maciej Bartczak
454a53b3f1 code review:
- remove the menu entry defined in code
2025-02-22 16:32:23 -06:00
Maciej Bartczak
6189f5d09e code review:
- use blueprint for the dialog content
- use zig-gobject bindings
- make the enum values lowercase
2025-02-22 16:31:32 -06:00
Maciej Bartczak
dcd17c6ac4 set the ok widget to be activated by default 2025-02-22 16:30:57 -06:00
Maciej Bartczak
3542778d84 free the terminal title when destroy is run 2025-02-22 16:30:57 -06:00
Maciej Bartczak
95fc5ad1e9 remove outdated comment 2025-02-22 16:30:57 -06:00
Maciej Bartczak
cc9c45de2a fix the edge case when user tries to revert the title to default and hasn't set a title before 2025-02-22 16:30:57 -06:00
Maciej Bartczak
5e9908af27 make the change of the title persistent & allow the user to restore to a default one 2025-02-22 16:30:56 -06:00
Maciej Bartczak
6b75ca40ca Implement a prompt that allows the user to set the title 2025-02-22 16:30:55 -06:00
Jeffrey C. Ollie
3f715c296a gtk: update menus to use popovers and builder ui files (#5781)
Menus (context menus and the window hamburger menu) now use popovers and
are defined using GTK builder UI files. This is a bit more "modern" and
reduces the amount of code to define menus.
2025-02-22 14:54:06 -06:00
Mitchell Hashimoto
e307f1a373 Allow whitespace in ColorList values (#5925)
The following formats are now all valid:

```zig
macos-icon-screen-color = #00FF00,#FF1000,#00FFFF
macos-icon-screen-color = #00FF00, #FF1000, #00FFFF
macos-icon-screen-color = #00FF00 ,#FF1000 ,#00FFFF
macos-icon-screen-color =  #00FF00 , #FF1000  , #00FFFF
```

Fixes #5918
2025-02-22 12:18:54 -08:00
Mitchell Hashimoto
726ac36612 Add support for whitespace in color and palette parsing (#5926)
Resolves #5921
2025-02-22 07:25:18 -08:00
Mitchell Hashimoto
ce62b5cc5e Clarify configuration of macos-icon-screen-color's gradient (#5923)
From #5863, cc @vollink.

I'm not sure what the hard-wrap limit for comments is (70?), so I've
tried to match the paragraph I've edited.
2025-02-22 07:13:08 -08:00
Bryan Lee
1b6b029e0d Add test cases for whitespace handling for ColorList 2025-02-22 22:11:35 +08:00
Bryan Lee
2383e4d90d Add support for whitespace in color and palette parsing 2025-02-22 22:05:05 +08:00
Bryan Lee
7c6375f744 Allow whitespace after commas in ColorList values 2025-02-22 20:53:27 +08:00
Kat
6770ad3736 Clarify configuration of macos-icon-screen-color's gradient. 2025-02-22 17:14:08 +11:00
Ronit Gandhi
a262da92bf using only note instead of both for docs. 2025-02-22 10:49:27 +05:30
Mitchell Hashimoto
870b74f4da macOS: Fix new window focus when created from quick terminal (#5834)
## Root Cause

The issue has two aspects:

1. The window creation process didn't explicitly force focus on the new
window after showing it.
2. More fundamentally, we were relying on `NSApp.isActive` to determine
whether to activate the application, which is problematic because:
- When creating a window from quick terminal, the application is already
"active" but this active state is owned by the quick terminal
- The [`NSApp.isActive`
check](4cfe5522db/macos/Sources/Features/Terminal/TerminalManager.swift (L100))
doesn't accurately reflect our intent - creating a new window is an
explicit user action that should always result in that window gaining
focus

## Solution

Removing the `NSApp.isActive` check.

```swift
// Before
if !NSApp.isActive {
    NSApp.activate(ignoringOtherApps: true)
}

// After
NSApp.activate(ignoringOtherApps: true)
```

Fixes #5688
2025-02-21 15:50:00 -08:00
Mitchell Hashimoto
c1fb9a33f7 Fix barely visible new tab button on macOS (#5897)
Resolve #5894 and #4288
2025-02-21 15:47:33 -08:00
Aaron Ruan
4291e1c5d7 fix: use surfaceConfig.backgroundColor to determine if the theme is light or dark
Signed-off-by: Aaron Ruan <i@ar212.com>
2025-02-21 15:32:24 -08:00
Mitchell Hashimoto
b5ecd7b6be Update libxev to use dynamic backend, support Linux configurability (#5916)
Related to #3224

Previously, Ghostty used a static API for async event handling: io_uring
on Linux, kqueue on macOS. This commit changes the backend to be dynamic
on Linux so that epoll will be used if io_uring isn't available, or if
the user explicitly chooses it.

This introduces a new config `async-backend` (default "auto") which can
be set by the user to change the async backend in use. This is a
best-effort setting: if the user requests io_uring but it isn't
available, Ghostty will fall back to something that is and that choice
is up to us.

Basic benchmarking both in libxev and Ghostty (vtebench) show no
noticeable performance differences introducing the dynamic API, nor
choosing epoll over io_uring.

For platforms that don't have multiple choices (currently macOS), the
dynamic API is literally the static API so there should be no
performance or behavioral changes whatsoever.
2025-02-21 15:18:59 -08:00
Mitchell Hashimoto
d532a6e260 Update libxev to use dynamic backend, support Linux configurability
Related to #3224

Previously, Ghostty used a static API for async event handling: io_uring
on Linux, kqueue on macOS. This commit changes the backend to be dynamic
on Linux so that epoll will be used if io_uring isn't available, or if
the user explicitly chooses it.

This introduces a new config `async-backend` (default "auto") which can
be set by the user to change the async backend in use. This is a
best-effort setting: if the user requests io_uring but it isn't
available, Ghostty will fall back to something that is and that choice
is up to us.

Basic benchmarking both in libxev and Ghostty (vtebench) show no
noticeable performance differences introducing the dynamic API, nor
choosing epoll over io_uring.
2025-02-21 15:04:37 -08:00
Jeffrey C. Ollie
2697061e5b gtk: fix comment in Window.updateConfig 2025-02-18 23:28:10 -06:00
Jeffrey C. Ollie
d1fa933006 gtk: forward config updates to GTK apprt surfaces 2025-02-18 23:18:47 -06:00
Jeffrey C. Ollie
2d5a07c795 gtk: fix build on debian 12 2025-02-18 17:10:54 -06:00
Jeffrey C. Ollie
b3f994a9d2 gtk: use builder ui files and popovers for menus 2025-02-18 17:10:51 -06:00
Jeffrey C. Ollie
38908e0126 gtk: apply all window appearance changes in syncAppearance (#5404)
The GTK side of appearance code is kind of a mess with several different
functions all having the responsibility of interacting with each other
and setting the appropriate window appearance. It should solely be the
responsibility of the `syncAppearance` function to apply appearance
changes, with other callbacks/functions calling it instead: much like
what we already do for the macOS apprt.

~~I also took the time to refactor the libadwaita version checks since
calling `versionAtLeast(0, 0, 0)` does get old after a while. Now almost
all checks are given human-readable names and contributors need not
memorize what the relevant version checks all are.~~ Moved to another PR
2025-02-18 16:36:07 -06:00
Leah Amelia Chen
8eaa901aec config: update reload ability information for several keys
Several keys are now able to affect existing windows (especially
window-decoration, whose config documentation got a greater overhaul)
2025-02-18 10:09:41 +01:00
Leah Amelia Chen
aa2dbe2919 gtk: apply all window appearance changes in syncAppearance
The GTK side of appearance code is kind of a mess with several different
functions all having the responsibility of interacting with each other
and setting the appropriate window appearance. It should solely be the
responsibility of the `syncAppearance` function to apply appearance
changes, with other callbacks/functions calling it instead: much like
what we already do for the macOS apprt.
2025-02-18 10:09:41 +01:00
Bryan Lee
c9f8732e5c Fix new window focus when quick terminal is open 2025-02-18 10:50:01 +08:00
Jeffrey C. Ollie
da32534e8a gtk: fix closing window when last tab is closed (#5837)
Causes windows to not close and leave behind a "corpse" if they are not
the last window or we are running in single instance mode.

![image](https://github.com/user-attachments/assets/5f6860c2-7807-4ff1-9cad-d32dd4bc348b)
2025-02-17 11:37:51 -06:00
Jeffrey C. Ollie
3dbbbdee0b gtk: fix closing window when last tab is closed 2025-02-17 11:15:16 -06:00
Mitchell Hashimoto
16c6903706 Vertically center title when macos-titlebar-style = tabs (#5777)
Fix #3868 
<img width="812" alt="Frame 14"
src="https://github.com/user-attachments/assets/1fe78a13-ed8f-46e5-b4d4-69ecefdbdc22"
/>
2025-02-17 07:44:22 -08:00
Mitchell Hashimoto
3253df3d54 Equalize Splits invalid keybind (#5646)
refer to #4007

there are also quite a few posts about this in the discord help section

Basically for some reason for the equal key shift is not a typical
modifier where it would be the original key + shift modifier but it
actually just changes equal to respond as the plus key this is the only
key on the keyboard I can see exhibit this behavior

it seems all 3 major operating systems report the key this way (mac,
linux, and windows)
2025-02-17 07:41:42 -08:00
Aaron Ruan
830a117555 fix: vertically center toolbar title more accurately
Signed-off-by: Aaron Ruan <i@ar212.com>
2025-02-17 07:30:14 -08:00
rhodes-b
768b0a79cb dont use shift+equal combo 2025-02-17 07:26:32 -08:00
Mitchell Hashimoto
429c8ab277 fix: [snap] Don't set GDK_PIXBUF_MODULE_FILE, it causes the icon loader (#5820)
This fixes loading the tab-new-symbolic icon in the snap package
2025-02-16 20:45:22 -08:00
Ken VanDine
76bd002aa4 fix: [snap] Don't set GDK_PIXBUF_MODULE_FILE, it causes the icon loader 2025-02-16 23:18:16 -05:00
Jeffrey C. Ollie
246f4baf7c gtk: rename notebook to TabView and switch to gobject (#5795) 2025-02-16 17:43:46 -06:00
Mitchell Hashimoto
1013ba63ee [macOS] feat: Add "Split Left" and "Split Up" actions to menubar (#5807)
Fixes #5779
2025-02-16 12:37:11 -08:00
mbrown379
b1df97b33f Add Split Left and Split Up to menu 2025-02-16 15:14:02 -05:00
Jeffrey C. Ollie
25b93ceb55 gtk: disable shortcuts in tab view 2025-02-16 13:56:15 -06:00
Jeffrey C. Ollie
497a1b6f8f gtk: prevent double free when closing window 2025-02-16 13:56:15 -06:00
Jeffrey C. Ollie
bf7e9603d2 gtk: rename notebook to TabView and switch to gobject 2025-02-16 13:56:15 -06:00
Mitchell Hashimoto
2e7ed98dfd build: fix colorscheme update (#5797) 2025-02-16 08:39:39 -08:00
Jeffrey C. Ollie
36e6ed3339 build: fix colorscheme update 2025-02-15 23:39:40 -06:00
Jeffrey C. Ollie
9a5bc65034 gtk: fix building on Debian 12 (#5791)
`std.debug.assert(x)` _is not_ the same as `if (!x) unreachable` because
the function call is not `inline`. Since it's not inline the Zig
compiler will try to compile any code that might otherwise be
unreachable.

Also, added a CI test that compiles Ghostty in a Debian 12 container to
ensure that regressions do not happen.
2025-02-15 18:31:39 -06:00
Mitchell Hashimoto
8ad2ae6ab4 Update iTerm2 colorschemes (#5793)
Upstream revision:
efb1bb1843
2025-02-15 16:26:58 -08:00
mitchellh
fe11efff63 deps: Update iTerm2 color schemes 2025-02-16 00:13:20 +00:00
Jeffrey C. Ollie
b0d68324a6 gtk: fix multiple build args in docker build 2025-02-15 18:11:42 -06:00
Jeffrey C. Ollie
fb35d10981 gtk: add Zig version as arg to Debian 12 build 2025-02-15 18:01:07 -06:00
Jeffrey C. Ollie
191b19f9a5 gtk: add debian build to list of required checks 2025-02-15 17:58:25 -06:00
Jeffrey C. Ollie
c7b3cbd397 gtk: only test Debian 12 builds on amd64 2025-02-15 17:57:19 -06:00
Jeffrey C. Ollie
0ce1342263 gtk: fix building on Debian 12
`std.debug.assert(x)` _is not_ the same as `if (!x) unreachable`
because the function call is not `inline`. Since it's not inline the
Zig compiler will try to compile any code that might otherwise be
unreachable.

Also, added a CI test that compiles Ghostty in a Debian 12 container to
ensure that regressions do not happen.
2025-02-15 16:53:53 -06:00
Mitchell Hashimoto
6d8db4b380 [macOS] feat: Add setting to hide icon from dock/cmd-tab (#5122)
Resolves #4538 

Adds boolean configuration option `macos-hidden` which toggles the
NSApp's activation policy appropriately on config change.
2025-02-15 11:00:32 -08:00
Albert Dong
d7a82f212a Add setting to hide icon from dock/cmd-tab 2025-02-15 10:45:27 -08:00
Mitchell Hashimoto
aeccbd266a Added snap packaging (#3931)
Added snap packaging, fixes #3153

If whoever registered the name in the snap store could add me as a
collaborator, I can handle getting it released in the store, setup
automated builds, and request the necessary classic permissions in the
store.
2025-02-15 09:24:36 -08:00
Thom Dickson
ac9f8ba9b1 wip: allow directional split movement 2025-02-15 10:14:21 -06:00
Mitchell Hashimoto
baa47ff24e ci: test requires build-snap 2025-02-15 07:24:25 -08:00
Mitchell Hashimoto
818bc779b3 apprt/gtk: unset snap env vars 2025-02-15 07:22:21 -08:00
Mitchell Hashimoto
88a6b542b3 ci: move snap testing into our big test workflow 2025-02-15 07:20:55 -08:00
Mitchell Hashimoto
494273cf08 ci: snap workflow requires git history 2025-02-15 07:10:31 -08:00
Mitchell Hashimoto
03d1240999 nix: use snapcraft only on Linux 2025-02-15 07:07:23 -08:00
Ken VanDine
b551e106a8 Comment out refresh-mode, the store rejects this. Needs fixing in
review-tools
2025-02-15 07:06:40 -08:00
Ken VanDine
0c3b873dde Merge remote-tracking branch 'origin/add_snap_package' into add_snap_package 2025-02-15 07:06:40 -08:00
Ken VanDine
d3623393a6 More environment handling to ensure reliability across distros 2025-02-15 07:06:40 -08:00
Ken VanDine
2adee4290a Improved rpath handling for ghostty 2025-02-15 07:06:40 -08:00
Ken VanDine
94e2982d4b Allow snap to refresh while running 2025-02-15 07:06:40 -08:00
Ken VanDine
238b0faf5c Simplified setting snap version 2025-02-15 07:06:40 -08:00
Ken VanDine
927f626d9a Merge remote-tracking branch 'upstream/main' into add_snap_package 2025-02-15 07:06:40 -08:00
Ken VanDine
bd6a133e95 Updated stage packages 2025-02-15 07:06:40 -08:00
Ken VanDine
1c41cf236f Merge branch 'ghostty-org:main' into add_snap_package 2025-02-15 07:06:40 -08:00
Ken VanDine
a831df903d Merge branch 'ghostty-org:main' into add_snap_package 2025-02-15 07:06:40 -08:00
Ken VanDine
ff5c1001c6 Per PR review feedback, this is the more "ziggy" way of doing the check for environment variable. 2025-02-15 07:06:40 -08:00
Ken VanDine
e4cf81c2ba Clean up environment variable while launching the shell 2025-02-15 07:06:40 -08:00
Ken VanDine
cb5379ab1d Unset environment varies set by the snap 2025-02-15 07:06:40 -08:00
Ken VanDine
7e5c57a848 Only export XDG_CONFIG_HOME and XDG_DATA_HOME if they aren't already set 2025-02-15 07:06:40 -08:00
Ken VanDine
5841a4f958 Stage libglib2.0-0t64 to insure we don't mix in the host's lib 2025-02-15 07:06:40 -08:00
Ken VanDine
725488e1a2 Improved environment handling to ensure the snap will work across
distros and unset all SNAP environment variables that could leak at
runtime
2025-02-15 07:06:40 -08:00
Ken VanDine
0acf82bb9c Use patch-rpath which improves our cross distro support 2025-02-15 07:06:40 -08:00
Mitchell Hashimoto
9944fd5958 ci: temporary apt installs required for namespace 2025-02-15 07:06:40 -08:00
Ken VanDine
e7d4daa7c1 Removed duplicated stage-packages 2025-02-15 07:06:40 -08:00
Ken VanDine
5de0e775cb Don't stage shells 2025-02-15 07:06:40 -08:00
Ken VanDine
301fdff58f enable-patchelf is more repliable for classic snaps 2025-02-15 07:06:40 -08:00
Ken VanDine
99c7abb43a Set GHOSTTY_RESOURCES_DIR 2025-02-15 07:06:40 -08:00
Ken VanDine
a85de40710 Exit with error if building for unsupported arch 2025-02-15 07:06:40 -08:00
Ken VanDine
e174fb2748 no-patchelf for DRI and tidy up the mesa bits 2025-02-15 07:06:40 -08:00
Ken VanDine
403eab2cf0 Stage gnome-text-editor to open configuration, this makes it more
reliable across more distros as a classic snap.
2025-02-15 07:06:40 -08:00
Ken VanDine
bdafc2227c Drop patchelf 2025-02-15 07:06:40 -08:00
Ken VanDine
c9cafd3051 Enable patch-elf for libs part 2025-02-15 07:06:40 -08:00
Ken VanDine
48f94e6fcc Stage more depends to ensure we aren't getting leaks from the host 2025-02-15 07:06:40 -08:00
Ken VanDine
43b2e43a11 EGL fixes, ensure necessary env variables are set to isolate
dependencies from the host
2025-02-15 07:06:40 -08:00
Ken VanDine
8dffe3450c CRAFT_TARGET_ARCH is deprecated, use CRAFT_ARCH_BUILD_FOR 2025-02-15 07:06:40 -08:00
Ken VanDine
ae953b5f10 Ensure LD_LIBRARY_PATH is set appropriately 2025-02-15 07:06:40 -08:00
Mitchell Hashimoto
c7635201ab Add snap to nix, add arm64 builders 2025-02-15 07:06:40 -08:00
Ken VanDine
c35ca1e87f Set a more meaningful version for the snap 2025-02-15 07:06:40 -08:00
Ken VanDine
d06d6796c5 Changed shebang in launcher script 2025-02-15 07:06:40 -08:00
Ken VanDine
e6c9dc7040 Only run snap workflow on push and PR 2025-02-15 07:06:40 -08:00
Ken VanDine
5d0dde57f9 Don't stage shells 2025-02-15 07:06:40 -08:00
Ken VanDine
d0108416d0 enable-patchelf is more repliable for classic snaps 2025-02-15 07:06:40 -08:00
Ken VanDine
71297870cf Set GHOSTTY_RESOURCES_DIR 2025-02-15 07:06:40 -08:00
Ken VanDine
fcde494440 Install bash-completion 2025-02-15 07:06:40 -08:00
Ken VanDine
b7bd8444c7 Exit with error if building for unsupported arch 2025-02-15 07:06:40 -08:00
Ken VanDine
2b2b3c5b3b Set source-type for launcher dir 2025-02-15 07:06:40 -08:00
Ken VanDine
818c81282b Added snap build workflow 2025-02-15 07:06:40 -08:00
Ken VanDine
f0842c5599 Added snap packaging 2025-02-15 07:06:40 -08:00
Jeffrey C. Ollie
2d0940f6ae gtk: require libadwaita (#5749)
This commit removes support for building without libadwaita. (Y'all knew
that I just had this sitting in my back pocket). This will need some
serious review to ensure that we haven't lost any functionality.
2025-02-15 09:04:11 -06:00
Tim Culverhouse
f1f1120749 termio: use modified backend (#5776)
In Termio.init, we make a copy of backend and modify it by calling
initTerminal. However, we used the original in the struct definition.
This lead to the pty being opened with a size 0,0.
2025-02-14 22:57:50 -06:00
Mitchell Hashimoto
c1ff382e97 core: add env config option (#5309)
Fixes #5257

Specify environment variables to pass to commands launched in a terminal
surface. The format is `env=KEY=VALUE`.

`env = foo=bar`
`env = bar=baz`

Setting `env` to an empty string will reset the entire map to default
(empty).

`env =`

Setting a key to an empty string will remove that particular key and
corresponding value from the map.

`env = foo=bar`
`env = foo=`

will result in `foo` not being passed to the launched commands. Setting
a key multiple times will overwrite previous entries.

`env = foo=bar`
`env = foo=baz`

will result in `foo=baz` being passed to the launched commands.

These environment variables _will not_ be passed to commands run by
Ghostty for other purposes, like `open` or `xdg-open` used to open URLs
in your browser.
2025-02-14 20:55:51 -08:00
Tim Culverhouse
29f25ae474 termio: prevent responses to non-query OSC 21 sequences (#5770)
The Ghostty implementation of OSC 21 (Kitty color protocol) currently
responds to *all* OSC 21 sequences. It should not respond to a set, nor
a reset command. Fix the implementation so that we only respond if a
query was received.
2025-02-14 22:50:03 -06:00
Jeffrey C. Ollie
c7971b562e core: add env config option
Fixes #5257

Specify environment variables to pass to commands launched in a terminal
surface. The format is `env=KEY=VALUE`.

`env = foo=bar`
`env = bar=baz`

Setting `env` to an empty string will reset the entire map to default
(empty).

`env =`

Setting a key to an empty string will remove that particular key and
corresponding value from the map.

`env = foo=bar`
`env = foo=`

will result in `foo` not being passed to the launched commands.
Setting a key multiple times will overwrite previous entries.

`env = foo=bar`
`env = foo=baz`

will result in `foo=baz` being passed to the launched commands.

These environment variables _will not_ be passed to commands run by Ghostty
for other purposes, like `open` or `xdg-open` used to open URLs in your
browser.
2025-02-14 20:50:01 -08:00
Tim Culverhouse
b7009202ce termio: use modified backend
In Termio.init, we make a copy of backend and modify it by calling
initTerminal. However, we used the original in the struct definition.
This lead to the pty being opened with a size 0,0.
2025-02-14 22:44:27 -06:00
Jeffrey C. Ollie
25c5ecf553 gtk: require libadwaita
This commit removes support for building without libadwaita.
2025-02-14 21:49:51 -06:00
Tim Culverhouse
09fbf096d3 termio: prevent responses to non-query OSC 21 sequences
The Ghostty implementation of OSC 21 (Kitty color protocol) currently
responds to *all* OSC 21 sequences. It should not respond to a set, nor
a reset command. Fix the implementation so that we only respond if a
query was received.
2025-02-14 18:55:26 -06:00
Mitchell Hashimoto
b975f1e860 cli: disable +boo on non-desktop platforms due to lack of tty 2025-02-14 15:14:05 -08:00
Mitchell Hashimoto
8c4b0f815d prettier 2025-02-14 14:54:59 -08:00
Mitchell Hashimoto
4e8e2d9796 nix: snapcraft should only be installed on Linux 2025-02-14 14:52:36 -08:00
Ken VanDine
90ce5b75f1 Simplified setting snap version 2025-02-14 14:52:08 -08:00
Ken VanDine
fd9cbde3d8 Merge remote-tracking branch 'upstream/main' into add_snap_package 2025-02-14 14:52:08 -08:00
Ken VanDine
b0edda4b69 Updated stage packages 2025-02-14 14:52:08 -08:00
Ken VanDine
bbd279bb4f Merge branch 'ghostty-org:main' into add_snap_package 2025-02-14 14:52:08 -08:00
Ken VanDine
bdbf30dc96 Merge branch 'ghostty-org:main' into add_snap_package 2025-02-14 14:52:08 -08:00
Ken VanDine
a111b3f96f Per PR review feedback, this is the more "ziggy" way of doing the check for environment variable. 2025-02-14 14:52:08 -08:00
Ken VanDine
f239df59ca Clean up environment variable while launching the shell 2025-02-14 14:52:08 -08:00
Ken VanDine
c036eb2444 Unset environment varies set by the snap 2025-02-14 14:52:08 -08:00
Ken VanDine
cee189de11 Only export XDG_CONFIG_HOME and XDG_DATA_HOME if they aren't already set 2025-02-14 14:52:08 -08:00
Ken VanDine
d2f82b2e40 Stage libglib2.0-0t64 to insure we don't mix in the host's lib 2025-02-14 14:52:08 -08:00
Ken VanDine
3e669fc4bb Improved environment handling to ensure the snap will work across
distros and unset all SNAP environment variables that could leak at
runtime
2025-02-14 14:52:08 -08:00
Ken VanDine
1a5b69181f Use patch-rpath which improves our cross distro support 2025-02-14 14:52:08 -08:00
Mitchell Hashimoto
55c5b8b72f ci: temporary apt installs required for namespace 2025-02-14 14:52:08 -08:00
Ken VanDine
5e77a973b2 Removed duplicated stage-packages 2025-02-14 14:52:08 -08:00
Ken VanDine
9c81cd323d Don't stage shells 2025-02-14 14:52:08 -08:00
Ken VanDine
78446008c4 enable-patchelf is more repliable for classic snaps 2025-02-14 14:52:08 -08:00
Ken VanDine
e09d8455a1 Set GHOSTTY_RESOURCES_DIR 2025-02-14 14:52:08 -08:00
Ken VanDine
1dcea3b11f Exit with error if building for unsupported arch 2025-02-14 14:52:08 -08:00
Ken VanDine
9d62c31f44 no-patchelf for DRI and tidy up the mesa bits 2025-02-14 14:52:08 -08:00
Ken VanDine
0272ad9edb Stage gnome-text-editor to open configuration, this makes it more
reliable across more distros as a classic snap.
2025-02-14 14:52:08 -08:00
Ken VanDine
f3829072f3 Drop patchelf 2025-02-14 14:52:08 -08:00
Ken VanDine
2b6b7c19d2 Enable patch-elf for libs part 2025-02-14 14:52:08 -08:00
Ken VanDine
3a9d61d6e4 Stage more depends to ensure we aren't getting leaks from the host 2025-02-14 14:52:08 -08:00
Ken VanDine
6d8b3973e4 EGL fixes, ensure necessary env variables are set to isolate
dependencies from the host
2025-02-14 14:52:08 -08:00
Ken VanDine
aa4d9809c3 CRAFT_TARGET_ARCH is deprecated, use CRAFT_ARCH_BUILD_FOR 2025-02-14 14:52:08 -08:00
Ken VanDine
ec8e7d9d86 Ensure LD_LIBRARY_PATH is set appropriately 2025-02-14 14:52:08 -08:00
Mitchell Hashimoto
f1f23e1c7d Add snap to nix, add arm64 builders 2025-02-14 14:52:08 -08:00
Ken VanDine
2e0e8af1ad Set a more meaningful version for the snap 2025-02-14 14:52:08 -08:00
Ken VanDine
53f1b4bc15 Changed shebang in launcher script 2025-02-14 14:52:08 -08:00
Ken VanDine
eae420a241 Only run snap workflow on push and PR 2025-02-14 14:52:08 -08:00
Ken VanDine
bf49784b7d Don't stage shells 2025-02-14 14:52:08 -08:00
Ken VanDine
b6a3b98828 enable-patchelf is more repliable for classic snaps 2025-02-14 14:52:08 -08:00
Ken VanDine
eb0816c2c4 Set GHOSTTY_RESOURCES_DIR 2025-02-14 14:52:08 -08:00
Ken VanDine
30fa18390f Install bash-completion 2025-02-14 14:52:08 -08:00
Ken VanDine
f51789b17a Exit with error if building for unsupported arch 2025-02-14 14:52:08 -08:00
Ken VanDine
97b104cf9d Set source-type for launcher dir 2025-02-14 14:52:08 -08:00
Ken VanDine
a7d1029e5c Added snap build workflow 2025-02-14 14:52:08 -08:00
Ken VanDine
aed30502bd Added snap packaging 2025-02-14 14:52:08 -08:00
Mitchell Hashimoto
56efaf0c82 [macOS] feat: add bring_all_to_front keybinding (#5006)
Can't consider the feature complete until the Linux (GTK) implementation
:/ .

Fixes #4704
2025-02-14 14:49:28 -08:00
Mitchell Hashimoto
686b6a2971 cli: add +boo command (#4876)
Add a `+boo` command to show the animation from the website. The data
for the frames is compressed during the build process. This build step
was added to the SharedDeps object because it is used in both
libghostty and in binaries.

The compression is done as follows:

- All files are concatenated together using \x01 as a combining byte
- The files are compressed to a cached build file
- A zig file is written to stdout which `@embedFile`s the compressed
  file and exposes it to the importer
- A new anonymous module "framedata" is added in the SharedDeps object

Any file can import framedata and access the compressed bytes via
`framedata.compressed`. In the `boo` command, we decompress the slice
and
split it into frames for use in the animation.

The overall addition to the binary size is 348k.
2025-02-14 14:47:51 -08:00
Tim Culverhouse
9cb297202b cli: add +boo command
Add a `+boo` command to show the animation from the website. The data
for the frames is compressed during the build process. This build step
was added to the SharedDeps object because it is used in both
libghostty and in binaries.

The compression is done as follows:
- All files are concatenated together using \x01 as a combining byte
- The files are compressed to a cached build file
- A zig file is written to stdout which `@embedFile`s the compressed
  file and exposes it to the importer
- A new anonymous module "framedata" is added in the SharedDeps object

Any file can import framedata and access the compressed bytes via
`framedata.compressed`. In the `boo` command, we decompress the file and
split it into frames for use in the animation.

The overall addition to the binary size is 348k.
2025-02-14 14:46:18 -08:00
Damien Mehala
a0f243691a feat: add bring_all_to_front keybinding
Resolves #4704.
2025-02-14 14:41:49 -08:00
Mitchell Hashimoto
cdfea4bc7e feat: add save instruction to +list-themes (#4902)
Close #4731 

<img width="1164" alt="image"
src="https://github.com/user-attachments/assets/50cb96cc-5192-424f-9ec6-1a150ae7f98b"
/>
2025-02-14 13:47:46 -08:00
Aaron Ruan
5c1f85e861 Merge branch 'ghostty-org:main' into list-theme-save 2025-02-14 13:44:33 -08:00
Aaron Ruan
2da7d77feb add save instruction to +list-themes
Signed-off-by: Aaron Ruan <aaron212cn@outlook.com>
2025-02-14 13:44:33 -08:00
Mitchell Hashimoto
1121ea9d6c Add tab title renaming feature to macos (#4217)
Tries to resolve #2509 partially by enabling tab title renaming feature
for MacOS.

* Used the existing set_title action
* Added the set_title action to Bindings so that a keybind can be set
for this feature (defaulted this to cmd+i -- same as iTerm2)
* 3 ways to trigger this feature: "Set Title" option in the right-click
menu for the window, "Set Title" option in the "View" menu in the title
bar, and the keybind (cmd+i default)
* Prevented esc sequences from the different programs from resetting the
tab title once it is set manually using a new state var called
`titleSetManually` in the SurfaceView
* The input box is a basic native macos dialog with "OK" and "Cancel".
Leaving the title text box empty resets the title to automatic / from
the `title` property in the config

**Demo**:


https://github.com/user-attachments/assets/5cacc389-4486-46c4-8cd5-dda347e9c663


Need some feedback. Thanks!
2025-02-14 13:37:29 -08:00
Aswin M Prabhu
a581955b9b Add tab title rename feature to macos 2025-02-14 13:29:36 -08:00
Mitchell Hashimoto
228b4dbd60 build: mirror most of our direct dependencies (#5765)
This adds a new script `update-mirror.sh` which generates the proper
blob format for R2 (or any blob storage) to mirror all of our
dependencies.

It doesn't automate updating build.zig.zon but on an ongoing basis this
should be easy to do manually, and we can strive to automate it in the
future.

I omitted iTerm2 color themes because we auto-update that via CI and
updating all of the machinery to send it to our mirror and so on is a
pain. Additionally, this doesn't mirror transitive dependencies because
Zig doesn't have a way to fetch those from a mirror instead (unless you
pre-generate a full cache like packagers but that's not practical for
day to day development).

It's hugely beneficial just to get most of our dependencies mirrored.
2025-02-14 11:34:08 -08:00
Mitchell Hashimoto
8231ebb770 build: mirror most of our direct dependencies
This adds a new script `update-mirror.sh` which generates the proper
blob format for R2 (or any blob storage) to mirror all of our
dependencies.

It doesn't automate updating build.zig.zon but on an ongoing basis this
should be easy to do manually, and we can strive to automate it in the
future.

I omitted iTerm2 color themes because we auto-update that via CI and
updating all of the machinery to send it to our mirror and so on is a
pain. Additionally, this doesn't mirror transitive dependencies because
Zig doesn't have a way to fetch those from a mirror instead (unless you
pre-generate a full cache like packagers but that's not practical for
day to day development).

It's hugely beneficial just to get most of our dependencies mirrored.
2025-02-14 10:06:15 -08:00
Mitchell Hashimoto
95e6a27393 build: generate a build.zig.zon.txt file for easy zig fetch scripting (#5764)
This fixes a regression in 1.1.1/1.1.2 where our PACKAGING docs mention
using `fetch-zig-cache.sh` but it was removed. This commit adds it back,
generating its contents from the build.zig.zon file (via zon2nix which
we use for our Nix packaging).

For packagers, there are no dependency changes: you still need Zig and
POSIX sh. For release time, Ghostty has a new dependency on `jq` but
otherwise the release process is the same. The check-zig-cache.sh script
is updated to generate the new build.zig.zon.txt file.
2025-02-14 09:24:07 -08:00
Jeffrey C. Ollie
f32ad5216b build: generate a build.zig.zon.txt file for easy zig fetch scripting
This fixes a regression in 1.1.1/1.1.2 where our PACKAGING docs mention
using `fetch-zig-cache.sh` but it was removed. This commit adds it back,
generating its contents from the build.zig.zon file (via zon2nix which
we use for our Nix packaging).

For packagers, there are no dependency changes: you still need Zig and
POSIX sh. For release time, Ghostty has a new dependency on `jq` but
otherwise the release process is the same. The check-zig-cache.sh script
is updated to generate the new build.zig.zon.txt file.
2025-02-14 09:23:51 -08:00
Mitchell Hashimoto
56b244973f Add back fetch-zig-cache.sh for packaging (#5762)
See the comment on more details, which also covers when and how we can
remove this.
2025-02-14 08:07:28 -08:00
Mitchell Hashimoto
cdd287c88b Add back fetch-zig-cache.sh for packaging
See the comment on more details, which also covers when and how we can
remove this.
2025-02-14 07:23:26 -08:00
Mitchell Hashimoto
315df0ab3f macos: add padded-notch option for macos-non-native-fullscreen (#5750)
Finishes #378
Supercedes #4159

This adds a new enum value for `macos-non-native-fullscreen`:
`padded-notch`. This value will add padding to the top of the window to
account for the notch on applicable devices while still hiding the menu.

This value is preferred over "visible-menu" by some people because for
screens without a notch, the window will take up the full height.

The plan in the future is that we may color the padded area when a notch
is present. In this commit it appears as transparent.

EDIT: Hah, the video below is pretty useless since the screen recording
software omits the notch. 😄


https://github.com/user-attachments/assets/4b1e84dd-3b3a-44a8-a83b-0f51e44f6cf8
2025-02-13 21:09:29 -08:00
Mitchell Hashimoto
ac7aa757bd macos: add padded-notch option for macos-non-native-fullscreen
Finishes #378
Supercedes #4159

This adds a new enum value for `macos-non-native-fullscreen`:
`padded-notch`. This value will add padding to the top of the window to
account for the notch on applicable devices while still hiding the
menu.

This value is preferred over "visible-menu" by some people because for
screens without a notch, the window will take up the full height.

The plan in the future is that we may color the padded area when a notch
is present. In this commit it appears as transparent.
2025-02-13 20:27:42 -08:00
Mitchell Hashimoto
52a5069dec up versions for development 2025-02-13 15:31:14 -08:00
627 changed files with 54303 additions and 8112 deletions

2
.envrc
View File

@ -4,3 +4,5 @@ if has nix; then
watch_file nix/{devShell,package,wraptest}.nix watch_file nix/{devShell,package,wraptest}.nix
use flake use flake
fi fi
source_env_if_exists .envrc.local

5
.gitattributes vendored
View File

@ -1,7 +1,12 @@
build.zig.zon.nix linguist-generated=true build.zig.zon.nix linguist-generated=true
build.zig.zon.txt linguist-generated=true
build.zig.zon.json linguist-generated=true
vendor/** linguist-vendored vendor/** linguist-vendored
website/** linguist-documentation website/** linguist-documentation
pkg/breakpad/vendor/** linguist-vendored pkg/breakpad/vendor/** linguist-vendored
pkg/cimgui/vendor/** linguist-vendored pkg/cimgui/vendor/** linguist-vendored
pkg/glfw/wayland-headers/** linguist-vendored
pkg/libintl/config.h linguist-generated=true
pkg/libintl/libintl.h linguist-generated=true
pkg/simdutf/vendor/** linguist-vendored pkg/simdutf/vendor/** linguist-vendored
src/terminal/res/** linguist-vendored src/terminal/res/** linguist-vendored

View File

@ -0,0 +1,139 @@
labels: ["needs confirmation"]
body:
- type: markdown
attributes:
value: |
> [!IMPORTANT]
> Please read through [the Discussion rules](https://github.com/ghostty-org/ghostty/discussions/6937), review [the FAQs](https://ghostty.org/docs/help#common-issues-and-solutions), and check for both existing [Discussions](https://github.com/ghostty-org/ghostty/discussions?discussions_q=) and [Issues](https://github.com/ghostty-org/ghostty/issues?q=sort%3Areactions-desc) prior to opening a new Discussion.
- type: markdown
attributes:
value: "# Issue Details"
- type: textarea
attributes:
label: Issue Description
description: |
Provide a detailed description of the issue. Include relevant information, such as:
- The feature or configuration option you encounter the issue with.
- The expected behavior.
- The actual behavior (and how it deviates from the expected behavior, if it is not immediately obvious).
- Relevant Ghostty logs or other stacktraces.
- Relevant screenshots, screen recordings, or other supporting media (as needed).
- If this is a regression of an existing issue that was closed or resolved, please include the previous item reference (Discussion, Issue, PR, commit) in your description.
>[!TIP]
> **Not sure what information to include?**
> Here are some recommendations:
> - **Input issues:** include your keyboard layout, a screenshot of the terminal inspector's logged keystrokes (Linux: <kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>i</kbd>; MacOS: <kbd>cmd</kbd>+<kbd>alt</kbd>+<kbd>i</kbd>), input method, Linux input method engine (IBus, Fcitx 5, or none) and its version.
> - **Font issues:** include the problematic character(s), the output of `ghostty +show-face` for these character(s), and if they work in other applications.
> - **VT issues (including image rendering issues):** attach an [asciinema](https://docs.asciinema.org/getting-started/) cast file, shell script, or text file for reproduction.
> - **Renderer issues:** (Linux) include your OpenGL version, graphics card, driver version.
placeholder: |
Example: When using SSH to connect to my remote Linux machine from my local macOS device in Ghostty, I try to run `clear`, and the screen does not clear. Instead, I see the following error message printed to the terminal: `Error opening terminal: xterm-ghostty.`
validations:
required: true
- type: textarea
attributes:
label: Reproduction Steps
description: |
Provide a detailed set of step-by-step instructions for reproducing this issue.
placeholder: |
1. Open Ghostty.
2. Connect to a remote server via SSH.
3. Try to execute `clear`.
4. Observe `xterm-ghostty` error message above.
validations:
required: true
- type: textarea
attributes:
label: Ghostty Version
description: Paste the output of `ghostty +version` here.
placeholder: |
Ghostty 1.1.3
Version
- version: 1.1.3
- channel: stable
Build Config
- Zig version: 0.13.0
- build mode : builtin.OptimizeMode.ReleaseFast
- app runtime: apprt.Runtime.none
- font engine: font.main.Backend.coretext
- renderer : renderer.Metal
- libxev : main.Backend.kqueue
render: text
validations:
required: true
- type: input
attributes:
label: OS Version Information
description: |
Please tell us what operating system (name and version) you are using.
placeholder: Ubuntu 24.04.1 (Noble Numbat)
validations:
required: true
- type: dropdown
attributes:
label: (Linux only) Display Server
description: |
If you run Linux, please tell us if you use X11 or Wayland. If you aren't sure, you can determine this by running `[ -z "$WAYLAND_DISPLAY" ] && echo X11 || echo Wayland`.
options:
- X11
- Wayland
- Other
validations:
required: false
- type: input
attributes:
label: (Linux only) Desktop Environment/Window Manager
description: |
If you run Linux, please tell us what Desktop Environment/Window Manager you are using (include the name and version).
placeholder: GNOME 47.4
validations:
required: false
- type: textarea
attributes:
label: Ghostty Configuration
description: |
Please provide the minimum configuration needed to reproduce this issue. If you cannot determine this, paste the output of `ghostty +show-config` here.
placeholder: |
font-family = CommitMono Nerd Font
font-family-bold = CommitMono Nerd Font
font-family-italic = CommitMono Nerd Font
font-family-bold-italic = CommitMono Nerd Font
font-feature = +cv07
font-size = 16
font-thicken = true
theme = catppuccin-mocha
render: ini
validations:
required: true
- type: textarea
attributes:
label: Additional Relevant Configuration
description: |
If your issue involves other programs, tools, or applications in addition to Ghostty (e.g. Neovim, tmux, Zellij, etc.), please provide the minimum configuration needed for all relevant programs to reproduce the issue here. If you use custom CSS or shaders for Ghostty, also include them here, if applicable to your issue.
placeholder: |
`tmux.conf`
---
set -g default-terminal "tmux-256color"
set-option -sa terminal-overrides ",xterm*:Tc"
set -g base-index 1
setw -g pane-base-index 1
render: text
validations:
required: false
- type: markdown
attributes:
value: |
# User Acknowledgements
> [!TIP]
> Use these links to review the existing Ghostty [Discussions](https://github.com/ghostty-org/ghostty/discussions?discussions_q=) and [Issues](https://github.com/ghostty-org/ghostty/issues?q=sort%3Areactions-desc).
- type: checkboxes
attributes:
label: "I acknowledge that:"
options:
- label: I have reviewed the FAQ and confirm that my issue is NOT among them.
required: true
- label: I have searched the Ghostty repository (both open and closed Discussions and Issues) and confirm this is not a duplicate of an existing issue or discussion.
required: true

189
.github/scripts/request_review.py vendored Normal file
View File

@ -0,0 +1,189 @@
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "githubkit",
# "loguru",
# ]
# ///
from __future__ import annotations
import asyncio
import os
import re
import sys
from collections.abc import Iterator
from contextlib import contextmanager
from itertools import chain
from githubkit import GitHub
from githubkit.exception import RequestFailed
from loguru import logger
ORG_NAME = "ghostty-org"
REPO_NAME = "ghostty"
ALLOWED_PARENT_TEAM = "localization"
LOCALIZATION_TEAM_NAME_PATTERN = re.compile(r"[a-z]{2}_[A-Z]{2}")
LEVEL_MAP = {"DEBUG": "DBG", "WARNING": "WRN", "ERROR": "ERR"}
logger.remove()
logger.add(
sys.stderr,
format=lambda record: (
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
f"<level>{LEVEL_MAP[record['level'].name]}</level> | "
"<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
"<level>{message}</level>\n"
),
backtrace=True,
diagnose=True,
)
@contextmanager
def log_fail(message: str, *, die: bool = True) -> Iterator[None]:
try:
yield
except RequestFailed as exc:
logger.error(message)
logger.error(exc)
logger.error(exc.response.raw_response.json())
if die:
sys.exit(1)
gh = GitHub(os.environ["GITHUB_TOKEN"])
with log_fail("Invalid token"):
# Do the simplest request as a test
gh.rest.rate_limit.get()
async def fetch_and_parse_codeowners() -> dict[str, str]:
logger.debug("Fetching CODEOWNERS file...")
with log_fail("Failed to fetch CODEOWNERS file"):
content = (
await gh.rest.repos.async_get_content(
ORG_NAME,
REPO_NAME,
"CODEOWNERS",
headers={"Accept": "application/vnd.github.raw+json"},
)
).text
logger.debug("Parsing CODEOWNERS file...")
codeowners: dict[str, str] = {}
for line in content.splitlines():
if not line or line.lstrip().startswith("#"):
continue
# This assumes that all entries only list one owner
# and that this owner is a team (ghostty-org/foobar)
path, owner = line.split()
path = path.lstrip("/")
owner = owner.removeprefix(f"@{ORG_NAME}/")
if not is_localization_team(owner):
logger.debug(f"Skipping non-l11n codeowner {owner!r} for {path}")
continue
codeowners[path] = owner
logger.debug(f"Found codeowner {owner!r} for {path}")
return codeowners
async def get_team_members(team_name: str) -> list[str]:
logger.debug(f"Fetching team {team_name!r}...")
with log_fail(f"Failed to fetch team {team_name!r}"):
team = (await gh.rest.teams.async_get_by_name(ORG_NAME, team_name)).parsed_data
if team.parent and team.parent.slug == ALLOWED_PARENT_TEAM:
logger.debug(f"Fetching team {team_name!r} members...")
with log_fail(f"Failed to fetch team {team_name!r} members"):
resp = await gh.rest.teams.async_list_members_in_org(ORG_NAME, team_name)
members = [m.login for m in resp.parsed_data]
logger.debug(f"Team {team_name!r} members: {', '.join(members)}")
return members
logger.warning(f"Team {team_name} does not have a {ALLOWED_PARENT_TEAM!r} parent")
return []
async def get_changed_files(pr_number: int) -> list[str]:
logger.debug("Gathering changed files...")
with log_fail("Failed to gather changed files"):
diff_entries = (
await gh.rest.pulls.async_list_files(
ORG_NAME,
REPO_NAME,
pr_number,
per_page=3000,
headers={"Accept": "application/vnd.github+json"},
)
).parsed_data
return [d.filename for d in diff_entries]
async def request_review(pr_number: int, user: str, pr_author: str) -> None:
if user == pr_author:
logger.debug(f"Skipping review request for {user!r} (is PR author)")
logger.debug(f"Requesting review from {user!r}...")
with log_fail(f"Failed to request review from {user}", die=False):
await gh.rest.pulls.async_request_reviewers(
ORG_NAME,
REPO_NAME,
pr_number,
headers={"Accept": "application/vnd.github+json"},
data={"reviewers": [user]},
)
def is_localization_team(team_name: str) -> bool:
return LOCALIZATION_TEAM_NAME_PATTERN.fullmatch(team_name) is not None
async def get_pr_author(pr_number: int) -> str:
logger.debug("Fetching PR author...")
with log_fail("Failed to fetch PR author"):
resp = await gh.rest.pulls.async_get(ORG_NAME, REPO_NAME, pr_number)
pr_author = resp.parsed_data.user.login
logger.debug(f"Found author: {pr_author!r}")
return pr_author
async def main() -> None:
logger.debug("Reading PR number...")
pr_number = int(os.environ["PR_NUMBER"])
logger.debug(f"Starting review request process for PR #{pr_number}...")
changed_files = await get_changed_files(pr_number)
logger.debug(f"Changed files: {', '.join(map(repr, changed_files))}")
pr_author = await get_pr_author(pr_number)
codeowners = await fetch_and_parse_codeowners()
found_owners = set[str]()
for file in changed_files:
logger.debug(f"Finding owner for {file!r}...")
for path, owner in codeowners.items():
if file.startswith(path):
logger.debug(f"Found owner: {owner!r}")
break
else:
logger.debug("No owner found")
continue
found_owners.add(owner)
member_lists = await asyncio.gather(
*(get_team_members(owner) for owner in found_owners)
)
await asyncio.gather(
*(
request_review(pr_number, user, pr_author)
for user in chain.from_iterable(member_lists)
)
)
if __name__ == "__main__":
asyncio.run(main())

View File

@ -77,9 +77,18 @@ jobs:
needs: [setup] needs: [setup]
env: env:
GHOSTTY_VERSION: ${{ needs.setup.outputs.version }} GHOSTTY_VERSION: ${{ needs.setup.outputs.version }}
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
- uses: cachix/install-nix-action@v30 - uses: cachix/install-nix-action@v30
with: with:
nix_path: nixpkgs=channel:nixos-unstable nix_path: nixpkgs=channel:nixos-unstable
@ -91,8 +100,8 @@ jobs:
- name: Create Tarball - name: Create Tarball
run: | run: |
git archive --format=tgz --prefix="ghostty-${GHOSTTY_VERSION}/" -o "ghostty-${GHOSTTY_VERSION}.tar.gz" HEAD nix develop -c zig build distcheck
git archive --format=tgz --prefix=ghostty-source/ -o ghostty-source.tar.gz HEAD cp zig-out/dist/ghostty-${GHOSTTY_VERSION}.tar.gz .
- name: Sign Tarball - name: Sign Tarball
run: | run: |
@ -108,8 +117,6 @@ jobs:
path: |- path: |-
ghostty-${{ env.GHOSTTY_VERSION }}.tar.gz ghostty-${{ env.GHOSTTY_VERSION }}.tar.gz
ghostty-${{ env.GHOSTTY_VERSION }}.tar.gz.minisig ghostty-${{ env.GHOSTTY_VERSION }}.tar.gz.minisig
ghostty-source.tar.gz
ghostty-source.tar.gz.minisig
build-macos: build-macos:
needs: [setup] needs: [setup]

View File

@ -101,8 +101,17 @@ jobs:
) )
}} }}
runs-on: namespace-profile-ghostty-md runs-on: namespace-profile-ghostty-md
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
- uses: cachix/install-nix-action@v30 - uses: cachix/install-nix-action@v30
with: with:
nix_path: nixpkgs=channel:nixos-unstable nix_path: nixpkgs=channel:nixos-unstable
@ -111,12 +120,17 @@ jobs:
name: ghostty name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
- name: Create Tarball - name: Create Tarball
run: git archive --format=tgz --prefix=ghostty-source/ -o ghostty-source.tar.gz HEAD run: |
rm -rf zig-out/dist
nix develop -c zig build distcheck
cp zig-out/dist/*.tar.gz ghostty-source.tar.gz
- name: Sign Tarball - name: Sign Tarball
run: | run: |
echo -n "${{ secrets.MINISIGN_KEY }}" > minisign.key echo -n "${{ secrets.MINISIGN_KEY }}" > minisign.key
echo -n "${{ secrets.MINISIGN_PASSWORD }}" > minisign.password echo -n "${{ secrets.MINISIGN_PASSWORD }}" > minisign.password
nix develop -c minisign -S -m ghostty-source.tar.gz -s minisign.key < minisign.password nix develop -c minisign -S -m ghostty-source.tar.gz -s minisign.key < minisign.password
- name: Update Release - name: Update Release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:

37
.github/workflows/review.yml vendored Normal file
View File

@ -0,0 +1,37 @@
name: Request Review
on:
pull_request:
types:
- opened
- synchronize
env:
PY_COLORS: 1
jobs:
review:
runs-on: namespace-profile-ghostty-xsm
steps:
- uses: actions/checkout@v4
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
- name: Request Localization Review
env:
GITHUB_TOKEN: ${{ secrets.GH_REVIEW_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: nix develop -c uv run .github/scripts/request_review.py

View File

@ -8,15 +8,19 @@ name: Test
jobs: jobs:
required: required:
name: "Required Checks: Test" name: "Required Checks: Test"
runs-on: namespace-profile-ghostty-sm runs-on: namespace-profile-ghostty-xsm
needs: needs:
- build
- build-bench - build-bench
- build-dist
- build-flatpak
- build-linux
- build-linux-libghostty - build-linux-libghostty
- build-nix - build-nix
- build-snap
- build-macos - build-macos
- build-macos-matrix - build-macos-matrix
- build-windows - build-windows
- build-windows-cross
- test - test
- test-gtk - test-gtk
- test-sentry-linux - test-sentry-linux
@ -24,7 +28,11 @@ jobs:
- prettier - prettier
- alejandra - alejandra
- typos - typos
- translations
- blueprint-compiler
- test-pkg-linux - test-pkg-linux
- test-debian-12
- zig-fmt
steps: steps:
- id: status - id: status
name: Determine status name: Determine status
@ -45,52 +53,6 @@ jobs:
echo "One or more required build workflows failed: ${{ steps.status.outputs.results }}" echo "One or more required build workflows failed: ${{ steps.status.outputs.results }}"
exit 1 exit 1
build:
strategy:
fail-fast: false
matrix:
os: ["namespace-profile-ghostty-md"]
target: [
aarch64-linux,
x86_64-linux,
x86-windows-gnu,
x86_64-windows-gnu,
# We don't support cross-compiling to macOS because the macOS build
# requires xcode due to the swift harness.
#aarch64-macos,
#x86_64-macos,
]
runs-on: ${{ matrix.os }}
needs: test
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
# Install Nix and use that to run our tests so our environment matches exactly.
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
# Cross-compile the binary. We always use static building for this
# because its the only way to access the headers.
- name: Test Build
run: nix develop -c zig build -Dapp-runtime=glfw -Dtarget=${{ matrix.target }}
build-bench: build-bench:
# We build benchmarks on large because it uses ReleaseFast # We build benchmarks on large because it uses ReleaseFast
runs-on: namespace-profile-ghostty-lg runs-on: namespace-profile-ghostty-lg
@ -121,6 +83,73 @@ jobs:
- name: Build Benchmarks - name: Build Benchmarks
run: nix develop -c zig build -Dapp-runtime=glfw -Demit-bench run: nix develop -c zig build -Dapp-runtime=glfw -Demit-bench
build-flatpak:
strategy:
fail-fast: false
runs-on: namespace-profile-ghostty-sm
needs: test
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
# Install Nix and use that to run our tests so our environment matches exactly.
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
- name: Build with Flatpak
run: |
nix develop -c \
zig build \
-Dflatpak=true
build-linux:
strategy:
fail-fast: false
matrix:
os: [namespace-profile-ghostty-md, namespace-profile-ghostty-md-arm64]
runs-on: ${{ matrix.os }}
needs: test
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
# Install Nix and use that to run our tests so our environment matches exactly.
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
- name: Test Build
run: nix develop -c zig build -Dapp-runtime=glfw
build-linux-libghostty: build-linux-libghostty:
runs-on: namespace-profile-ghostty-md runs-on: namespace-profile-ghostty-md
needs: test needs: test
@ -183,6 +212,45 @@ jobs:
- name: Test NixOS package build - name: Test NixOS package build
run: nix build .#ghostty run: nix build .#ghostty
build-dist:
runs-on: namespace-profile-ghostty-md
needs: test
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
# Install Nix and use that to run our tests so our environment matches exactly.
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
- name: Build and Check Source Tarball
run: |
rm -rf zig-out/dist
nix develop -c zig build distcheck
cp zig-out/dist/*.tar.gz ghostty-source.tar.gz
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: source-tarball
path: |-
ghostty-source.tar.gz
build-macos: build-macos:
runs-on: namespace-profile-ghostty-macos runs-on: namespace-profile-ghostty-macos
needs: test needs: test
@ -276,6 +344,32 @@ jobs:
nix develop -c zig build --system ${{ steps.deps.outputs.deps }} -Dapp-runtime=glfw -Drenderer=metal -Dfont-backend=coretext_harfbuzz nix develop -c zig build --system ${{ steps.deps.outputs.deps }} -Dapp-runtime=glfw -Drenderer=metal -Dfont-backend=coretext_harfbuzz
nix develop -c zig build --system ${{ steps.deps.outputs.deps }} -Dapp-runtime=glfw -Drenderer=metal -Dfont-backend=coretext_noshape nix develop -c zig build --system ${{ steps.deps.outputs.deps }} -Dapp-runtime=glfw -Drenderer=metal -Dfont-backend=coretext_noshape
build-snap:
strategy:
fail-fast: false
matrix:
os:
[namespace-profile-ghostty-snap, namespace-profile-ghostty-snap-arm64]
runs-on: ${{ matrix.os }}
needs: test
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
- run: sudo apt install -y udev
- run: sudo systemctl start systemd-udevd
- uses: snapcore/action-build@v1
build-windows: build-windows:
runs-on: windows-2022 runs-on: windows-2022
# this will not stop other jobs from running # this will not stop other jobs from running
@ -344,6 +438,52 @@ jobs:
shell: pwsh shell: pwsh
run: Get-Content -Path ".\build.log" run: Get-Content -Path ".\build.log"
build-windows-cross:
strategy:
fail-fast: false
matrix:
os: ["namespace-profile-ghostty-md"]
target: [
x86-windows-gnu,
x86_64-windows-gnu,
# We don't support cross-compiling to macOS or Linux because
# we require system libraries.
#aarch64-linux,
#x86_64-linux,
#aarch64-macos,
#x86_64-macos,
]
runs-on: ${{ matrix.os }}
needs: test
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
# Install Nix and use that to run our tests so our environment matches exactly.
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
# Cross-compile the binary. We always use static building for this
# because its the only way to access the headers.
- name: Test Build
run: nix develop -c zig build -Dapp-runtime=glfw -Dtarget=${{ matrix.target }}
test: test:
if: github.repository == 'ghostty-org/ghostty' if: github.repository == 'ghostty-org/ghostty'
runs-on: namespace-profile-ghostty-md runs-on: namespace-profile-ghostty-md
@ -374,7 +514,7 @@ jobs:
run: nix develop -c zig build -Dapp-runtime=none test run: nix develop -c zig build -Dapp-runtime=none test
- name: Test GTK Build - name: Test GTK Build
run: nix develop -c zig build -Dapp-runtime=gtk -Dgtk-adwaita=true -Demit-docs run: nix develop -c zig build -Dapp-runtime=gtk -Demit-docs
- name: Test GLFW Build - name: Test GLFW Build
run: nix develop -c zig build -Dapp-runtime=glfw run: nix develop -c zig build -Dapp-runtime=glfw
@ -387,10 +527,9 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
adwaita: ["true", "false"]
x11: ["true", "false"] x11: ["true", "false"]
wayland: ["true", "false"] wayland: ["true", "false"]
name: GTK adwaita=${{ matrix.adwaita }} x11=${{ matrix.x11 }} wayland=${{ matrix.wayland }} name: GTK x11=${{ matrix.x11 }} wayland=${{ matrix.wayland }}
runs-on: namespace-profile-ghostty-sm runs-on: namespace-profile-ghostty-sm
needs: test needs: test
env: env:
@ -421,7 +560,6 @@ jobs:
nix develop -c \ nix develop -c \
zig build \ zig build \
-Dapp-runtime=gtk \ -Dapp-runtime=gtk \
-Dgtk-adwaita=${{ matrix.adwaita }} \
-Dgtk-x11=${{ matrix.x11 }} \ -Dgtk-x11=${{ matrix.x11 }} \
-Dgtk-wayland=${{ matrix.wayland }} -Dgtk-wayland=${{ matrix.wayland }}
@ -486,9 +624,36 @@ jobs:
- name: test - name: test
run: nix develop -c zig build test --system ${{ steps.deps.outputs.deps }} run: nix develop -c zig build test --system ${{ steps.deps.outputs.deps }}
zig-fmt:
if: github.repository == 'ghostty-org/ghostty'
runs-on: namespace-profile-ghostty-xsm
timeout-minutes: 60
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- uses: actions/checkout@v4 # Check out repo so we can lint it
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
skipPush: true
useDaemon: false # sometimes fails on short jobs
- name: zig fmt
run: nix develop -c zig fmt --check .
prettier: prettier:
if: github.repository == 'ghostty-org/ghostty' if: github.repository == 'ghostty-org/ghostty'
runs-on: namespace-profile-ghostty-sm runs-on: namespace-profile-ghostty-xsm
timeout-minutes: 60 timeout-minutes: 60
env: env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache ZIG_LOCAL_CACHE_DIR: /zig/local-cache
@ -515,7 +680,7 @@ jobs:
alejandra: alejandra:
if: github.repository == 'ghostty-org/ghostty' if: github.repository == 'ghostty-org/ghostty'
runs-on: namespace-profile-ghostty-sm runs-on: namespace-profile-ghostty-xsm
timeout-minutes: 60 timeout-minutes: 60
env: env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache ZIG_LOCAL_CACHE_DIR: /zig/local-cache
@ -542,7 +707,7 @@ jobs:
typos: typos:
if: github.repository == 'ghostty-org/ghostty' if: github.repository == 'ghostty-org/ghostty'
runs-on: namespace-profile-ghostty-sm runs-on: namespace-profile-ghostty-xsm
timeout-minutes: 60 timeout-minutes: 60
env: env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache ZIG_LOCAL_CACHE_DIR: /zig/local-cache
@ -567,6 +732,74 @@ jobs:
- name: typos check - name: typos check
run: nix develop -c typos run: nix develop -c typos
translations:
if: github.repository == 'ghostty-org/ghostty'
runs-on: namespace-profile-ghostty-sm
timeout-minutes: 60
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- uses: actions/checkout@v4 # Check out repo so we can lint it
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
skipPush: true
useDaemon: false # sometimes fails on short jobs
- name: check translations
run: |
old_pot=$(mktemp)
cp po/com.mitchellh.ghostty.pot "$old_pot"
nix develop -c zig build update-translations
# Compare previous POT to current POT
msgcmp "$old_pot" po/com.mitchellh.ghostty.pot --use-untranslated
# Compare all other POs to current POT
for f in po/*.po; do
# Ignore untranslated entries
msgcmp --use-untranslated "$f" po/com.mitchellh.ghostty.pot;
done
blueprint-compiler:
if: github.repository == 'ghostty-org/ghostty'
runs-on: namespace-profile-ghostty-sm
timeout-minutes: 60
env:
ZIG_LOCAL_CACHE_DIR: /zig/local-cache
ZIG_GLOBAL_CACHE_DIR: /zig/global-cache
steps:
- uses: actions/checkout@v4 # Check out repo so we can lint it
- name: Setup Cache
uses: namespacelabs/nscloud-cache-action@v1.2.0
with:
path: |
/nix
/zig
- uses: cachix/install-nix-action@v30
with:
nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v15
with:
name: ghostty
authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}"
skipPush: true
useDaemon: false # sometimes fails on short jobs
- name: check blueprints
run: nix develop -c ./nix/build-support/check-blueprints.sh
- name: check unchanged
run: git diff --exit-code
test-pkg-linux: test-pkg-linux:
strategy: strategy:
fail-fast: false fail-fast: false
@ -601,3 +834,32 @@ jobs:
- name: Test ${{ matrix.pkg }} Build - name: Test ${{ matrix.pkg }} Build
run: | run: |
nix develop -c sh -c "cd pkg/${{ matrix.pkg }} ; zig build test" nix develop -c sh -c "cd pkg/${{ matrix.pkg }} ; zig build test"
test-debian-12:
name: Test build on Debian 12
runs-on: namespace-profile-ghostty-sm
needs: [test, build-dist]
steps:
- name: Install and configure Namespace CLI
uses: namespacelabs/nscloud-setup@v0
- name: Configure Namespace powered Buildx
uses: namespacelabs/nscloud-setup-buildx-action@v0
- name: Download Source Tarball Artifacts
uses: actions/download-artifact@v4
with:
name: source-tarball
- name: Extract tarball
run: |
mkdir dist
tar --verbose --extract --strip-components 1 --directory dist --file ghostty-source.tar.gz
- name: Build and push
uses: docker/build-push-action@v6
with:
context: dist
file: dist/src/build/docker/debian/Dockerfile
build-args: |
DISTRO_VERSION=12

View File

@ -67,6 +67,8 @@ jobs:
add-paths: | add-paths: |
build.zig.zon build.zig.zon
build.zig.zon.nix build.zig.zon.nix
build.zig.zon.txt
build.zig.zon.json
body: | body: |
Upstream revision: https://github.com/mbadolato/iTerm2-Color-Schemes/tree/${{ steps.zig_fetch.outputs.upstream_rev }} Upstream revision: https://github.com/mbadolato/iTerm2-Color-Schemes/tree/${{ steps.zig_fetch.outputs.upstream_rev }}
labels: dependencies labels: dependencies

2
.gitignore vendored
View File

@ -5,6 +5,7 @@
.DS_Store .DS_Store
.vscode/ .vscode/
.direnv/ .direnv/
.envrc.local
.flatpak-builder/ .flatpak-builder/
zig-cache/ zig-cache/
.zig-cache/ .zig-cache/
@ -18,4 +19,3 @@ glad.zip
/Box_test.ppm /Box_test.ppm
/Box_test_diff.ppm /Box_test_diff.ppm
/ghostty.qcow2 /ghostty.qcow2
/build.zig.zon2json-lock

View File

@ -78,9 +78,15 @@
# the GTK apprt. Also includes X11/Wayland integrations and general # the GTK apprt. Also includes X11/Wayland integrations and general
# Linux support. # Linux support.
# #
# - @ghostty-org/localization/* - Anything related to localization
# for a specific locale.
#
# - @ghostty-org/macos - The Ghostty macOS app and any macOS-specific # - @ghostty-org/macos - The Ghostty macOS app and any macOS-specific
# features, configurations, etc. # features, configurations, etc.
# #
# - @ghostty-org/packaging/snap - Ghostty snap packaging
# (https://snapcraft.io/ghostty)
#
# - @ghostty-org/renderer - Ghostty rendering subsystem, including the # - @ghostty-org/renderer - Ghostty rendering subsystem, including the
# rendering abstractions as well as specific renderers like OpenGL # rendering abstractions as well as specific renderers like OpenGL
# and Metal. # and Metal.
@ -142,8 +148,31 @@
# Terminal # Terminal
/src/simd/ @ghostty-org/terminal /src/simd/ @ghostty-org/terminal
/src/input/KeyEncoder.zig @ghostty-org/terminal
/src/terminal/ @ghostty-org/terminal /src/terminal/ @ghostty-org/terminal
/src/terminfo/ @ghostty-org/terminal /src/terminfo/ @ghostty-org/terminal
/src/unicode/ @ghostty-org/terminal /src/unicode/ @ghostty-org/terminal
/src/Surface.zig @ghostty-org/terminal /src/Surface.zig @ghostty-org/terminal
/src/surface_mouse.zig @ghostty-org/terminal /src/surface_mouse.zig @ghostty-org/terminal
# Localization
/po/README_TRANSLATORS.md @ghostty-org/localization
/po/com.mitchellh.ghostty.pot @ghostty-org/localization
/po/ca_ES.UTF-8.po @ghostty-org/ca_ES
/po/de_DE.UTF-8.po @ghostty-org/de_DE
/po/es_BO.UTF-8.po @ghostty-org/es_BO
/po/fr_FR.UTF-8.po @ghostty-org/fr_FR
/po/id_ID.UTF-8.po @ghostty-org/id_ID
/po/ja_JP.UTF-8.po @ghostty-org/ja_JP
/po/mk_MK.UTF-8.po @ghostty-org/mk_MK
/po/nb_NO.UTF-8.po @ghostty-org/nb_NO
/po/nl_NL.UTF-8.po @ghostty-org/nl_NL
/po/pl_PL.UTF-8.po @ghostty-org/pl_PL
/po/pt_BR.UTF-8.po @ghostty-org/pt_BR
/po/ru_RU.UTF-8.po @ghostty-org/ru_RU
/po/tr_TR.UTF-8.po @ghostty-org/tr_TR
/po/uk_UA.UTF-8.po @ghostty-org/uk_UA
/po/zh_CN.UTF-8.po @ghostty-org/zh_CN
# Packaging - Snap
/snap/ @ghostty-org/snap

View File

@ -21,6 +21,15 @@ All issues are actionable. Pick one and start working on it. Thank you.
If you need help or guidance, comment on the issue. Issues that are extra If you need help or guidance, comment on the issue. Issues that are extra
friendly to new contributors are tagged with "contributor friendly". friendly to new contributors are tagged with "contributor friendly".
**I'd like to translate Ghostty to my language!**
We have written a [Translator's Guide](po/README_TRANSLATORS.md) for
everyone interested in contributing translations to Ghostty.
Translations usually do not need to go through the process of issue triage
and you can submit pull requests directly, although please make sure that
our [Style Guide](po/README_TRANSLATORS.md#style-guide) is followed before
submission.
**I have a bug!** **I have a bug!**
1. Search the issue tracker and discussions for similar issues. 1. Search the issue tracker and discussions for similar issues.
@ -86,6 +95,10 @@ pull request will be accepted with a high degree of certainty.
> working on Ghostty.** If you're a user reporting an issue, you can > working on Ghostty.** If you're a user reporting an issue, you can
> ignore the rest of this document. > ignore the rest of this document.
## Including and Updating Translations
See the [Contributor's Guide](po/README_CONTRIBUTORS.md) for more details.
## Input Stack Testing ## Input Stack Testing
The input stack is the part of the codebase that starts with a The input stack is the part of the codebase that starts with a

View File

@ -23,13 +23,6 @@ https://release.files.ghostty.org/VERSION/ghostty-VERSION.tar.gz
https://release.files.ghostty.org/VERSION/ghostty-VERSION.tar.gz.minisig https://release.files.ghostty.org/VERSION/ghostty-VERSION.tar.gz.minisig
``` ```
> [!NOTE]
>
> **Version 1.0.0 the filename is `ghostty-source.tar.gz`.** Future
> versions will use the `ghostty-VERSION.tar.gz` format since it is more
> typical for source tarballs. But for version 1.0.0, the filename is
> `ghostty-source.tar.gz`.
Signature files are signed with Signature files are signed with
[minisign](https://jedisct1.github.io/minisign/) [minisign](https://jedisct1.github.io/minisign/)
using the following public key: using the following public key:
@ -55,7 +48,7 @@ To find the version of Zig required to build Ghostty, check the `required_zig`
constant in `build.zig`. You don't need to know Zig to extract this information. constant in `build.zig`. You don't need to know Zig to extract this information.
This version will always be an official released version of Zig. This version will always be an official released version of Zig.
For example, at the time of writing this document, Ghostty requires Zig 0.13.0. For example, at the time of writing this document, Ghostty requires Zig 0.14.0.
## Building Ghostty ## Building Ghostty
@ -88,6 +81,13 @@ for system packages which separate a build and install step, since the
install step can then be done with a `mv` or `cp` command (from `/tmp/ghostty` install step can then be done with a `mv` or `cp` command (from `/tmp/ghostty`
to wherever the package manager expects it). to wherever the package manager expects it).
> [!NOTE]
>
> **Version 1.1.1 and 1.1.2 are missing `fetch-zig-cache.sh`.** This was
> an oversight on the release process. You can use the script from version
> 1.1.0 to fetch the Zig cache for these versions. Future versions will
> restore the script.
### Build Options ### Build Options
Ghostty uses the Zig build system. You can see all available build options by Ghostty uses the Zig build system. You can see all available build options by

View File

@ -188,8 +188,11 @@ SENTRY_DSN=https://e914ee84fd895c4fe324afa3e53dac76@o4507352570920960.ingest.us.
## Developing Ghostty ## Developing Ghostty
See the documentation on the Ghostty website for See the documentation on the Ghostty website for
[building Ghostty from source](http://ghostty.org/docs/install/build). [building Ghostty from a source tarball](http://ghostty.org/docs/install/build).
For development, omit the `-Doptimize` flag to build a debug build. Building Ghostty from a Git checkout is very similar, except you want to
omit the `-Doptimize` flag to build a debug build, and you may require
additional dependencies since the source tarball includes some processed
files that are not in the Git repository.
On Linux or macOS, you can use `zig build -Dapp-runtime=glfw run` for a quick On Linux or macOS, you can use `zig build -Dapp-runtime=glfw run` for a quick
GLFW-based app for a faster development cycle while developing core GLFW-based app for a faster development cycle while developing core
@ -206,6 +209,21 @@ Other useful commands:
in the current running terminal emulator so if you want to check the in the current running terminal emulator so if you want to check the
behavior of this project, you must run this command in Ghostty. behavior of this project, you must run this command in Ghostty.
### Extra Dependencies
Building Ghostty from a Git checkout on Linux requires some additional
dependencies:
- `blueprint-compiler`
macOS users don't require any additional dependencies.
> [!NOTE]
> This only applies to building from a _Git checkout_. This section does
> not apply if you're building from a released _source tarball_. For
> source tarballs, see the
> [website](http://ghostty.org/docs/install/build).
### Linting ### Linting
#### Prettier #### Prettier
@ -233,7 +251,7 @@ nix develop -c prettier --write .
Nix modules are formatted with [Alejandra](https://github.com/kamadorueda/alejandra/). An Alejandra CI check Nix modules are formatted with [Alejandra](https://github.com/kamadorueda/alejandra/). An Alejandra CI check
will fail builds with improper formatting. will fail builds with improper formatting.
Nix users can use the following command to format with Alejanda: Nix users can use the following command to format with Alejandra:
``` ```
nix develop -c alejandra . nix develop -c alejandra .

View File

@ -3,7 +3,7 @@ const builtin = @import("builtin");
const buildpkg = @import("src/build/main.zig"); const buildpkg = @import("src/build/main.zig");
comptime { comptime {
buildpkg.requireZig("0.13.0"); buildpkg.requireZig("0.14.0");
} }
pub fn build(b: *std.Build) !void { pub fn build(b: *std.Build) !void {
@ -11,34 +11,42 @@ pub fn build(b: *std.Build) !void {
// Ghostty resources like terminfo, shell integration, themes, etc. // Ghostty resources like terminfo, shell integration, themes, etc.
const resources = try buildpkg.GhosttyResources.init(b, &config); const resources = try buildpkg.GhosttyResources.init(b, &config);
const i18n = try buildpkg.GhosttyI18n.init(b, &config);
// Ghostty dependencies used by many artifacts. // Ghostty dependencies used by many artifacts.
const deps = try buildpkg.SharedDeps.init(b, &config); const deps = try buildpkg.SharedDeps.init(b, &config);
const exe = try buildpkg.GhosttyExe.init(b, &config, &deps);
if (config.emit_helpgen) deps.help_strings.install(); if (config.emit_helpgen) deps.help_strings.install();
// Ghostty executable, the actual runnable Ghostty program.
const exe = try buildpkg.GhosttyExe.init(b, &config, &deps);
// Ghostty docs // Ghostty docs
if (config.emit_docs) { const docs = try buildpkg.GhosttyDocs.init(b, &deps);
const docs = try buildpkg.GhosttyDocs.init(b, &deps); if (config.emit_docs) docs.install();
docs.install();
}
// Ghostty webdata // Ghostty webdata
if (config.emit_webdata) { const webdata = try buildpkg.GhosttyWebdata.init(b, &deps);
const webdata = try buildpkg.GhosttyWebdata.init(b, &deps); if (config.emit_webdata) webdata.install();
webdata.install();
}
// Ghostty bench tools // Ghostty bench tools
if (config.emit_bench) { const bench = try buildpkg.GhosttyBench.init(b, &deps);
const bench = try buildpkg.GhosttyBench.init(b, &deps); if (config.emit_bench) bench.install();
bench.install();
// Ghostty dist tarball
const dist = try buildpkg.GhosttyDist.init(b, &config);
{
const step = b.step("dist", "Build the dist tarball");
step.dependOn(dist.install_step);
const check_step = b.step("distcheck", "Install and validate the dist tarball");
check_step.dependOn(dist.check_step);
check_step.dependOn(dist.install_step);
} }
// If we're not building libghostty, then install the exe and resources. // If we're not building libghostty, then install the exe and resources.
if (config.app_runtime != .none) { if (config.app_runtime != .none) {
exe.install(); exe.install();
resources.install(); resources.install();
i18n.install();
} }
// Libghostty // Libghostty
@ -48,7 +56,7 @@ pub fn build(b: *std.Build) !void {
// As such, these build steps are lacking. For example, the Darwin // As such, these build steps are lacking. For example, the Darwin
// build only produces an xcframework. // build only produces an xcframework.
if (config.app_runtime == .none) { if (config.app_runtime == .none) {
if (config.target.result.isDarwin()) darwin: { if (config.target.result.os.tag.isDarwin()) darwin: {
if (!config.emit_xcframework) break :darwin; if (!config.emit_xcframework) break :darwin;
// Build the xcframework // Build the xcframework
@ -58,6 +66,7 @@ pub fn build(b: *std.Build) !void {
// The xcframework build always installs resources because our // The xcframework build always installs resources because our
// macOS xcode project contains references to them. // macOS xcode project contains references to them.
resources.install(); resources.install();
i18n.install();
// If we aren't emitting docs we need to emit a placeholder so // If we aren't emitting docs we need to emit a placeholder so
// our macOS xcodeproject builds. // our macOS xcodeproject builds.
@ -80,6 +89,16 @@ pub fn build(b: *std.Build) !void {
{ {
const run_cmd = b.addRunArtifact(exe.exe); const run_cmd = b.addRunArtifact(exe.exe);
if (b.args) |args| run_cmd.addArgs(args); if (b.args) |args| run_cmd.addArgs(args);
// Set the proper resources dir so things like shell integration
// work correctly. If we're running `zig build run` in Ghostty,
// this also ensures it overwrites the release one with our debug
// build.
run_cmd.setEnvironmentVariable(
"GHOSTTY_RESOURCES_DIR",
b.getInstallPath(.prefix, "share/ghostty"),
);
const run_step = b.step("run", "Run the app"); const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step); run_step.dependOn(&run_cmd.step);
} }
@ -103,4 +122,11 @@ pub fn build(b: *std.Build) !void {
test_step.dependOn(&test_run.step); test_step.dependOn(&test_run.step);
} }
} }
// update-translations does what it sounds like and updates the "pot"
// files. These should be committed to the repo.
{
const step = b.step("update-translations", "Update translation files");
step.dependOn(i18n.update_step);
}
} }

View File

@ -1,90 +1,111 @@
.{ .{
.name = "ghostty", .name = .ghostty,
.version = "1.1.2", .version = "1.1.4",
.paths = .{""}, .paths = .{""},
.fingerprint = 0x64407a2a0b4147e5,
.dependencies = .{ .dependencies = .{
// Zig libs // Zig libs
.libxev = .{ .libxev = .{
.url = "https://github.com/mitchellh/libxev/archive/31eed4e337fed7b0149319e5cdbb62b848c24fbd.tar.gz", // mitchellh/libxev
.hash = "1220ebf88622c4d502dc59e71347e4d28c47e033f11b59aff774ae5787565c40999c", .url = "https://github.com/mitchellh/libxev/archive/3df9337a9e84450a58a2c4af434ec1a036f7b494.tar.gz",
}, .hash = "libxev-0.0.0-86vtc-ziEgDbLP0vihUn1MhsxNKY4GJEga6BEr7oyHpz",
.mach_glfw = .{
.url = "https://github.com/mitchellh/mach-glfw/archive/37c2995f31abcf7e8378fba68ddcf4a3faa02de0.tar.gz",
.hash = "12206ed982e709e565d536ce930701a8c07edfd2cfdce428683f3f2a601d37696a62",
.lazy = true, .lazy = true,
}, },
.vaxis = .{ .vaxis = .{
.url = "git+https://github.com/rockorager/libvaxis/?ref=main#6d729a2dc3b934818dffe06d2ba3ce02841ed74b", // rockorager/libvaxis
.hash = "12200df4ebeaed45de26cb2c9f3b6f3746d8013b604e035dae658f86f586c8c91d2f", .url = "git+https://github.com/rockorager/libvaxis#1f41c121e8fc153d9ce8c6eb64b2bbab68ad7d23",
.hash = "vaxis-0.1.0-BWNV_FUICQAFZnTCL11TUvnUr1Y0_ZdqtXHhd51d76Rn",
.lazy = true,
}, },
.z2d = .{ .z2d = .{
.url = "git+https://github.com/vancluever/z2d?ref=v0.4.0#4638bb02a9dc41cc2fb811f092811f6a951c752a", // vancluever/z2d
.hash = "12201f0d542e7541cf492a001d4d0d0155c92f58212fbcb0d224e95edeba06b5416a", .url = "https://github.com/vancluever/z2d/archive/1e89605a624940c310c7a1d81b46a7c5c05919e3.tar.gz",
.hash = "z2d-0.6.0-j5P_HvLdCABu-dXpCeRM7Uk4m16vULg1980lMNCQj4_C",
.lazy = true,
}, },
.zig_objc = .{ .zig_objc = .{
.url = "https://github.com/mitchellh/zig-objc/archive/9b8ba849b0f58fe207ecd6ab7c147af55b17556e.tar.gz", // mitchellh/zig-objc
.hash = "1220e17e64ef0ef561b3e4b9f3a96a2494285f2ec31c097721bf8c8677ec4415c634", .url = "https://github.com/mitchellh/zig-objc/archive/3ab0d37c7d6b933d6ded1b3a35b6b60f05590a98.tar.gz",
.hash = "zig_objc-0.0.0-Ir_Sp3TyAADEVRTxXlScq3t_uKAM91MYNerZkHfbD0yt",
.lazy = true,
}, },
.zig_js = .{ .zig_js = .{
.url = "https://github.com/mitchellh/zig-js/archive/d0b8b0a57c52fbc89f9d9fecba75ca29da7dd7d1.tar.gz", // mitchellh/zig-js
.hash = "12205a66d423259567764fa0fc60c82be35365c21aeb76c5a7dc99698401f4f6fefc", .url = "https://deps.files.ghostty.org/zig_js-12205a66d423259567764fa0fc60c82be35365c21aeb76c5a7dc99698401f4f6fefc.tar.gz",
.hash = "N-V-__8AAB9YCQBaZtQjJZVndk-g_GDIK-NTZcIa63bFp9yZ",
.lazy = true,
}, },
.ziglyph = .{ .ziglyph = .{
.url = "https://deps.files.ghostty.org/ziglyph-b89d43d1e3fb01b6074bc1f7fc980324b04d26a5.tar.gz", .url = "https://deps.files.ghostty.org/ziglyph-b89d43d1e3fb01b6074bc1f7fc980324b04d26a5.tar.gz",
.hash = "12207831bce7d4abce57b5a98e8f3635811cfefd160bca022eb91fe905d36a02cf25", .hash = "ziglyph-0.11.2-AAAAAHPtHwB4Mbzn1KvOV7Wpjo82NYEc_v0WC8oCLrkf",
.lazy = true,
}, },
.zig_wayland = .{ .zig_wayland = .{
.url = "https://deps.files.ghostty.org/zig-wayland-fbfe3b4ac0b472a27b1f1a67405436c58cbee12d.tar.gz", // codeberg ifreund/zig-wayland
.hash = "12209ca054cb1919fa276e328967f10b253f7537c4136eb48f3332b0f7cf661cad38", .url = "https://codeberg.org/ifreund/zig-wayland/archive/f3c5d503e540ada8cbcb056420de240af0c094f7.tar.gz",
.hash = "wayland-0.4.0-dev-lQa1kjfIAQCmhhQu3xF0KH-94-TzeMXOqfnP0-Dg6Wyy",
}, },
.zf = .{ .zf = .{
.url = "git+https://github.com/natecraddock/zf/?ref=main#ed99ca18b02dda052e20ba467e90b623c04690dd", // natecraddock/zf
.hash = "1220edc3b8d8bedbb50555947987e5e8e2f93871ca3c8e8d4cc8f1377c15b5dd35e8", .url = "https://github.com/natecraddock/zf/archive/7aacbe6d155d64d15937ca95ca6c014905eb531f.tar.gz",
.hash = "zf-0.10.3-OIRy8aiIAACLrBllz0zjxaH0aOe5oNm3KtEMyCntST-9",
.lazy = true,
}, },
.gobject = .{ .gobject = .{
.url = "https://github.com/ianprime0509/zig-gobject/releases/download/v0.2.2/bindings-gnome47.tar.zst", // https://github.com/jcollie/ghostty-gobject based on zig_gobject
.hash = "12208d70ee791d7ef7e16e1c3c9c1127b57f1ed066a24f87d57fc9f730c5dc394b9d", // Temporary until we generate them at build time automatically.
.url = "https://github.com/jcollie/ghostty-gobject/releases/download/0.14.0-2025-03-18-21-1/ghostty-gobject-0.14.0-2025-03-18-21-1.tar.zst",
.hash = "gobject-0.2.0-Skun7IWDlQAOKu4BV7LapIxL9Imbq1JRmzvcIkazvAxR",
.lazy = true,
}, },
// C libs // C libs
.cimgui = .{ .path = "./pkg/cimgui" }, .cimgui = .{ .path = "./pkg/cimgui", .lazy = true },
.fontconfig = .{ .path = "./pkg/fontconfig" }, .fontconfig = .{ .path = "./pkg/fontconfig", .lazy = true },
.freetype = .{ .path = "./pkg/freetype" }, .freetype = .{ .path = "./pkg/freetype", .lazy = true },
.harfbuzz = .{ .path = "./pkg/harfbuzz" }, .glfw = .{ .path = "./pkg/glfw", .lazy = true },
.highway = .{ .path = "./pkg/highway" }, .gtk4_layer_shell = .{ .path = "./pkg/gtk4-layer-shell", .lazy = true },
.libpng = .{ .path = "./pkg/libpng" }, .harfbuzz = .{ .path = "./pkg/harfbuzz", .lazy = true },
.macos = .{ .path = "./pkg/macos" }, .highway = .{ .path = "./pkg/highway", .lazy = true },
.oniguruma = .{ .path = "./pkg/oniguruma" }, .libintl = .{ .path = "./pkg/libintl", .lazy = true },
.opengl = .{ .path = "./pkg/opengl" }, .libpng = .{ .path = "./pkg/libpng", .lazy = true },
.sentry = .{ .path = "./pkg/sentry" }, .macos = .{ .path = "./pkg/macos", .lazy = true },
.simdutf = .{ .path = "./pkg/simdutf" }, .oniguruma = .{ .path = "./pkg/oniguruma", .lazy = true },
.utfcpp = .{ .path = "./pkg/utfcpp" }, .opengl = .{ .path = "./pkg/opengl", .lazy = true },
.wuffs = .{ .path = "./pkg/wuffs" }, .sentry = .{ .path = "./pkg/sentry", .lazy = true },
.zlib = .{ .path = "./pkg/zlib" }, .simdutf = .{ .path = "./pkg/simdutf", .lazy = true },
.utfcpp = .{ .path = "./pkg/utfcpp", .lazy = true },
.wuffs = .{ .path = "./pkg/wuffs", .lazy = true },
.zlib = .{ .path = "./pkg/zlib", .lazy = true },
// Shader translation // Shader translation
.glslang = .{ .path = "./pkg/glslang" }, .glslang = .{ .path = "./pkg/glslang", .lazy = true },
.spirv_cross = .{ .path = "./pkg/spirv-cross" }, .spirv_cross = .{ .path = "./pkg/spirv-cross", .lazy = true },
// Wayland // Wayland
.wayland = .{ .wayland = .{
.url = "https://deps.files.ghostty.org/wayland-9cb3d7aa9dc995ffafdbdef7ab86a949d0fb0e7d.tar.gz", .url = "https://deps.files.ghostty.org/wayland-9cb3d7aa9dc995ffafdbdef7ab86a949d0fb0e7d.tar.gz",
.hash = "12202cdac858abc52413a6c6711d5026d2d3c8e13f95ca2c327eade0736298bb021f", .hash = "N-V-__8AAKrHGAAs2shYq8UkE6bGcR1QJtLTyOE_lcosMn6t",
.lazy = true,
}, },
.wayland_protocols = .{ .wayland_protocols = .{
.url = "https://deps.files.ghostty.org/wayland-protocols-258d8f88f2c8c25a830c6316f87d23ce1a0f12d9.tar.gz", .url = "https://deps.files.ghostty.org/wayland-protocols-258d8f88f2c8c25a830c6316f87d23ce1a0f12d9.tar.gz",
.hash = "12201a57c6ce0001aa034fa80fba3e1cd2253c560a45748f4f4dd21ff23b491cddef", .hash = "N-V-__8AAKw-DAAaV8bOAAGqA0-oD7o-HNIlPFYKRXSPT03S",
.lazy = true,
}, },
.plasma_wayland_protocols = .{ .plasma_wayland_protocols = .{
.url = "git+https://github.com/KDE/plasma-wayland-protocols?ref=main#db525e8f9da548cffa2ac77618dd0fbe7f511b86", .url = "https://deps.files.ghostty.org/plasma_wayland_protocols-12207e0851c12acdeee0991e893e0132fc87bb763969a585dc16ecca33e88334c566.tar.gz",
.hash = "12207e0851c12acdeee0991e893e0132fc87bb763969a585dc16ecca33e88334c566", .hash = "N-V-__8AAKYZBAB-CFHBKs3u4JkeiT4BMvyHu3Y5aaWF3Bbs",
.lazy = true,
}, },
// Other // Other
.apple_sdk = .{ .path = "./pkg/apple-sdk" }, .apple_sdk = .{ .path = "./pkg/apple-sdk" },
.iterm2_themes = .{ .iterm2_themes = .{
.url = "https://github.com/mbadolato/iTerm2-Color-Schemes/archive/db227d159adc265818f2e898da0f70ef8d7b580e.tar.gz", .url = "https://github.com/mbadolato/iTerm2-Color-Schemes/archive/4c57d8c11d352a4aeda6928b65d78794c28883a5.tar.gz",
.hash = "12203d2647e5daf36a9c85b969e03f422540786ce9ea624eb4c26d204fe1f46218f3", .hash = "N-V-__8AAEH8MwQaEsARbyV42-bSZGcu1am8xtg2h67wTFC3",
.lazy = true,
}, },
}, },
} }

172
build.zig.zon.json generated Normal file
View File

@ -0,0 +1,172 @@
{
"N-V-__8AALw2uwF_03u4JRkZwRLc3Y9hakkYV7NKRR9-RIZJ": {
"name": "breakpad",
"url": "https://deps.files.ghostty.org/breakpad-b99f444ba5f6b98cac261cbb391d8766b34a5918.tar.gz",
"hash": "sha256-bMqYlD0amQdmzvYQd8Ca/1k4Bj/heh7+EijlQSttatk="
},
"N-V-__8AAIrfdwARSa-zMmxWwFuwpXf1T3asIN7s5jqi9c1v": {
"name": "fontconfig",
"url": "https://deps.files.ghostty.org/fontconfig-2.14.2.tar.gz",
"hash": "sha256-O6LdkhWHGKzsXKrxpxYEO1qgVcJ7CB2RSvPMtA3OilU="
},
"N-V-__8AAKLKpwC4H27Ps_0iL3bPkQb-z6ZVSrB-x_3EEkub": {
"name": "freetype",
"url": "https://deps.files.ghostty.org/freetype-1220b81f6ecfb3fd222f76cf9106fecfa6554ab07ec7fdc4124b9bb063ae2adf969d.tar.gz",
"hash": "sha256-QnIB9dUVFnDQXB9bRb713aHy592XHvVPD+qqf/0quQw="
},
"N-V-__8AADcZkgn4cMhTUpIz6mShCKyqqB-NBtf_S2bHaTC-": {
"name": "gettext",
"url": "https://deps.files.ghostty.org/gettext-0.24.tar.gz",
"hash": "sha256-yRhQPVk9cNr0hE0XWhPYFq+stmfAb7oeydzVACwVGLc="
},
"N-V-__8AAMrJSwAUGb9-vTzkNR-5LXS81MR__ZRVfF3tWgG6": {
"name": "glfw",
"url": "https://github.com/glfw/glfw/archive/e7ea71be039836da3a98cea55ae5569cb5eb885c.tar.gz",
"hash": "sha256-M3N1XUAlMebBo5X1Py+9YxjKXgZ6eacqWRCbUmwLKQo="
},
"N-V-__8AABzkUgISeKGgXAzgtutgJsZc0-kkeqBBscJgMkvy": {
"name": "glslang",
"url": "https://deps.files.ghostty.org/glslang-12201278a1a05c0ce0b6eb6026c65cd3e9247aa041b1c260324bf29cee559dd23ba1.tar.gz",
"hash": "sha256-FKLtu1Ccs+UamlPj9eQ12/WXFgS0uDPmPmB26MCpl7U="
},
"gobject-0.2.0-Skun7IWDlQAOKu4BV7LapIxL9Imbq1JRmzvcIkazvAxR": {
"name": "gobject",
"url": "https://github.com/jcollie/ghostty-gobject/releases/download/0.14.0-2025-03-18-21-1/ghostty-gobject-0.14.0-2025-03-18-21-1.tar.zst",
"hash": "sha256-hWcpl0Wd3XydT+RY7+VIoxXPhCzele1Ip76YSh+KmLI="
},
"N-V-__8AALiNBAA-_0gprYr92CjrMj1I5bqNu0TSJOnjFNSr": {
"name": "gtk4_layer_shell",
"url": "https://deps.files.ghostty.org/gtk4-layer-shell-1.1.0.tar.gz",
"hash": "sha256-mChCgSYKXu9bT2OlXxbEv2p4ihAgptsDfssPcfozaYg="
},
"N-V-__8AAG02ugUcWec-Ndp-i7JTsJ0dgF8nnJRUInkGLG7G": {
"name": "harfbuzz",
"url": "https://deps.files.ghostty.org/harfbuzz-11.0.0.tar.xz",
"hash": "sha256-8WNRuv4hRyX+LB1bWfDZPkmQWkskeJn7kNcM/5U6K5s="
},
"N-V-__8AAGmZhABbsPJLfbqrh6JTHsXhY6qCaLAQyx25e0XE": {
"name": "highway",
"url": "https://deps.files.ghostty.org/highway-66486a10623fa0d72fe91260f96c892e41aceb06.tar.gz",
"hash": "sha256-h9T4iT704I8iSXNgj/6/lCaKgTgLp5wS6IQZaMgKohI="
},
"N-V-__8AAH0GaQC8a52s6vfIxg88OZgFgEW6DFxfSK4lX_l3": {
"name": "imgui",
"url": "https://deps.files.ghostty.org/imgui-1220bc6b9daceaf7c8c60f3c3998058045ba0c5c5f48ae255ff97776d9cd8bfc6402.tar.gz",
"hash": "sha256-oF/QHgTPEat4Hig4fGIdLkIPHmBEyOJ6JeYD6pnveGA="
},
"N-V-__8AAEH8MwQaEsARbyV42-bSZGcu1am8xtg2h67wTFC3": {
"name": "iterm2_themes",
"url": "https://github.com/mbadolato/iTerm2-Color-Schemes/archive/4c57d8c11d352a4aeda6928b65d78794c28883a5.tar.gz",
"hash": "sha256-c+twvkEPiz1DaULYlnGXLxis19Q2h+TgBJxoARMasjU="
},
"N-V-__8AAJrvXQCqAT8Mg9o_tk6m0yf5Fz-gCNEOKLyTSerD": {
"name": "libpng",
"url": "https://deps.files.ghostty.org/libpng-1220aa013f0c83da3fb64ea6d327f9173fa008d10e28bc9349eac3463457723b1c66.tar.gz",
"hash": "sha256-/syVtGzwXo4/yKQUdQ4LparQDYnp/fF16U/wQcrxoDo="
},
"libxev-0.0.0-86vtc-ziEgDbLP0vihUn1MhsxNKY4GJEga6BEr7oyHpz": {
"name": "libxev",
"url": "https://github.com/mitchellh/libxev/archive/3df9337a9e84450a58a2c4af434ec1a036f7b494.tar.gz",
"hash": "sha256-oKZqA9d79jHnp/HsqJWQE33Ffn5Ee5G4VnlQepQuY4o="
},
"N-V-__8AAG3RoQEyRC2Vw7Qoro5SYBf62IHn3HjqtNVY6aWK": {
"name": "libxml2",
"url": "https://deps.files.ghostty.org/libxml2-2.11.5.tar.gz",
"hash": "sha256-bCgFni4+60K1tLFkieORamNGwQladP7jvGXNxdiaYhU="
},
"N-V-__8AAHjwMQDBXnLq3Q2QhaivE0kE2aD138vtX2Bq1g7c": {
"name": "oniguruma",
"url": "https://deps.files.ghostty.org/oniguruma-1220c15e72eadd0d9085a8af134904d9a0f5dfcbed5f606ad60edc60ebeccd9706bb.tar.gz",
"hash": "sha256-ABqhIC54RI9MC/GkjHblVodrNvFtks4yB+zP1h2Z8qA="
},
"N-V-__8AADYiAAB_80AWnH1AxXC0tql9thT-R-DYO1gBqTLc": {
"name": "pixels",
"url": "https://deps.files.ghostty.org/pixels-12207ff340169c7d40c570b4b6a97db614fe47e0d83b5801a932dcd44917424c8806.tar.gz",
"hash": "sha256-Veg7FtCRCCUCvxSb9FfzH0IJLFmCZQ4/+657SIcb8Ro="
},
"N-V-__8AAKYZBAB-CFHBKs3u4JkeiT4BMvyHu3Y5aaWF3Bbs": {
"name": "plasma_wayland_protocols",
"url": "https://deps.files.ghostty.org/plasma_wayland_protocols-12207e0851c12acdeee0991e893e0132fc87bb763969a585dc16ecca33e88334c566.tar.gz",
"hash": "sha256-XFi6IUrNjmvKNCbcCLAixGqN2Zeymhs+KLrfccIN9EE="
},
"N-V-__8AAPlZGwBEa-gxrcypGBZ2R8Bse4JYSfo_ul8i2jlG": {
"name": "sentry",
"url": "https://deps.files.ghostty.org/sentry-1220446be831adcca918167647c06c7b825849fa3fba5f22da394667974537a9c77e.tar.gz",
"hash": "sha256-KsZJfMjWGo0xCT5HrduMmyxFsWsHBbszSoNbZCPDGN8="
},
"N-V-__8AANb6pwD7O1WG6L5nvD_rNMvnSc9Cpg1ijSlTYywv": {
"name": "spirv_cross",
"url": "https://deps.files.ghostty.org/spirv_cross-1220fb3b5586e8be67bc3feb34cbe749cf42a60d628d2953632c2f8141302748c8da.tar.gz",
"hash": "sha256-tStvz8Ref6abHwahNiwVVHNETizAmZVVaxVsU7pmV+M="
},
"N-V-__8AAHffAgDU0YQmynL8K35WzkcnMUmBVQHQ0jlcKpjH": {
"name": "utfcpp",
"url": "https://deps.files.ghostty.org/utfcpp-1220d4d18426ca72fc2b7e56ce47273149815501d0d2395c2a98c726b31ba931e641.tar.gz",
"hash": "sha256-/8ZooxDndgfTk/PBizJxXyI9oerExNbgV5oR345rWc8="
},
"vaxis-0.1.0-BWNV_FUICQAFZnTCL11TUvnUr1Y0_ZdqtXHhd51d76Rn": {
"name": "vaxis",
"url": "git+https://github.com/rockorager/libvaxis#1f41c121e8fc153d9ce8c6eb64b2bbab68ad7d23",
"hash": "sha256-bNZ3oveT6vPChjimPJ/GGfcdivlAeJdl/xfWM+S/MHY="
},
"N-V-__8AAKrHGAAs2shYq8UkE6bGcR1QJtLTyOE_lcosMn6t": {
"name": "wayland",
"url": "https://deps.files.ghostty.org/wayland-9cb3d7aa9dc995ffafdbdef7ab86a949d0fb0e7d.tar.gz",
"hash": "sha256-6kGR1o5DdnflHzqs3ieCmBAUTpMdOXoyfcYDXiw5xQ0="
},
"N-V-__8AAKw-DAAaV8bOAAGqA0-oD7o-HNIlPFYKRXSPT03S": {
"name": "wayland_protocols",
"url": "https://deps.files.ghostty.org/wayland-protocols-258d8f88f2c8c25a830c6316f87d23ce1a0f12d9.tar.gz",
"hash": "sha256-XO3K3egbdeYPI+XoO13SuOtO+5+Peb16NH0UiusFMPg="
},
"N-V-__8AAAzZywE3s51XfsLbP9eyEw57ae9swYB9aGB6fCMs": {
"name": "wuffs",
"url": "https://deps.files.ghostty.org/wuffs-122037b39d577ec2db3fd7b2130e7b69ef6cc1807d68607a7c232c958315d381b5cd.tar.gz",
"hash": "sha256-nkzSCr6W5sTG7enDBXEIhgEm574uLD41UVR2wlC+HBM="
},
"z2d-0.6.0-j5P_HvLdCABu-dXpCeRM7Uk4m16vULg1980lMNCQj4_C": {
"name": "z2d",
"url": "https://github.com/vancluever/z2d/archive/1e89605a624940c310c7a1d81b46a7c5c05919e3.tar.gz",
"hash": "sha256-PEKVSUZ6teRbDyhFPWSiuBSe40pgr0kVRivIY8Cn8HQ="
},
"zf-0.10.3-OIRy8aiIAACLrBllz0zjxaH0aOe5oNm3KtEMyCntST-9": {
"name": "zf",
"url": "https://github.com/natecraddock/zf/archive/7aacbe6d155d64d15937ca95ca6c014905eb531f.tar.gz",
"hash": "sha256-3nulNQd/4rZ4paeXJYXwAliNNyRNsIOX/q3z1JB8C7I="
},
"zg-0.13.4-AAAAAGiZ7QLz4pvECFa_wG4O4TP4FLABHHbemH2KakWM": {
"name": "zg",
"url": "git+https://codeberg.org/atman/zg#4a002763419a34d61dcbb1f415821b83b9bf8ddc",
"hash": "sha256-fo3l6cjkrr/godElTGnQzalBsasN7J73IDIRmw7v1gA="
},
"N-V-__8AAB9YCQBaZtQjJZVndk-g_GDIK-NTZcIa63bFp9yZ": {
"name": "zig_js",
"url": "https://deps.files.ghostty.org/zig_js-12205a66d423259567764fa0fc60c82be35365c21aeb76c5a7dc99698401f4f6fefc.tar.gz",
"hash": "sha256-fyNeCVbC9UAaKJY6JhAZlT0A479M/AKYMPIWEZbDWD0="
},
"zig_objc-0.0.0-Ir_Sp3TyAADEVRTxXlScq3t_uKAM91MYNerZkHfbD0yt": {
"name": "zig_objc",
"url": "https://github.com/mitchellh/zig-objc/archive/3ab0d37c7d6b933d6ded1b3a35b6b60f05590a98.tar.gz",
"hash": "sha256-zn1tR6xhSmDla4UJ3t+Gni4Ni3R8deSK3tEe7DGzNXw="
},
"wayland-0.4.0-dev-lQa1kjfIAQCmhhQu3xF0KH-94-TzeMXOqfnP0-Dg6Wyy": {
"name": "zig_wayland",
"url": "https://codeberg.org/ifreund/zig-wayland/archive/f3c5d503e540ada8cbcb056420de240af0c094f7.tar.gz",
"hash": "sha256-E77GZ15APYbbO1WzmuJi8eG9/iQFbc2CgkNBxjCLUhk="
},
"zigimg-0.1.0-lly-O6N2EABOxke8dqyzCwhtUCAafqP35zC7wsZ4Ddxj": {
"name": "zigimg",
"url": "git+https://github.com/TUSF/zigimg#31268548fe3276c0e95f318a6c0d2ab10565b58d",
"hash": "sha256-oblfr2FIzuqq0FLo/RrzCwUX1NJJuT53EwD3nP3KwN0="
},
"ziglyph-0.11.2-AAAAAHPtHwB4Mbzn1KvOV7Wpjo82NYEc_v0WC8oCLrkf": {
"name": "ziglyph",
"url": "https://deps.files.ghostty.org/ziglyph-b89d43d1e3fb01b6074bc1f7fc980324b04d26a5.tar.gz",
"hash": "sha256-cse98+Ft8QUjX+P88yyYfaxJOJGQ9M7Ymw7jFxDz89k="
},
"N-V-__8AAB0eQwD-0MdOEBmz7intriBReIsIDNlukNVoNu6o": {
"name": "zlib",
"url": "https://deps.files.ghostty.org/zlib-1220fed0c74e1019b3ee29edae2051788b080cd96e90d56836eea857b0b966742efb.tar.gz",
"hash": "sha256-F+iIY/NgBnKrSRgvIXKBtvxNPHYr3jYZNeQ2qVIU0Fw="
}
}

532
build.zig.zon.nix generated
View File

@ -1,22 +1,20 @@
# generated by zon2nix (https://github.com/Cloudef/zig2nix) # generated by zon2nix (https://github.com/jcollie/zon2nix)
{ {
lib, lib,
linkFarm, linkFarm,
fetchurl, fetchurl,
fetchgit, fetchgit,
runCommandLocal, runCommandLocal,
zig, zig_0_14,
name ? "zig-packages", name ? "zig-packages",
}: }: let
with builtins;
with lib; let
unpackZigArtifact = { unpackZigArtifact = {
name, name,
artifact, artifact,
}: }:
runCommandLocal name runCommandLocal name
{ {
nativeBuildInputs = [zig]; nativeBuildInputs = [zig_0_14];
} }
'' ''
hash="$(zig fetch --global-cache-dir "$TMPDIR" ${artifact})" hash="$(zig fetch --global-cache-dir "$TMPDIR" ${artifact})"
@ -38,12 +36,12 @@ with lib; let
url, url,
hash, hash,
}: let }: let
parts = splitString "#" url; parts = lib.splitString "#" url;
url_base = elemAt parts 0; url_base = builtins.elemAt parts 0;
url_without_query = elemAt (splitString "?" url_base) 0; url_without_query = builtins.elemAt (lib.splitString "?" url_base) 0;
rev_base = elemAt parts 1; rev_base = builtins.elemAt parts 1;
rev = rev =
if match "^[a-fA-F0-9]{40}$" rev_base != null if builtins.match "^[a-fA-F0-9]{40}$" rev_base != null
then rev_base then rev_base
else "refs/heads/${rev_base}"; else "refs/heads/${rev_base}";
in in
@ -58,9 +56,9 @@ with lib; let
url, url,
hash, hash,
}: let }: let
parts = splitString "://" url; parts = lib.splitString "://" url;
proto = elemAt parts 0; proto = builtins.elemAt parts 0;
path = elemAt parts 1; path = builtins.elemAt parts 1;
fetcher = { fetcher = {
"git+http" = fetchGitZig { "git+http" = fetchGitZig {
inherit name hash; inherit name hash;
@ -84,215 +82,15 @@ with lib; let
in in
linkFarm name [ linkFarm name [
{ {
name = "1220ebf88622c4d502dc59e71347e4d28c47e033f11b59aff774ae5787565c40999c"; name = "N-V-__8AALw2uwF_03u4JRkZwRLc3Y9hakkYV7NKRR9-RIZJ";
path = fetchZigArtifact { path = fetchZigArtifact {
name = "libxev"; name = "breakpad";
url = "https://github.com/mitchellh/libxev/archive/31eed4e337fed7b0149319e5cdbb62b848c24fbd.tar.gz"; url = "https://deps.files.ghostty.org/breakpad-b99f444ba5f6b98cac261cbb391d8766b34a5918.tar.gz";
hash = "sha256-VHP90NTytIZ8UZsYRKOOxN490/I6yv6ec40sP8y5MJ8="; hash = "sha256-bMqYlD0amQdmzvYQd8Ca/1k4Bj/heh7+EijlQSttatk=";
}; };
} }
{ {
name = "12206ed982e709e565d536ce930701a8c07edfd2cfdce428683f3f2a601d37696a62"; name = "N-V-__8AAIrfdwARSa-zMmxWwFuwpXf1T3asIN7s5jqi9c1v";
path = fetchZigArtifact {
name = "mach_glfw";
url = "https://github.com/mitchellh/mach-glfw/archive/37c2995f31abcf7e8378fba68ddcf4a3faa02de0.tar.gz";
hash = "sha256-HhXIvWUS8/CHWY4VXPG2ZEo+we8XOn3o5rYJCQ1n8Nk=";
};
}
{
name = "1220736fa4ba211162c7a0e46cc8fe04d95921927688bff64ab5da7420d098a7272d";
path = fetchZigArtifact {
name = "glfw";
url = "https://github.com/mitchellh/glfw/archive/b552c6ec47326b94015feddb36058ea567b87159.tar.gz";
hash = "sha256-IeBVAOQmtyFqVxzuXPek1onuPwIamcOyYtxqKpPEQjU=";
};
}
{
name = "12202adbfecdad671d585c9a5bfcbd5cdf821726779430047742ce1bf94ad67d19cb";
path = fetchZigArtifact {
name = "xcode_frameworks";
url = "https://github.com/mitchellh/xcode-frameworks/archive/69801c154c39d7ae6129ea1ba8fe1afe00585fc8.tar.gz";
hash = "sha256-mP/I2coL57UJm/3+4Q8sPAgQwk8V4zM+S4VBBTrX2To=";
};
}
{
name = "122004bfd4c519dadfb8e6281a42fc34fd1aa15aea654ea8a492839046f9894fa2cf";
path = fetchZigArtifact {
name = "vulkan_headers";
url = "https://github.com/mitchellh/vulkan-headers/archive/04c8a0389d5a0236a96312988017cd4ce27d8041.tar.gz";
hash = "sha256-K+zrRudgHFukOM6En1StRYRMNYkeRk+qHTXvrXaG+FU=";
};
}
{
name = "1220b3164434d2ec9db146a40bf3a30f490590d68fa8529776a3138074f0da2c11ca";
path = fetchZigArtifact {
name = "wayland_headers";
url = "https://github.com/mitchellh/wayland-headers/archive/5f991515a29f994d87b908115a2ab0b899474bd1.tar.gz";
hash = "sha256-uFilLZinKkZt6RdVTV3lUmJpzpswDdFva22FvwU/XQI=";
};
}
{
name = "122089c326186c84aa2fd034b16abc38f3ebf4862d9ae106dc1847ac44f557b36465";
path = fetchZigArtifact {
name = "x11_headers";
url = "https://github.com/mitchellh/x11-headers/archive/2ffbd62d82ff73ec929dd8de802bc95effa0ef88.tar.gz";
hash = "sha256-EhV2bmTY/OMYN1wEul35gD0hQgS/Al262jO3pVr0O+c=";
};
}
{
name = "12200df4ebeaed45de26cb2c9f3b6f3746d8013b604e035dae658f86f586c8c91d2f";
path = fetchZigArtifact {
name = "vaxis";
url = "git+https://github.com/rockorager/libvaxis/?ref=main#6d729a2dc3b934818dffe06d2ba3ce02841ed74b";
hash = "sha256-fFf79fCy4QQFVNcN722tSMjB6FyVEzCB36oH1olk9JQ=";
};
}
{
name = "1220dd654ef941fc76fd96f9ec6adadf83f69b9887a0d3f4ee5ac0a1a3e11be35cf5";
path = fetchZigArtifact {
name = "zigimg";
url = "git+https://github.com/zigimg/zigimg#3a667bdb3d7f0955a5a51c8468eac83210c1439e";
hash = "sha256-oLf3YH3yeg4ikVO/GahMCDRMTU31AHkfSnF4rt7xTKo=";
};
}
{
name = "122055beff332830a391e9895c044d33b15ea21063779557024b46169fb1984c6e40";
path = fetchZigArtifact {
name = "zg";
url = "https://codeberg.org/atman/zg/archive/v0.13.2.tar.gz";
hash = "sha256-2x9hT7bYq9KJYWLVOf21a+QvTG/F7HWT+YK15IMRzNY=";
};
}
{
name = "12201f0d542e7541cf492a001d4d0d0155c92f58212fbcb0d224e95edeba06b5416a";
path = fetchZigArtifact {
name = "z2d";
url = "git+https://github.com/vancluever/z2d?ref=v0.4.0#4638bb02a9dc41cc2fb811f092811f6a951c752a";
hash = "sha256-YpWXn1J3JKQSCrWB25mAfzd1/T56QstEZnhPzBwxgoM=";
};
}
{
name = "1220e17e64ef0ef561b3e4b9f3a96a2494285f2ec31c097721bf8c8677ec4415c634";
path = fetchZigArtifact {
name = "zig_objc";
url = "https://github.com/mitchellh/zig-objc/archive/9b8ba849b0f58fe207ecd6ab7c147af55b17556e.tar.gz";
hash = "sha256-H+HIbh2T23uzrsg9/1/vl9Ir1HCAa2pzeTx6zktJH9Q=";
};
}
{
name = "12205a66d423259567764fa0fc60c82be35365c21aeb76c5a7dc99698401f4f6fefc";
path = fetchZigArtifact {
name = "zig_js";
url = "https://github.com/mitchellh/zig-js/archive/d0b8b0a57c52fbc89f9d9fecba75ca29da7dd7d1.tar.gz";
hash = "sha256-fyNeCVbC9UAaKJY6JhAZlT0A479M/AKYMPIWEZbDWD0=";
};
}
{
name = "12207831bce7d4abce57b5a98e8f3635811cfefd160bca022eb91fe905d36a02cf25";
path = fetchZigArtifact {
name = "ziglyph";
url = "https://deps.files.ghostty.org/ziglyph-b89d43d1e3fb01b6074bc1f7fc980324b04d26a5.tar.gz";
hash = "sha256-cse98+Ft8QUjX+P88yyYfaxJOJGQ9M7Ymw7jFxDz89k=";
};
}
{
name = "12209ca054cb1919fa276e328967f10b253f7537c4136eb48f3332b0f7cf661cad38";
path = fetchZigArtifact {
name = "zig_wayland";
url = "https://deps.files.ghostty.org/zig-wayland-fbfe3b4ac0b472a27b1f1a67405436c58cbee12d.tar.gz";
hash = "sha256-RtAystqK/GRYIquTK1KfD7rRSCrfuzAvCD1Z9DE1ldc=";
};
}
{
name = "1220edc3b8d8bedbb50555947987e5e8e2f93871ca3c8e8d4cc8f1377c15b5dd35e8";
path = fetchZigArtifact {
name = "zf";
url = "git+https://github.com/natecraddock/zf/?ref=main#ed99ca18b02dda052e20ba467e90b623c04690dd";
hash = "sha256-t6QNrEJZ4GZZsYixjYvpdrYoCmNbG8TTUmGs2MFa4sU=";
};
}
{
name = "1220c72c1697dd9008461ead702997a15d8a1c5810247f02e7983b9f74c6c6e4c087";
path = fetchZigArtifact {
name = "vaxis";
url = "git+https://github.com/rockorager/libvaxis/?ref=main#dc0a228a5544988d4a920cfb40be9cd28db41423";
hash = "sha256-QWN4jOrA91KlbqmeEHHJ4HTnCC9nmfxt8DHUXJpAzLI=";
};
}
{
name = "12208d70ee791d7ef7e16e1c3c9c1127b57f1ed066a24f87d57fc9f730c5dc394b9d";
path = fetchZigArtifact {
name = "gobject";
url = "https://github.com/ianprime0509/zig-gobject/releases/download/v0.2.2/bindings-gnome47.tar.zst";
hash = "sha256-UU97kNv/bZzQPKz1djhEDLapLguvfBpFfWVb6FthtcI=";
};
}
{
name = "12202cdac858abc52413a6c6711d5026d2d3c8e13f95ca2c327eade0736298bb021f";
path = fetchZigArtifact {
name = "wayland";
url = "https://deps.files.ghostty.org/wayland-9cb3d7aa9dc995ffafdbdef7ab86a949d0fb0e7d.tar.gz";
hash = "sha256-m9G72jdG30KH2yQhNBcBJ46OnekzuX0i2uIOyczkpLk=";
};
}
{
name = "12201a57c6ce0001aa034fa80fba3e1cd2253c560a45748f4f4dd21ff23b491cddef";
path = fetchZigArtifact {
name = "wayland_protocols";
url = "https://deps.files.ghostty.org/wayland-protocols-258d8f88f2c8c25a830c6316f87d23ce1a0f12d9.tar.gz";
hash = "sha256-XO3K3egbdeYPI+XoO13SuOtO+5+Peb16NH0UiusFMPg=";
};
}
{
name = "12207e0851c12acdeee0991e893e0132fc87bb763969a585dc16ecca33e88334c566";
path = fetchZigArtifact {
name = "plasma_wayland_protocols";
url = "git+https://github.com/KDE/plasma-wayland-protocols?ref=main#db525e8f9da548cffa2ac77618dd0fbe7f511b86";
hash = "sha256-iWRv3+OfmHxmeCJ8m0ChjgZX6mwXlcFmK8P/Vt8gDj4=";
};
}
{
name = "12203d2647e5daf36a9c85b969e03f422540786ce9ea624eb4c26d204fe1f46218f3";
path = fetchZigArtifact {
name = "iterm2_themes";
url = "https://github.com/mbadolato/iTerm2-Color-Schemes/archive/db227d159adc265818f2e898da0f70ef8d7b580e.tar.gz";
hash = "sha256-Iyf7U4rpvNkPX4AOEbYSYGte5+SjRwsWD2luOn1Hz8U=";
};
}
{
name = "1220bc6b9daceaf7c8c60f3c3998058045ba0c5c5f48ae255ff97776d9cd8bfc6402";
path = fetchZigArtifact {
name = "imgui";
url = "https://github.com/ocornut/imgui/archive/e391fe2e66eb1c96b1624ae8444dc64c23146ef4.tar.gz";
hash = "sha256-oF/QHgTPEat4Hig4fGIdLkIPHmBEyOJ6JeYD6pnveGA=";
};
}
{
name = "1220b81f6ecfb3fd222f76cf9106fecfa6554ab07ec7fdc4124b9bb063ae2adf969d";
path = fetchZigArtifact {
name = "freetype";
url = "https://github.com/freetype/freetype/archive/refs/tags/VER-2-13-2.tar.gz";
hash = "sha256-QnIB9dUVFnDQXB9bRb713aHy592XHvVPD+qqf/0quQw=";
};
}
{
name = "1220aa013f0c83da3fb64ea6d327f9173fa008d10e28bc9349eac3463457723b1c66";
path = fetchZigArtifact {
name = "libpng";
url = "https://github.com/glennrp/libpng/archive/refs/tags/v1.6.43.tar.gz";
hash = "sha256-/syVtGzwXo4/yKQUdQ4LparQDYnp/fF16U/wQcrxoDo=";
};
}
{
name = "1220fed0c74e1019b3ee29edae2051788b080cd96e90d56836eea857b0b966742efb";
path = fetchZigArtifact {
name = "zlib";
url = "https://github.com/madler/zlib/archive/refs/tags/v1.3.1.tar.gz";
hash = "sha256-F+iIY/NgBnKrSRgvIXKBtvxNPHYr3jYZNeQ2qVIU0Fw=";
};
}
{
name = "12201149afb3326c56c05bb0a577f54f76ac20deece63aa2f5cd6ff31a4fa4fcb3b7";
path = fetchZigArtifact { path = fetchZigArtifact {
name = "fontconfig"; name = "fontconfig";
url = "https://deps.files.ghostty.org/fontconfig-2.14.2.tar.gz"; url = "https://deps.files.ghostty.org/fontconfig-2.14.2.tar.gz";
@ -300,91 +98,259 @@ in
}; };
} }
{ {
name = "122032442d95c3b428ae8e526017fad881e7dc78eab4d558e9a58a80bfbd65a64f7d"; name = "N-V-__8AAKLKpwC4H27Ps_0iL3bPkQb-z6ZVSrB-x_3EEkub";
path = fetchZigArtifact { path = fetchZigArtifact {
name = "libxml2"; name = "freetype";
url = "https://github.com/GNOME/libxml2/archive/refs/tags/v2.11.5.tar.gz"; url = "https://deps.files.ghostty.org/freetype-1220b81f6ecfb3fd222f76cf9106fecfa6554ab07ec7fdc4124b9bb063ae2adf969d.tar.gz";
hash = "sha256-bCgFni4+60K1tLFkieORamNGwQladP7jvGXNxdiaYhU="; hash = "sha256-QnIB9dUVFnDQXB9bRb713aHy592XHvVPD+qqf/0quQw=";
}; };
} }
{ {
name = "1220b8588f106c996af10249bfa092c6fb2f35fbacb1505ef477a0b04a7dd1063122"; name = "N-V-__8AADcZkgn4cMhTUpIz6mShCKyqqB-NBtf_S2bHaTC-";
path = fetchZigArtifact { path = fetchZigArtifact {
name = "harfbuzz"; name = "gettext";
url = "https://github.com/harfbuzz/harfbuzz/archive/refs/tags/8.4.0.tar.gz"; url = "https://deps.files.ghostty.org/gettext-0.24.tar.gz";
hash = "sha256-nxygiYE7BZRK0c6MfgGCEwJtNdybq0gKIeuHaDg5ZVY="; hash = "sha256-yRhQPVk9cNr0hE0XWhPYFq+stmfAb7oeydzVACwVGLc=";
}; };
} }
{ {
name = "12205c83b8311a24b1d5ae6d21640df04f4b0726e314337c043cde1432758cbe165b"; name = "N-V-__8AAMrJSwAUGb9-vTzkNR-5LXS81MR__ZRVfF3tWgG6";
path = fetchZigArtifact { path = fetchZigArtifact {
name = "highway"; name = "glfw";
url = "https://github.com/google/highway/archive/refs/tags/1.1.0.tar.gz"; url = "https://github.com/glfw/glfw/archive/e7ea71be039836da3a98cea55ae5569cb5eb885c.tar.gz";
hash = "sha256-NUqLRTm1iOcLmOxwhEJz4/J0EwLEw3e8xOgbPRhm98k="; hash = "sha256-M3N1XUAlMebBo5X1Py+9YxjKXgZ6eacqWRCbUmwLKQo=";
}; };
} }
{ {
name = "1220c15e72eadd0d9085a8af134904d9a0f5dfcbed5f606ad60edc60ebeccd9706bb"; name = "N-V-__8AABzkUgISeKGgXAzgtutgJsZc0-kkeqBBscJgMkvy";
path = fetchZigArtifact {
name = "oniguruma";
url = "https://github.com/kkos/oniguruma/archive/refs/tags/v6.9.9.tar.gz";
hash = "sha256-ABqhIC54RI9MC/GkjHblVodrNvFtks4yB+zP1h2Z8qA=";
};
}
{
name = "1220446be831adcca918167647c06c7b825849fa3fba5f22da394667974537a9c77e";
path = fetchZigArtifact {
name = "sentry";
url = "https://github.com/getsentry/sentry-native/archive/refs/tags/0.7.8.tar.gz";
hash = "sha256-KsZJfMjWGo0xCT5HrduMmyxFsWsHBbszSoNbZCPDGN8=";
};
}
{
name = "12207fd37bb8251919c112dcdd8f616a491857b34a451f7e4486490077206dc2a1ea";
path = fetchZigArtifact {
name = "breakpad";
url = "https://github.com/getsentry/breakpad/archive/b99f444ba5f6b98cac261cbb391d8766b34a5918.tar.gz";
hash = "sha256-bMqYlD0amQdmzvYQd8Ca/1k4Bj/heh7+EijlQSttatk=";
};
}
{
name = "1220d4d18426ca72fc2b7e56ce47273149815501d0d2395c2a98c726b31ba931e641";
path = fetchZigArtifact {
name = "utfcpp";
url = "https://github.com/nemtrif/utfcpp/archive/refs/tags/v4.0.5.tar.gz";
hash = "sha256-/8ZooxDndgfTk/PBizJxXyI9oerExNbgV5oR345rWc8=";
};
}
{
name = "122037b39d577ec2db3fd7b2130e7b69ef6cc1807d68607a7c232c958315d381b5cd";
path = fetchZigArtifact {
name = "wuffs";
url = "https://github.com/google/wuffs/archive/refs/tags/v0.4.0-alpha.9.tar.gz";
hash = "sha256-nkzSCr6W5sTG7enDBXEIhgEm574uLD41UVR2wlC+HBM=";
};
}
{
name = "12207ff340169c7d40c570b4b6a97db614fe47e0d83b5801a932dcd44917424c8806";
path = fetchZigArtifact {
name = "pixels";
url = "git+https://github.com/make-github-pseudonymous-again/pixels?ref=main#d843c2714d32e15b48b8d7eeb480295af537f877";
hash = "sha256-kXYGO0qn2PfyOYCrRA49BHIgTzdmKhI8SNO1ZKfUYEE=";
};
}
{
name = "12201278a1a05c0ce0b6eb6026c65cd3e9247aa041b1c260324bf29cee559dd23ba1";
path = fetchZigArtifact { path = fetchZigArtifact {
name = "glslang"; name = "glslang";
url = "https://github.com/KhronosGroup/glslang/archive/refs/tags/14.2.0.tar.gz"; url = "https://deps.files.ghostty.org/glslang-12201278a1a05c0ce0b6eb6026c65cd3e9247aa041b1c260324bf29cee559dd23ba1.tar.gz";
hash = "sha256-FKLtu1Ccs+UamlPj9eQ12/WXFgS0uDPmPmB26MCpl7U="; hash = "sha256-FKLtu1Ccs+UamlPj9eQ12/WXFgS0uDPmPmB26MCpl7U=";
}; };
} }
{ {
name = "1220fb3b5586e8be67bc3feb34cbe749cf42a60d628d2953632c2f8141302748c8da"; name = "gobject-0.2.0-Skun7IWDlQAOKu4BV7LapIxL9Imbq1JRmzvcIkazvAxR";
path = fetchZigArtifact {
name = "gobject";
url = "https://github.com/jcollie/ghostty-gobject/releases/download/0.14.0-2025-03-18-21-1/ghostty-gobject-0.14.0-2025-03-18-21-1.tar.zst";
hash = "sha256-hWcpl0Wd3XydT+RY7+VIoxXPhCzele1Ip76YSh+KmLI=";
};
}
{
name = "N-V-__8AALiNBAA-_0gprYr92CjrMj1I5bqNu0TSJOnjFNSr";
path = fetchZigArtifact {
name = "gtk4_layer_shell";
url = "https://deps.files.ghostty.org/gtk4-layer-shell-1.1.0.tar.gz";
hash = "sha256-mChCgSYKXu9bT2OlXxbEv2p4ihAgptsDfssPcfozaYg=";
};
}
{
name = "N-V-__8AAG02ugUcWec-Ndp-i7JTsJ0dgF8nnJRUInkGLG7G";
path = fetchZigArtifact {
name = "harfbuzz";
url = "https://deps.files.ghostty.org/harfbuzz-11.0.0.tar.xz";
hash = "sha256-8WNRuv4hRyX+LB1bWfDZPkmQWkskeJn7kNcM/5U6K5s=";
};
}
{
name = "N-V-__8AAGmZhABbsPJLfbqrh6JTHsXhY6qCaLAQyx25e0XE";
path = fetchZigArtifact {
name = "highway";
url = "https://deps.files.ghostty.org/highway-66486a10623fa0d72fe91260f96c892e41aceb06.tar.gz";
hash = "sha256-h9T4iT704I8iSXNgj/6/lCaKgTgLp5wS6IQZaMgKohI=";
};
}
{
name = "N-V-__8AAH0GaQC8a52s6vfIxg88OZgFgEW6DFxfSK4lX_l3";
path = fetchZigArtifact {
name = "imgui";
url = "https://deps.files.ghostty.org/imgui-1220bc6b9daceaf7c8c60f3c3998058045ba0c5c5f48ae255ff97776d9cd8bfc6402.tar.gz";
hash = "sha256-oF/QHgTPEat4Hig4fGIdLkIPHmBEyOJ6JeYD6pnveGA=";
};
}
{
name = "N-V-__8AAEH8MwQaEsARbyV42-bSZGcu1am8xtg2h67wTFC3";
path = fetchZigArtifact {
name = "iterm2_themes";
url = "https://github.com/mbadolato/iTerm2-Color-Schemes/archive/4c57d8c11d352a4aeda6928b65d78794c28883a5.tar.gz";
hash = "sha256-c+twvkEPiz1DaULYlnGXLxis19Q2h+TgBJxoARMasjU=";
};
}
{
name = "N-V-__8AAJrvXQCqAT8Mg9o_tk6m0yf5Fz-gCNEOKLyTSerD";
path = fetchZigArtifact {
name = "libpng";
url = "https://deps.files.ghostty.org/libpng-1220aa013f0c83da3fb64ea6d327f9173fa008d10e28bc9349eac3463457723b1c66.tar.gz";
hash = "sha256-/syVtGzwXo4/yKQUdQ4LparQDYnp/fF16U/wQcrxoDo=";
};
}
{
name = "libxev-0.0.0-86vtc-ziEgDbLP0vihUn1MhsxNKY4GJEga6BEr7oyHpz";
path = fetchZigArtifact {
name = "libxev";
url = "https://github.com/mitchellh/libxev/archive/3df9337a9e84450a58a2c4af434ec1a036f7b494.tar.gz";
hash = "sha256-oKZqA9d79jHnp/HsqJWQE33Ffn5Ee5G4VnlQepQuY4o=";
};
}
{
name = "N-V-__8AAG3RoQEyRC2Vw7Qoro5SYBf62IHn3HjqtNVY6aWK";
path = fetchZigArtifact {
name = "libxml2";
url = "https://deps.files.ghostty.org/libxml2-2.11.5.tar.gz";
hash = "sha256-bCgFni4+60K1tLFkieORamNGwQladP7jvGXNxdiaYhU=";
};
}
{
name = "N-V-__8AAHjwMQDBXnLq3Q2QhaivE0kE2aD138vtX2Bq1g7c";
path = fetchZigArtifact {
name = "oniguruma";
url = "https://deps.files.ghostty.org/oniguruma-1220c15e72eadd0d9085a8af134904d9a0f5dfcbed5f606ad60edc60ebeccd9706bb.tar.gz";
hash = "sha256-ABqhIC54RI9MC/GkjHblVodrNvFtks4yB+zP1h2Z8qA=";
};
}
{
name = "N-V-__8AADYiAAB_80AWnH1AxXC0tql9thT-R-DYO1gBqTLc";
path = fetchZigArtifact {
name = "pixels";
url = "https://deps.files.ghostty.org/pixels-12207ff340169c7d40c570b4b6a97db614fe47e0d83b5801a932dcd44917424c8806.tar.gz";
hash = "sha256-Veg7FtCRCCUCvxSb9FfzH0IJLFmCZQ4/+657SIcb8Ro=";
};
}
{
name = "N-V-__8AAKYZBAB-CFHBKs3u4JkeiT4BMvyHu3Y5aaWF3Bbs";
path = fetchZigArtifact {
name = "plasma_wayland_protocols";
url = "https://deps.files.ghostty.org/plasma_wayland_protocols-12207e0851c12acdeee0991e893e0132fc87bb763969a585dc16ecca33e88334c566.tar.gz";
hash = "sha256-XFi6IUrNjmvKNCbcCLAixGqN2Zeymhs+KLrfccIN9EE=";
};
}
{
name = "N-V-__8AAPlZGwBEa-gxrcypGBZ2R8Bse4JYSfo_ul8i2jlG";
path = fetchZigArtifact {
name = "sentry";
url = "https://deps.files.ghostty.org/sentry-1220446be831adcca918167647c06c7b825849fa3fba5f22da394667974537a9c77e.tar.gz";
hash = "sha256-KsZJfMjWGo0xCT5HrduMmyxFsWsHBbszSoNbZCPDGN8=";
};
}
{
name = "N-V-__8AANb6pwD7O1WG6L5nvD_rNMvnSc9Cpg1ijSlTYywv";
path = fetchZigArtifact { path = fetchZigArtifact {
name = "spirv_cross"; name = "spirv_cross";
url = "https://github.com/KhronosGroup/SPIRV-Cross/archive/476f384eb7d9e48613c45179e502a15ab95b6b49.tar.gz"; url = "https://deps.files.ghostty.org/spirv_cross-1220fb3b5586e8be67bc3feb34cbe749cf42a60d628d2953632c2f8141302748c8da.tar.gz";
hash = "sha256-tStvz8Ref6abHwahNiwVVHNETizAmZVVaxVsU7pmV+M="; hash = "sha256-tStvz8Ref6abHwahNiwVVHNETizAmZVVaxVsU7pmV+M=";
}; };
} }
{
name = "N-V-__8AAHffAgDU0YQmynL8K35WzkcnMUmBVQHQ0jlcKpjH";
path = fetchZigArtifact {
name = "utfcpp";
url = "https://deps.files.ghostty.org/utfcpp-1220d4d18426ca72fc2b7e56ce47273149815501d0d2395c2a98c726b31ba931e641.tar.gz";
hash = "sha256-/8ZooxDndgfTk/PBizJxXyI9oerExNbgV5oR345rWc8=";
};
}
{
name = "vaxis-0.1.0-BWNV_FUICQAFZnTCL11TUvnUr1Y0_ZdqtXHhd51d76Rn";
path = fetchZigArtifact {
name = "vaxis";
url = "git+https://github.com/rockorager/libvaxis#1f41c121e8fc153d9ce8c6eb64b2bbab68ad7d23";
hash = "sha256-bNZ3oveT6vPChjimPJ/GGfcdivlAeJdl/xfWM+S/MHY=";
};
}
{
name = "N-V-__8AAKrHGAAs2shYq8UkE6bGcR1QJtLTyOE_lcosMn6t";
path = fetchZigArtifact {
name = "wayland";
url = "https://deps.files.ghostty.org/wayland-9cb3d7aa9dc995ffafdbdef7ab86a949d0fb0e7d.tar.gz";
hash = "sha256-6kGR1o5DdnflHzqs3ieCmBAUTpMdOXoyfcYDXiw5xQ0=";
};
}
{
name = "N-V-__8AAKw-DAAaV8bOAAGqA0-oD7o-HNIlPFYKRXSPT03S";
path = fetchZigArtifact {
name = "wayland_protocols";
url = "https://deps.files.ghostty.org/wayland-protocols-258d8f88f2c8c25a830c6316f87d23ce1a0f12d9.tar.gz";
hash = "sha256-XO3K3egbdeYPI+XoO13SuOtO+5+Peb16NH0UiusFMPg=";
};
}
{
name = "N-V-__8AAAzZywE3s51XfsLbP9eyEw57ae9swYB9aGB6fCMs";
path = fetchZigArtifact {
name = "wuffs";
url = "https://deps.files.ghostty.org/wuffs-122037b39d577ec2db3fd7b2130e7b69ef6cc1807d68607a7c232c958315d381b5cd.tar.gz";
hash = "sha256-nkzSCr6W5sTG7enDBXEIhgEm574uLD41UVR2wlC+HBM=";
};
}
{
name = "z2d-0.6.0-j5P_HvLdCABu-dXpCeRM7Uk4m16vULg1980lMNCQj4_C";
path = fetchZigArtifact {
name = "z2d";
url = "https://github.com/vancluever/z2d/archive/1e89605a624940c310c7a1d81b46a7c5c05919e3.tar.gz";
hash = "sha256-PEKVSUZ6teRbDyhFPWSiuBSe40pgr0kVRivIY8Cn8HQ=";
};
}
{
name = "zf-0.10.3-OIRy8aiIAACLrBllz0zjxaH0aOe5oNm3KtEMyCntST-9";
path = fetchZigArtifact {
name = "zf";
url = "https://github.com/natecraddock/zf/archive/7aacbe6d155d64d15937ca95ca6c014905eb531f.tar.gz";
hash = "sha256-3nulNQd/4rZ4paeXJYXwAliNNyRNsIOX/q3z1JB8C7I=";
};
}
{
name = "zg-0.13.4-AAAAAGiZ7QLz4pvECFa_wG4O4TP4FLABHHbemH2KakWM";
path = fetchZigArtifact {
name = "zg";
url = "git+https://codeberg.org/atman/zg#4a002763419a34d61dcbb1f415821b83b9bf8ddc";
hash = "sha256-fo3l6cjkrr/godElTGnQzalBsasN7J73IDIRmw7v1gA=";
};
}
{
name = "N-V-__8AAB9YCQBaZtQjJZVndk-g_GDIK-NTZcIa63bFp9yZ";
path = fetchZigArtifact {
name = "zig_js";
url = "https://deps.files.ghostty.org/zig_js-12205a66d423259567764fa0fc60c82be35365c21aeb76c5a7dc99698401f4f6fefc.tar.gz";
hash = "sha256-fyNeCVbC9UAaKJY6JhAZlT0A479M/AKYMPIWEZbDWD0=";
};
}
{
name = "zig_objc-0.0.0-Ir_Sp3TyAADEVRTxXlScq3t_uKAM91MYNerZkHfbD0yt";
path = fetchZigArtifact {
name = "zig_objc";
url = "https://github.com/mitchellh/zig-objc/archive/3ab0d37c7d6b933d6ded1b3a35b6b60f05590a98.tar.gz";
hash = "sha256-zn1tR6xhSmDla4UJ3t+Gni4Ni3R8deSK3tEe7DGzNXw=";
};
}
{
name = "wayland-0.4.0-dev-lQa1kjfIAQCmhhQu3xF0KH-94-TzeMXOqfnP0-Dg6Wyy";
path = fetchZigArtifact {
name = "zig_wayland";
url = "https://codeberg.org/ifreund/zig-wayland/archive/f3c5d503e540ada8cbcb056420de240af0c094f7.tar.gz";
hash = "sha256-E77GZ15APYbbO1WzmuJi8eG9/iQFbc2CgkNBxjCLUhk=";
};
}
{
name = "zigimg-0.1.0-lly-O6N2EABOxke8dqyzCwhtUCAafqP35zC7wsZ4Ddxj";
path = fetchZigArtifact {
name = "zigimg";
url = "git+https://github.com/TUSF/zigimg#31268548fe3276c0e95f318a6c0d2ab10565b58d";
hash = "sha256-oblfr2FIzuqq0FLo/RrzCwUX1NJJuT53EwD3nP3KwN0=";
};
}
{
name = "ziglyph-0.11.2-AAAAAHPtHwB4Mbzn1KvOV7Wpjo82NYEc_v0WC8oCLrkf";
path = fetchZigArtifact {
name = "ziglyph";
url = "https://deps.files.ghostty.org/ziglyph-b89d43d1e3fb01b6074bc1f7fc980324b04d26a5.tar.gz";
hash = "sha256-cse98+Ft8QUjX+P88yyYfaxJOJGQ9M7Ymw7jFxDz89k=";
};
}
{
name = "N-V-__8AAB0eQwD-0MdOEBmz7intriBReIsIDNlukNVoNu6o";
path = fetchZigArtifact {
name = "zlib";
url = "https://deps.files.ghostty.org/zlib-1220fed0c74e1019b3ee29edae2051788b080cd96e90d56836eea857b0b966742efb.tar.gz";
hash = "sha256-F+iIY/NgBnKrSRgvIXKBtvxNPHYr3jYZNeQ2qVIU0Fw=";
};
}
] ]

34
build.zig.zon.txt generated Normal file
View File

@ -0,0 +1,34 @@
git+https://codeberg.org/atman/zg#4a002763419a34d61dcbb1f415821b83b9bf8ddc
git+https://github.com/TUSF/zigimg#31268548fe3276c0e95f318a6c0d2ab10565b58d
git+https://github.com/rockorager/libvaxis#1f41c121e8fc153d9ce8c6eb64b2bbab68ad7d23
https://codeberg.org/ifreund/zig-wayland/archive/f3c5d503e540ada8cbcb056420de240af0c094f7.tar.gz
https://deps.files.ghostty.org/breakpad-b99f444ba5f6b98cac261cbb391d8766b34a5918.tar.gz
https://deps.files.ghostty.org/fontconfig-2.14.2.tar.gz
https://deps.files.ghostty.org/freetype-1220b81f6ecfb3fd222f76cf9106fecfa6554ab07ec7fdc4124b9bb063ae2adf969d.tar.gz
https://deps.files.ghostty.org/gettext-0.24.tar.gz
https://deps.files.ghostty.org/glslang-12201278a1a05c0ce0b6eb6026c65cd3e9247aa041b1c260324bf29cee559dd23ba1.tar.gz
https://deps.files.ghostty.org/gtk4-layer-shell-1.1.0.tar.gz
https://deps.files.ghostty.org/harfbuzz-11.0.0.tar.xz
https://deps.files.ghostty.org/highway-66486a10623fa0d72fe91260f96c892e41aceb06.tar.gz
https://deps.files.ghostty.org/imgui-1220bc6b9daceaf7c8c60f3c3998058045ba0c5c5f48ae255ff97776d9cd8bfc6402.tar.gz
https://deps.files.ghostty.org/libpng-1220aa013f0c83da3fb64ea6d327f9173fa008d10e28bc9349eac3463457723b1c66.tar.gz
https://deps.files.ghostty.org/libxml2-2.11.5.tar.gz
https://deps.files.ghostty.org/oniguruma-1220c15e72eadd0d9085a8af134904d9a0f5dfcbed5f606ad60edc60ebeccd9706bb.tar.gz
https://deps.files.ghostty.org/pixels-12207ff340169c7d40c570b4b6a97db614fe47e0d83b5801a932dcd44917424c8806.tar.gz
https://deps.files.ghostty.org/plasma_wayland_protocols-12207e0851c12acdeee0991e893e0132fc87bb763969a585dc16ecca33e88334c566.tar.gz
https://deps.files.ghostty.org/sentry-1220446be831adcca918167647c06c7b825849fa3fba5f22da394667974537a9c77e.tar.gz
https://deps.files.ghostty.org/spirv_cross-1220fb3b5586e8be67bc3feb34cbe749cf42a60d628d2953632c2f8141302748c8da.tar.gz
https://deps.files.ghostty.org/utfcpp-1220d4d18426ca72fc2b7e56ce47273149815501d0d2395c2a98c726b31ba931e641.tar.gz
https://deps.files.ghostty.org/wayland-9cb3d7aa9dc995ffafdbdef7ab86a949d0fb0e7d.tar.gz
https://deps.files.ghostty.org/wayland-protocols-258d8f88f2c8c25a830c6316f87d23ce1a0f12d9.tar.gz
https://deps.files.ghostty.org/wuffs-122037b39d577ec2db3fd7b2130e7b69ef6cc1807d68607a7c232c958315d381b5cd.tar.gz
https://deps.files.ghostty.org/zig_js-12205a66d423259567764fa0fc60c82be35365c21aeb76c5a7dc99698401f4f6fefc.tar.gz
https://deps.files.ghostty.org/ziglyph-b89d43d1e3fb01b6074bc1f7fc980324b04d26a5.tar.gz
https://deps.files.ghostty.org/zlib-1220fed0c74e1019b3ee29edae2051788b080cd96e90d56836eea857b0b966742efb.tar.gz
https://github.com/glfw/glfw/archive/e7ea71be039836da3a98cea55ae5569cb5eb885c.tar.gz
https://github.com/jcollie/ghostty-gobject/releases/download/0.14.0-2025-03-18-21-1/ghostty-gobject-0.14.0-2025-03-18-21-1.tar.zst
https://github.com/mbadolato/iTerm2-Color-Schemes/archive/4c57d8c11d352a4aeda6928b65d78794c28883a5.tar.gz
https://github.com/mitchellh/libxev/archive/3df9337a9e84450a58a2c4af434ec1a036f7b494.tar.gz
https://github.com/mitchellh/zig-objc/archive/3ab0d37c7d6b933d6ded1b3a35b6b60f05590a98.tar.gz
https://github.com/natecraddock/zf/archive/7aacbe6d155d64d15937ca95ca6c014905eb531f.tar.gz
https://github.com/vancluever/z2d/archive/1e89605a624940c310c7a1d81b46a7c5c05919e3.tar.gz

36
flake.lock generated
View File

@ -36,11 +36,11 @@
}, },
"nixpkgs-stable": { "nixpkgs-stable": {
"locked": { "locked": {
"lastModified": 1738255539, "lastModified": 1741992157,
"narHash": "sha256-hP2eOqhIO/OILW+3moNWO4GtdJFYCqAe9yJZgvlCoDQ=", "narHash": "sha256-nlIfTsTrMSksEJc1f7YexXiPVuzD1gOfeN1ggwZyUoc=",
"owner": "nixos", "owner": "nixos",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "c3511a3b53b482aa7547c9d1626fd7310c1de1c5", "rev": "da4b122f63095ca1199bd4d526f9e26426697689",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -52,11 +52,11 @@
}, },
"nixpkgs-unstable": { "nixpkgs-unstable": {
"locked": { "locked": {
"lastModified": 1738136902, "lastModified": 1741865919,
"narHash": "sha256-pUvLijVGARw4u793APze3j6mU1Zwdtz7hGkGGkD87qw=", "narHash": "sha256-4thdbnP6dlbdq+qZWTsm4ffAwoS8Tiq1YResB+RP6WE=",
"owner": "nixos", "owner": "nixos",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "9a5db3142ce450045840cc8d832b13b8a2018e0c", "rev": "573c650e8a14b2faa0041645ab18aed7e60f0c9a",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -73,7 +73,7 @@
"nixpkgs-stable": "nixpkgs-stable", "nixpkgs-stable": "nixpkgs-stable",
"nixpkgs-unstable": "nixpkgs-unstable", "nixpkgs-unstable": "nixpkgs-unstable",
"zig": "zig", "zig": "zig",
"zig2nix": "zig2nix" "zon2nix": "zon2nix"
} }
}, },
"systems": { "systems": {
@ -102,11 +102,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1738239110, "lastModified": 1741825901,
"narHash": "sha256-Y5i9mQ++dyIQr+zEPNy+KIbc5wjPmfllBrag3cHZgcE=", "narHash": "sha256-aeopo+aXg5I2IksOPFN79usw7AeimH1+tjfuMzJHFdk=",
"owner": "mitchellh", "owner": "mitchellh",
"repo": "zig-overlay", "repo": "zig-overlay",
"rev": "1a8fb6f3a04724519436355564b95fce5e272504", "rev": "0b14285e283f5a747f372fb2931835dd937c4383",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -115,27 +115,27 @@
"type": "github" "type": "github"
} }
}, },
"zig2nix": { "zon2nix": {
"inputs": { "inputs": {
"flake-utils": [ "flake-utils": [
"flake-utils" "flake-utils"
], ],
"nixpkgs": [ "nixpkgs": [
"nixpkgs-stable" "nixpkgs-unstable"
] ]
}, },
"locked": { "locked": {
"lastModified": 1738263917, "lastModified": 1742104771,
"narHash": "sha256-j/3fwe2pEOquHabP/puljOKwAZFjIE9gXZqA91sC48M=", "narHash": "sha256-LhidlyEA9MP8jGe1rEnyjGFCzLLgCdDpYeWggibayr0=",
"owner": "jcollie", "owner": "jcollie",
"repo": "zig2nix", "repo": "zon2nix",
"rev": "c311d8e77a6ee0d995f40a6e10a89a3a4ab04f9a", "rev": "56c159be489cc6c0e73c3930bd908ddc6fe89613",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "jcollie", "owner": "jcollie",
"ref": "c311d8e77a6ee0d995f40a6e10a89a3a4ab04f9a", "ref": "56c159be489cc6c0e73c3930bd908ddc6fe89613",
"repo": "zig2nix", "repo": "zon2nix",
"type": "github" "type": "github"
} }
} }

View File

@ -25,10 +25,10 @@
}; };
}; };
zig2nix = { zon2nix = {
url = "github:jcollie/zig2nix?ref=c311d8e77a6ee0d995f40a6e10a89a3a4ab04f9a"; url = "github:jcollie/zon2nix?ref=56c159be489cc6c0e73c3930bd908ddc6fe89613";
inputs = { inputs = {
nixpkgs.follows = "nixpkgs-stable"; nixpkgs.follows = "nixpkgs-unstable";
flake-utils.follows = "flake-utils"; flake-utils.follows = "flake-utils";
}; };
}; };
@ -39,7 +39,7 @@
nixpkgs-unstable, nixpkgs-unstable,
nixpkgs-stable, nixpkgs-stable,
zig, zig,
zig2nix, zon2nix,
... ...
}: }:
builtins.foldl' nixpkgs-stable.lib.recursiveUpdate {} ( builtins.foldl' nixpkgs-stable.lib.recursiveUpdate {} (
@ -49,9 +49,12 @@
pkgs-unstable = nixpkgs-unstable.legacyPackages.${system}; pkgs-unstable = nixpkgs-unstable.legacyPackages.${system};
in { in {
devShell.${system} = pkgs-stable.callPackage ./nix/devShell.nix { devShell.${system} = pkgs-stable.callPackage ./nix/devShell.nix {
zig = zig.packages.${system}."0.13.0"; zig = zig.packages.${system}."0.14.0";
wraptest = pkgs-stable.callPackage ./nix/wraptest.nix {}; wraptest = pkgs-stable.callPackage ./nix/wraptest.nix {};
zig2nix = zig2nix; uv = pkgs-unstable.uv;
# remove once blueprint-compiler 0.16.0 is in the stable nixpkgs
blueprint-compiler = pkgs-unstable.blueprint-compiler;
zon2nix = zon2nix;
}; };
packages.${system} = let packages.${system} = let
@ -61,10 +64,10 @@
revision = self.shortRev or self.dirtyShortRev or "dirty"; revision = self.shortRev or self.dirtyShortRev or "dirty";
}; };
in rec { in rec {
deps = pkgs-stable.callPackage ./build.zig.zon.nix {}; deps = pkgs-unstable.callPackage ./build.zig.zon.nix {};
ghostty-debug = pkgs-stable.callPackage ./nix/package.nix (mkArgs "Debug"); ghostty-debug = pkgs-unstable.callPackage ./nix/package.nix (mkArgs "Debug");
ghostty-releasesafe = pkgs-stable.callPackage ./nix/package.nix (mkArgs "ReleaseSafe"); ghostty-releasesafe = pkgs-unstable.callPackage ./nix/package.nix (mkArgs "ReleaseSafe");
ghostty-releasefast = pkgs-stable.callPackage ./nix/package.nix (mkArgs "ReleaseFast"); ghostty-releasefast = pkgs-unstable.callPackage ./nix/package.nix (mkArgs "ReleaseFast");
ghostty = ghostty-releasefast; ghostty = ghostty-releasefast;
default = ghostty; default = ghostty;
@ -77,14 +80,14 @@
module: let module: let
vm = import ./nix/vm/create.nix { vm = import ./nix/vm/create.nix {
inherit system module; inherit system module;
nixpkgs = nixpkgs-stable; nixpkgs = nixpkgs-unstable;
overlay = self.overlays.debug; overlay = self.overlays.debug;
}; };
program = pkgs-stable.writeShellScript "run-ghostty-vm" '' program = pkgs-unstable.writeShellScript "run-ghostty-vm" ''
SHARED_DIR=$(pwd) SHARED_DIR=$(pwd)
export SHARED_DIR export SHARED_DIR
${pkgs-stable.lib.getExe vm.config.system.build.vm} "$@" ${pkgs-unstable.lib.getExe vm.config.system.build.vm} "$@"
''; '';
in { in {
type = "app"; type = "app";

View File

@ -254,8 +254,10 @@ typedef enum {
typedef struct { typedef struct {
ghostty_input_action_e action; ghostty_input_action_e action;
ghostty_input_mods_e mods; ghostty_input_mods_e mods;
ghostty_input_mods_e consumed_mods;
uint32_t keycode; uint32_t keycode;
const char* text; const char* text;
uint32_t unshifted_codepoint;
bool composing; bool composing;
} ghostty_input_key_s; } ghostty_input_key_s;
@ -412,6 +414,7 @@ typedef enum {
GHOSTTY_FULLSCREEN_NATIVE, GHOSTTY_FULLSCREEN_NATIVE,
GHOSTTY_FULLSCREEN_NON_NATIVE, GHOSTTY_FULLSCREEN_NON_NATIVE,
GHOSTTY_FULLSCREEN_NON_NATIVE_VISIBLE_MENU, GHOSTTY_FULLSCREEN_NON_NATIVE_VISIBLE_MENU,
GHOSTTY_FULLSCREEN_NON_NATIVE_PADDED_NOTCH,
} ghostty_action_fullscreen_e; } ghostty_action_fullscreen_e;
// apprt.action.SecureInput // apprt.action.SecureInput
@ -579,12 +582,14 @@ typedef enum {
GHOSTTY_ACTION_TOGGLE_SPLIT_ZOOM, GHOSTTY_ACTION_TOGGLE_SPLIT_ZOOM,
GHOSTTY_ACTION_PRESENT_TERMINAL, GHOSTTY_ACTION_PRESENT_TERMINAL,
GHOSTTY_ACTION_SIZE_LIMIT, GHOSTTY_ACTION_SIZE_LIMIT,
GHOSTTY_ACTION_RESET_WINDOW_SIZE,
GHOSTTY_ACTION_INITIAL_SIZE, GHOSTTY_ACTION_INITIAL_SIZE,
GHOSTTY_ACTION_CELL_SIZE, GHOSTTY_ACTION_CELL_SIZE,
GHOSTTY_ACTION_INSPECTOR, GHOSTTY_ACTION_INSPECTOR,
GHOSTTY_ACTION_RENDER_INSPECTOR, GHOSTTY_ACTION_RENDER_INSPECTOR,
GHOSTTY_ACTION_DESKTOP_NOTIFICATION, GHOSTTY_ACTION_DESKTOP_NOTIFICATION,
GHOSTTY_ACTION_SET_TITLE, GHOSTTY_ACTION_SET_TITLE,
GHOSTTY_ACTION_PROMPT_TITLE,
GHOSTTY_ACTION_PWD, GHOSTTY_ACTION_PWD,
GHOSTTY_ACTION_MOUSE_SHAPE, GHOSTTY_ACTION_MOUSE_SHAPE,
GHOSTTY_ACTION_MOUSE_VISIBILITY, GHOSTTY_ACTION_MOUSE_VISIBILITY,
@ -597,6 +602,8 @@ typedef enum {
GHOSTTY_ACTION_COLOR_CHANGE, GHOSTTY_ACTION_COLOR_CHANGE,
GHOSTTY_ACTION_RELOAD_CONFIG, GHOSTTY_ACTION_RELOAD_CONFIG,
GHOSTTY_ACTION_CONFIG_CHANGE, GHOSTTY_ACTION_CONFIG_CHANGE,
GHOSTTY_ACTION_CLOSE_WINDOW,
GHOSTTY_ACTION_RING_BELL,
} ghostty_action_tag_e; } ghostty_action_tag_e;
typedef union { typedef union {
@ -665,6 +672,7 @@ typedef struct {
int ghostty_init(void); int ghostty_init(void);
void ghostty_cli_main(uintptr_t, char**); void ghostty_cli_main(uintptr_t, char**);
ghostty_info_s ghostty_info(void); ghostty_info_s ghostty_info(void);
const char* ghostty_translate(const char*);
ghostty_config_t ghostty_config_new(); ghostty_config_t ghostty_config_new();
void ghostty_config_free(ghostty_config_t); void ghostty_config_free(ghostty_config_t);
@ -719,6 +727,7 @@ ghostty_input_mods_e ghostty_surface_key_translation_mods(ghostty_surface_t,
bool ghostty_surface_key(ghostty_surface_t, ghostty_input_key_s); bool ghostty_surface_key(ghostty_surface_t, ghostty_input_key_s);
bool ghostty_surface_key_is_binding(ghostty_surface_t, ghostty_input_key_s); bool ghostty_surface_key_is_binding(ghostty_surface_t, ghostty_input_key_s);
void ghostty_surface_text(ghostty_surface_t, const char*, uintptr_t); void ghostty_surface_text(ghostty_surface_t, const char*, uintptr_t);
void ghostty_surface_preedit(ghostty_surface_t, const char*, uintptr_t);
bool ghostty_surface_mouse_captured(ghostty_surface_t); bool ghostty_surface_mouse_captured(ghostty_surface_t);
bool ghostty_surface_mouse_button(ghostty_surface_t, bool ghostty_surface_mouse_button(ghostty_surface_t,
ghostty_input_mouse_state_e, ghostty_input_mouse_state_e,

View File

@ -40,6 +40,7 @@
A53D0C952B53B4D800305CE6 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A5B30538299BEAAB0047F10C /* Assets.xcassets */; }; A53D0C952B53B4D800305CE6 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A5B30538299BEAAB0047F10C /* Assets.xcassets */; };
A53D0C9B2B543F3B00305CE6 /* Ghostty.App.swift in Sources */ = {isa = PBXBuildFile; fileRef = A53D0C992B543F3B00305CE6 /* Ghostty.App.swift */; }; A53D0C9B2B543F3B00305CE6 /* Ghostty.App.swift in Sources */ = {isa = PBXBuildFile; fileRef = A53D0C992B543F3B00305CE6 /* Ghostty.App.swift */; };
A53D0C9C2B543F7B00305CE6 /* Package.swift in Sources */ = {isa = PBXBuildFile; fileRef = A55B7BB729B6F53A0055DE60 /* Package.swift */; }; A53D0C9C2B543F7B00305CE6 /* Package.swift in Sources */ = {isa = PBXBuildFile; fileRef = A55B7BB729B6F53A0055DE60 /* Package.swift */; };
A546F1142D7B68D7003B11A0 /* locale in Resources */ = {isa = PBXBuildFile; fileRef = A546F1132D7B68D7003B11A0 /* locale */; };
A54B0CE92D0CECD100CBEFF8 /* ColorizedGhosttyIconView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54B0CE82D0CECD100CBEFF8 /* ColorizedGhosttyIconView.swift */; }; A54B0CE92D0CECD100CBEFF8 /* ColorizedGhosttyIconView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54B0CE82D0CECD100CBEFF8 /* ColorizedGhosttyIconView.swift */; };
A54B0CEB2D0CFB4C00CBEFF8 /* NSImage+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54B0CEA2D0CFB4A00CBEFF8 /* NSImage+Extension.swift */; }; A54B0CEB2D0CFB4C00CBEFF8 /* NSImage+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54B0CEA2D0CFB4A00CBEFF8 /* NSImage+Extension.swift */; };
A54B0CED2D0CFB7700CBEFF8 /* ColorizedGhosttyIcon.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54B0CEC2D0CFB7300CBEFF8 /* ColorizedGhosttyIcon.swift */; }; A54B0CED2D0CFB7700CBEFF8 /* ColorizedGhosttyIcon.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54B0CEC2D0CFB7300CBEFF8 /* ColorizedGhosttyIcon.swift */; };
@ -54,6 +55,8 @@
A571AB1D2A206FCF00248498 /* GhosttyKit.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = A5D495A1299BEC7E00DD1313 /* GhosttyKit.xcframework */; }; A571AB1D2A206FCF00248498 /* GhosttyKit.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = A5D495A1299BEC7E00DD1313 /* GhosttyKit.xcframework */; };
A57D79272C9C879B001D522E /* SecureInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = A57D79262C9C8798001D522E /* SecureInput.swift */; }; A57D79272C9C879B001D522E /* SecureInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = A57D79262C9C8798001D522E /* SecureInput.swift */; };
A586167C2B7703CC009BDB1D /* fish in Resources */ = {isa = PBXBuildFile; fileRef = A586167B2B7703CC009BDB1D /* fish */; }; A586167C2B7703CC009BDB1D /* fish in Resources */ = {isa = PBXBuildFile; fileRef = A586167B2B7703CC009BDB1D /* fish */; };
A5874D992DAD751B00E83852 /* CGS.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5874D982DAD751A00E83852 /* CGS.swift */; };
A5874D9D2DAD786100E83852 /* NSWindow+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5874D9C2DAD785F00E83852 /* NSWindow+Extension.swift */; };
A59444F729A2ED5200725BBA /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A59444F629A2ED5200725BBA /* SettingsView.swift */; }; A59444F729A2ED5200725BBA /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A59444F629A2ED5200725BBA /* SettingsView.swift */; };
A59630972AEE163600D64628 /* HostingWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = A59630962AEE163600D64628 /* HostingWindow.swift */; }; A59630972AEE163600D64628 /* HostingWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = A59630962AEE163600D64628 /* HostingWindow.swift */; };
A596309A2AEE1C6400D64628 /* Terminal.xib in Resources */ = {isa = PBXBuildFile; fileRef = A59630992AEE1C6400D64628 /* Terminal.xib */; }; A596309A2AEE1C6400D64628 /* Terminal.xib in Resources */ = {isa = PBXBuildFile; fileRef = A59630992AEE1C6400D64628 /* Terminal.xib */; };
@ -138,6 +141,7 @@
A53A6C022CCC1B7D00943E98 /* Ghostty.Action.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ghostty.Action.swift; sourceTree = "<group>"; }; A53A6C022CCC1B7D00943E98 /* Ghostty.Action.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ghostty.Action.swift; sourceTree = "<group>"; };
A53D0C932B53B43700305CE6 /* iOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iOSApp.swift; sourceTree = "<group>"; }; A53D0C932B53B43700305CE6 /* iOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iOSApp.swift; sourceTree = "<group>"; };
A53D0C992B543F3B00305CE6 /* Ghostty.App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ghostty.App.swift; sourceTree = "<group>"; }; A53D0C992B543F3B00305CE6 /* Ghostty.App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ghostty.App.swift; sourceTree = "<group>"; };
A546F1132D7B68D7003B11A0 /* locale */ = {isa = PBXFileReference; lastKnownFileType = folder; name = locale; path = "../zig-out/share/locale"; sourceTree = "<group>"; };
A54B0CE82D0CECD100CBEFF8 /* ColorizedGhosttyIconView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorizedGhosttyIconView.swift; sourceTree = "<group>"; }; A54B0CE82D0CECD100CBEFF8 /* ColorizedGhosttyIconView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorizedGhosttyIconView.swift; sourceTree = "<group>"; };
A54B0CEA2D0CFB4A00CBEFF8 /* NSImage+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSImage+Extension.swift"; sourceTree = "<group>"; }; A54B0CEA2D0CFB4A00CBEFF8 /* NSImage+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSImage+Extension.swift"; sourceTree = "<group>"; };
A54B0CEC2D0CFB7300CBEFF8 /* ColorizedGhosttyIcon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorizedGhosttyIcon.swift; sourceTree = "<group>"; }; A54B0CEC2D0CFB7300CBEFF8 /* ColorizedGhosttyIcon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorizedGhosttyIcon.swift; sourceTree = "<group>"; };
@ -152,6 +156,8 @@
A571AB1C2A206FC600248498 /* Ghostty-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "Ghostty-Info.plist"; sourceTree = "<group>"; }; A571AB1C2A206FC600248498 /* Ghostty-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "Ghostty-Info.plist"; sourceTree = "<group>"; };
A57D79262C9C8798001D522E /* SecureInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureInput.swift; sourceTree = "<group>"; }; A57D79262C9C8798001D522E /* SecureInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecureInput.swift; sourceTree = "<group>"; };
A586167B2B7703CC009BDB1D /* fish */ = {isa = PBXFileReference; lastKnownFileType = folder; name = fish; path = "../zig-out/share/fish"; sourceTree = "<group>"; }; A586167B2B7703CC009BDB1D /* fish */ = {isa = PBXFileReference; lastKnownFileType = folder; name = fish; path = "../zig-out/share/fish"; sourceTree = "<group>"; };
A5874D982DAD751A00E83852 /* CGS.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CGS.swift; sourceTree = "<group>"; };
A5874D9C2DAD785F00E83852 /* NSWindow+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSWindow+Extension.swift"; sourceTree = "<group>"; };
A59444F629A2ED5200725BBA /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; }; A59444F629A2ED5200725BBA /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
A59630962AEE163600D64628 /* HostingWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostingWindow.swift; sourceTree = "<group>"; }; A59630962AEE163600D64628 /* HostingWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostingWindow.swift; sourceTree = "<group>"; };
A59630992AEE1C6400D64628 /* Terminal.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = Terminal.xib; sourceTree = "<group>"; }; A59630992AEE1C6400D64628 /* Terminal.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = Terminal.xib; sourceTree = "<group>"; };
@ -272,13 +278,13 @@
A534263D2A7DCBB000EBB7A2 /* Helpers */ = { A534263D2A7DCBB000EBB7A2 /* Helpers */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
A5874D9B2DAD781100E83852 /* Private */,
A5AEB1642D5BE7BF00513529 /* LastWindowPosition.swift */, A5AEB1642D5BE7BF00513529 /* LastWindowPosition.swift */,
A5A6F7292CC41B8700B232A5 /* Xcode.swift */, A5A6F7292CC41B8700B232A5 /* Xcode.swift */,
A5CEAFFE29C2410700646FDA /* Backport.swift */, A5CEAFFE29C2410700646FDA /* Backport.swift */,
A5333E1B2B5A1CE3008AEFF7 /* CrossKit.swift */, A5333E1B2B5A1CE3008AEFF7 /* CrossKit.swift */,
A5CBD0572C9F30860017A1AE /* Cursor.swift */, A5CBD0572C9F30860017A1AE /* Cursor.swift */,
A5D0AF3C2B37804400D21823 /* CodableBridge.swift */, A5D0AF3C2B37804400D21823 /* CodableBridge.swift */,
A5A2A3C92D4445E20033CF96 /* Dock.swift */,
A52FFF582CAA4FF1000C6A5B /* Fullscreen.swift */, A52FFF582CAA4FF1000C6A5B /* Fullscreen.swift */,
A59630962AEE163600D64628 /* HostingWindow.swift */, A59630962AEE163600D64628 /* HostingWindow.swift */,
A5CA378B2D2A4DE800931030 /* KeyboardLayout.swift */, A5CA378B2D2A4DE800931030 /* KeyboardLayout.swift */,
@ -291,6 +297,7 @@
A52FFF5C2CAB4D05000C6A5B /* NSScreen+Extension.swift */, A52FFF5C2CAB4D05000C6A5B /* NSScreen+Extension.swift */,
C1F26EA62B738B9900404083 /* NSView+Extension.swift */, C1F26EA62B738B9900404083 /* NSView+Extension.swift */,
AEE8B3442B9AA39600260C5E /* NSPasteboard+Extension.swift */, AEE8B3442B9AA39600260C5E /* NSPasteboard+Extension.swift */,
A5874D9C2DAD785F00E83852 /* NSWindow+Extension.swift */,
A5985CD62C320C4500C57AD3 /* String+Extension.swift */, A5985CD62C320C4500C57AD3 /* String+Extension.swift */,
A5CC36142C9CDA03004D6760 /* View+Extension.swift */, A5CC36142C9CDA03004D6760 /* View+Extension.swift */,
A5CA378D2D31D6C100931030 /* Weak.swift */, A5CA378D2D31D6C100931030 /* Weak.swift */,
@ -401,6 +408,15 @@
path = "Secure Input"; path = "Secure Input";
sourceTree = "<group>"; sourceTree = "<group>";
}; };
A5874D9B2DAD781100E83852 /* Private */ = {
isa = PBXGroup;
children = (
A5874D982DAD751A00E83852 /* CGS.swift */,
A5A2A3C92D4445E20033CF96 /* Dock.swift */,
);
path = Private;
sourceTree = "<group>";
};
A59630982AEE1C4400D64628 /* Terminal */ = { A59630982AEE1C4400D64628 /* Terminal */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
@ -424,6 +440,7 @@
29C15B1C2CDC3B2000520DD4 /* bat */, 29C15B1C2CDC3B2000520DD4 /* bat */,
A586167B2B7703CC009BDB1D /* fish */, A586167B2B7703CC009BDB1D /* fish */,
55154BDF2B33911F001622DC /* ghostty */, 55154BDF2B33911F001622DC /* ghostty */,
A546F1132D7B68D7003B11A0 /* locale */,
A5985CE52C33060F00C57AD3 /* man */, A5985CE52C33060F00C57AD3 /* man */,
9351BE8E2D22937F003B3499 /* nvim */, 9351BE8E2D22937F003B3499 /* nvim */,
A5A1F8842A489D6800D1E8BC /* terminfo */, A5A1F8842A489D6800D1E8BC /* terminfo */,
@ -593,20 +610,21 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
FC9ABA9C2D0F53F80020D4C8 /* bash-completion in Resources */, FC9ABA9C2D0F53F80020D4C8 /* bash-completion in Resources */,
29C15B1D2CDC3B2900520DD4 /* bat in Resources */,
A586167C2B7703CC009BDB1D /* fish in Resources */,
55154BE02B33911F001622DC /* ghostty in Resources */,
A546F1142D7B68D7003B11A0 /* locale in Resources */,
A5985CE62C33060F00C57AD3 /* man in Resources */,
9351BE8E3D22937F003B3499 /* nvim in Resources */,
A5A1F8852A489D6800D1E8BC /* terminfo in Resources */,
552964E62B34A9B400030505 /* vim in Resources */,
FC5218FA2D10FFCE004C93E0 /* zsh in Resources */,
A5B30539299BEAAB0047F10C /* Assets.xcassets in Resources */, A5B30539299BEAAB0047F10C /* Assets.xcassets in Resources */,
A51BFC1E2B2FB5CE00E92F16 /* About.xib in Resources */, A51BFC1E2B2FB5CE00E92F16 /* About.xib in Resources */,
A5E112932AF73E6E00C6E0C2 /* ClipboardConfirmation.xib in Resources */, A5E112932AF73E6E00C6E0C2 /* ClipboardConfirmation.xib in Resources */,
A5CDF1912AAF9A5800513312 /* ConfigurationErrors.xib in Resources */, A5CDF1912AAF9A5800513312 /* ConfigurationErrors.xib in Resources */,
857F63812A5E64F200CA4815 /* MainMenu.xib in Resources */, 857F63812A5E64F200CA4815 /* MainMenu.xib in Resources */,
29C15B1D2CDC3B2900520DD4 /* bat in Resources */,
A596309A2AEE1C6400D64628 /* Terminal.xib in Resources */, A596309A2AEE1C6400D64628 /* Terminal.xib in Resources */,
A586167C2B7703CC009BDB1D /* fish in Resources */,
FC5218FA2D10FFCE004C93E0 /* zsh in Resources */,
55154BE02B33911F001622DC /* ghostty in Resources */,
A5985CE62C33060F00C57AD3 /* man in Resources */,
A5A1F8852A489D6800D1E8BC /* terminfo in Resources */,
552964E62B34A9B400030505 /* vim in Resources */,
9351BE8E3D22937F003B3499 /* nvim in Resources */,
A5CBD05C2CA0C5C70017A1AE /* QuickTerminal.xib in Resources */, A5CBD05C2CA0C5C70017A1AE /* QuickTerminal.xib in Resources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
@ -630,6 +648,7 @@
A59630A42AF059BB00D64628 /* Ghostty.SplitNode.swift in Sources */, A59630A42AF059BB00D64628 /* Ghostty.SplitNode.swift in Sources */,
A514C8D62B54A16400493A16 /* Ghostty.Config.swift in Sources */, A514C8D62B54A16400493A16 /* Ghostty.Config.swift in Sources */,
A54B0CEB2D0CFB4C00CBEFF8 /* NSImage+Extension.swift in Sources */, A54B0CEB2D0CFB4C00CBEFF8 /* NSImage+Extension.swift in Sources */,
A5874D9D2DAD786100E83852 /* NSWindow+Extension.swift in Sources */,
A54D786C2CA7978E001B19B1 /* BaseTerminalController.swift in Sources */, A54D786C2CA7978E001B19B1 /* BaseTerminalController.swift in Sources */,
A59FB5CF2AE0DB50009128F3 /* InspectorView.swift in Sources */, A59FB5CF2AE0DB50009128F3 /* InspectorView.swift in Sources */,
CFBB5FEA2D231E5000FD62EE /* QuickTerminalSpaceBehavior.swift in Sources */, CFBB5FEA2D231E5000FD62EE /* QuickTerminalSpaceBehavior.swift in Sources */,
@ -665,6 +684,7 @@
A5CDF1952AAFA19600513312 /* ConfigurationErrorsView.swift in Sources */, A5CDF1952AAFA19600513312 /* ConfigurationErrorsView.swift in Sources */,
A55B7BBC29B6FC330055DE60 /* SurfaceView.swift in Sources */, A55B7BBC29B6FC330055DE60 /* SurfaceView.swift in Sources */,
A5333E1C2B5A1CE3008AEFF7 /* CrossKit.swift in Sources */, A5333E1C2B5A1CE3008AEFF7 /* CrossKit.swift in Sources */,
A5874D992DAD751B00E83852 /* CGS.swift in Sources */,
A59444F729A2ED5200725BBA /* SettingsView.swift in Sources */, A59444F729A2ED5200725BBA /* SettingsView.swift in Sources */,
A56D58862ACDDB4100508D2C /* Ghostty.Shell.swift in Sources */, A56D58862ACDDB4100508D2C /* Ghostty.Shell.swift in Sources */,
A5985CD72C320C4500C57AD3 /* String+Extension.swift in Sources */, A5985CD72C320C4500C57AD3 /* String+Extension.swift in Sources */,

View File

@ -28,7 +28,9 @@ class AppDelegate: NSObject,
@IBOutlet private var menuNewWindow: NSMenuItem? @IBOutlet private var menuNewWindow: NSMenuItem?
@IBOutlet private var menuNewTab: NSMenuItem? @IBOutlet private var menuNewTab: NSMenuItem?
@IBOutlet private var menuSplitRight: NSMenuItem? @IBOutlet private var menuSplitRight: NSMenuItem?
@IBOutlet private var menuSplitLeft: NSMenuItem?
@IBOutlet private var menuSplitDown: NSMenuItem? @IBOutlet private var menuSplitDown: NSMenuItem?
@IBOutlet private var menuSplitUp: NSMenuItem?
@IBOutlet private var menuClose: NSMenuItem? @IBOutlet private var menuClose: NSMenuItem?
@IBOutlet private var menuCloseTab: NSMenuItem? @IBOutlet private var menuCloseTab: NSMenuItem?
@IBOutlet private var menuCloseWindow: NSMenuItem? @IBOutlet private var menuCloseWindow: NSMenuItem?
@ -41,6 +43,7 @@ class AppDelegate: NSObject,
@IBOutlet private var menuToggleVisibility: NSMenuItem? @IBOutlet private var menuToggleVisibility: NSMenuItem?
@IBOutlet private var menuToggleFullScreen: NSMenuItem? @IBOutlet private var menuToggleFullScreen: NSMenuItem?
@IBOutlet private var menuBringAllToFront: NSMenuItem?
@IBOutlet private var menuZoomSplit: NSMenuItem? @IBOutlet private var menuZoomSplit: NSMenuItem?
@IBOutlet private var menuPreviousSplit: NSMenuItem? @IBOutlet private var menuPreviousSplit: NSMenuItem?
@IBOutlet private var menuNextSplit: NSMenuItem? @IBOutlet private var menuNextSplit: NSMenuItem?
@ -48,10 +51,12 @@ class AppDelegate: NSObject,
@IBOutlet private var menuSelectSplitBelow: NSMenuItem? @IBOutlet private var menuSelectSplitBelow: NSMenuItem?
@IBOutlet private var menuSelectSplitLeft: NSMenuItem? @IBOutlet private var menuSelectSplitLeft: NSMenuItem?
@IBOutlet private var menuSelectSplitRight: NSMenuItem? @IBOutlet private var menuSelectSplitRight: NSMenuItem?
@IBOutlet private var menuReturnToDefaultSize: NSMenuItem?
@IBOutlet private var menuIncreaseFontSize: NSMenuItem? @IBOutlet private var menuIncreaseFontSize: NSMenuItem?
@IBOutlet private var menuDecreaseFontSize: NSMenuItem? @IBOutlet private var menuDecreaseFontSize: NSMenuItem?
@IBOutlet private var menuResetFontSize: NSMenuItem? @IBOutlet private var menuResetFontSize: NSMenuItem?
@IBOutlet private var menuChangeTitle: NSMenuItem?
@IBOutlet private var menuQuickTerminal: NSMenuItem? @IBOutlet private var menuQuickTerminal: NSMenuItem?
@IBOutlet private var menuTerminalInspector: NSMenuItem? @IBOutlet private var menuTerminalInspector: NSMenuItem?
@ -181,6 +186,12 @@ class AppDelegate: NSObject,
name: .ghosttyConfigDidChange, name: .ghosttyConfigDidChange,
object: nil object: nil
) )
NotificationCenter.default.addObserver(
self,
selector: #selector(ghosttyBellDidRing(_:)),
name: .ghosttyBellDidRing,
object: nil
)
// Configure user notifications // Configure user notifications
let actions = [ let actions = [
@ -361,7 +372,9 @@ class AppDelegate: NSObject,
syncMenuShortcut(config, action: "close_window", menuItem: self.menuCloseWindow) syncMenuShortcut(config, action: "close_window", menuItem: self.menuCloseWindow)
syncMenuShortcut(config, action: "close_all_windows", menuItem: self.menuCloseAllWindows) syncMenuShortcut(config, action: "close_all_windows", menuItem: self.menuCloseAllWindows)
syncMenuShortcut(config, action: "new_split:right", menuItem: self.menuSplitRight) syncMenuShortcut(config, action: "new_split:right", menuItem: self.menuSplitRight)
syncMenuShortcut(config, action: "new_split:left", menuItem: self.menuSplitLeft)
syncMenuShortcut(config, action: "new_split:down", menuItem: self.menuSplitDown) syncMenuShortcut(config, action: "new_split:down", menuItem: self.menuSplitDown)
syncMenuShortcut(config, action: "new_split:up", menuItem: self.menuSplitUp)
syncMenuShortcut(config, action: "copy_to_clipboard", menuItem: self.menuCopy) syncMenuShortcut(config, action: "copy_to_clipboard", menuItem: self.menuCopy)
syncMenuShortcut(config, action: "paste_from_clipboard", menuItem: self.menuPaste) syncMenuShortcut(config, action: "paste_from_clipboard", menuItem: self.menuPaste)
@ -380,10 +393,12 @@ class AppDelegate: NSObject,
syncMenuShortcut(config, action: "resize_split:right,10", menuItem: self.menuMoveSplitDividerRight) syncMenuShortcut(config, action: "resize_split:right,10", menuItem: self.menuMoveSplitDividerRight)
syncMenuShortcut(config, action: "resize_split:left,10", menuItem: self.menuMoveSplitDividerLeft) syncMenuShortcut(config, action: "resize_split:left,10", menuItem: self.menuMoveSplitDividerLeft)
syncMenuShortcut(config, action: "equalize_splits", menuItem: self.menuEqualizeSplits) syncMenuShortcut(config, action: "equalize_splits", menuItem: self.menuEqualizeSplits)
syncMenuShortcut(config, action: "reset_window_size", menuItem: self.menuReturnToDefaultSize)
syncMenuShortcut(config, action: "increase_font_size:1", menuItem: self.menuIncreaseFontSize) syncMenuShortcut(config, action: "increase_font_size:1", menuItem: self.menuIncreaseFontSize)
syncMenuShortcut(config, action: "decrease_font_size:1", menuItem: self.menuDecreaseFontSize) syncMenuShortcut(config, action: "decrease_font_size:1", menuItem: self.menuDecreaseFontSize)
syncMenuShortcut(config, action: "reset_font_size", menuItem: self.menuResetFontSize) syncMenuShortcut(config, action: "reset_font_size", menuItem: self.menuResetFontSize)
syncMenuShortcut(config, action: "change_title_prompt", menuItem: self.menuChangeTitle)
syncMenuShortcut(config, action: "toggle_quick_terminal", menuItem: self.menuQuickTerminal) syncMenuShortcut(config, action: "toggle_quick_terminal", menuItem: self.menuQuickTerminal)
syncMenuShortcut(config, action: "toggle_visibility", menuItem: self.menuToggleVisibility) syncMenuShortcut(config, action: "toggle_visibility", menuItem: self.menuToggleVisibility)
syncMenuShortcut(config, action: "inspector:toggle", menuItem: self.menuTerminalInspector) syncMenuShortcut(config, action: "inspector:toggle", menuItem: self.menuTerminalInspector)
@ -493,6 +508,11 @@ class AppDelegate: NSObject,
ghosttyConfigDidChange(config: config) ghosttyConfigDidChange(config: config)
} }
@objc private func ghosttyBellDidRing(_ notification: Notification) {
// Bounce the dock icon if we're not focused.
NSApp.requestUserAttention(.informationalRequest)
}
private func ghosttyConfigDidChange(config: Ghostty.Config) { private func ghosttyConfigDidChange(config: Ghostty.Config) {
// Update the config we need to store // Update the config we need to store
self.derivedConfig = DerivedConfig(config) self.derivedConfig = DerivedConfig(config)
@ -530,6 +550,15 @@ class AppDelegate: NSObject,
// AppKit mutex on the appearance. // AppKit mutex on the appearance.
DispatchQueue.main.async { self.syncAppearance(config: config) } DispatchQueue.main.async { self.syncAppearance(config: config) }
// Decide whether to hide/unhide app from dock and app switcher
switch (config.macosHidden) {
case .never:
NSApp.setActivationPolicy(.regular)
case .always:
NSApp.setActivationPolicy(.accessory)
}
// If we have configuration errors, we need to show them. // If we have configuration errors, we need to show them.
let c = ConfigurationErrorsController.sharedInstance let c = ConfigurationErrorsController.sharedInstance
c.errors = config.errors c.errors = config.errors
@ -762,6 +791,14 @@ class AppDelegate: NSObject,
hiddenState = nil hiddenState = nil
} }
@IBAction func bringAllToFront(_ sender: Any) {
if !NSApp.isActive {
NSApp.activate(ignoringOtherApps: true)
}
NSApplication.shared.arrangeInFront(sender)
}
private struct DerivedConfig { private struct DerivedConfig {
let initialWindow: Bool let initialWindow: Bool
let shouldQuitAfterLastWindowClosed: Bool let shouldQuitAfterLastWindowClosed: Bool

View File

@ -14,6 +14,8 @@
<customObject id="-3" userLabel="Application" customClass="NSObject"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customObject id="bbz-4X-AYv" userLabel="AppDelegate" customClass="AppDelegate" customModule="Ghostty" customModuleProvider="target"> <customObject id="bbz-4X-AYv" userLabel="AppDelegate" customClass="AppDelegate" customModule="Ghostty" customModuleProvider="target">
<connections> <connections>
<outlet property="menuBringAllToFront" destination="LE2-aR-0XJ" id="AP9-oK-60V"/>
<outlet property="menuChangeTitle" destination="24I-xg-qIq" id="kg6-kT-jNL"/>
<outlet property="menuCheckForUpdates" destination="GEA-5y-yzH" id="0nV-Tf-nJQ"/> <outlet property="menuCheckForUpdates" destination="GEA-5y-yzH" id="0nV-Tf-nJQ"/>
<outlet property="menuClose" destination="DVo-aG-piG" id="R3t-0C-aSU"/> <outlet property="menuClose" destination="DVo-aG-piG" id="R3t-0C-aSU"/>
<outlet property="menuCloseAllWindows" destination="yKr-Vi-Yqw" id="Zet-Ir-zbm"/> <outlet property="menuCloseAllWindows" destination="yKr-Vi-Yqw" id="Zet-Ir-zbm"/>
@ -38,6 +40,7 @@
<outlet property="menuQuit" destination="4sb-4s-VLi" id="qYN-S1-6UW"/> <outlet property="menuQuit" destination="4sb-4s-VLi" id="qYN-S1-6UW"/>
<outlet property="menuReloadConfig" destination="KKH-XX-5py" id="Wvp-7J-wqX"/> <outlet property="menuReloadConfig" destination="KKH-XX-5py" id="Wvp-7J-wqX"/>
<outlet property="menuResetFontSize" destination="Jah-MY-aLX" id="ger-qM-wrm"/> <outlet property="menuResetFontSize" destination="Jah-MY-aLX" id="ger-qM-wrm"/>
<outlet property="menuReturnToDefaultSize" destination="Gbx-Vi-OGC" id="po9-qC-Iz6"/>
<outlet property="menuSecureInput" destination="oC6-w4-qI7" id="PCc-pe-Mda"/> <outlet property="menuSecureInput" destination="oC6-w4-qI7" id="PCc-pe-Mda"/>
<outlet property="menuSelectAll" destination="q2h-lq-e4r" id="s98-r1-Jcv"/> <outlet property="menuSelectAll" destination="q2h-lq-e4r" id="s98-r1-Jcv"/>
<outlet property="menuSelectSplitAbove" destination="0yU-hC-8xF" id="aPc-lS-own"/> <outlet property="menuSelectSplitAbove" destination="0yU-hC-8xF" id="aPc-lS-own"/>
@ -45,8 +48,10 @@
<outlet property="menuSelectSplitLeft" destination="cTK-oy-KuV" id="Jpr-5q-dqz"/> <outlet property="menuSelectSplitLeft" destination="cTK-oy-KuV" id="Jpr-5q-dqz"/>
<outlet property="menuSelectSplitRight" destination="upj-mc-L7X" id="nLY-o1-lky"/> <outlet property="menuSelectSplitRight" destination="upj-mc-L7X" id="nLY-o1-lky"/>
<outlet property="menuServices" destination="aQe-vS-j8Q" id="uWQ-Wo-T1L"/> <outlet property="menuServices" destination="aQe-vS-j8Q" id="uWQ-Wo-T1L"/>
<outlet property="menuSplitDown" destination="UDZ-4y-6xL" id="fgZ-Wb-8OR"/> <outlet property="menuSplitDown" destination="UDZ-4y-6xL" id="ptr-mj-Azh"/>
<outlet property="menuSplitLeft" destination="Ppv-GP-lQU" id="Xd5-Cd-Jut"/>
<outlet property="menuSplitRight" destination="VUR-Ld-nLx" id="RxO-Zw-ovb"/> <outlet property="menuSplitRight" destination="VUR-Ld-nLx" id="RxO-Zw-ovb"/>
<outlet property="menuSplitUp" destination="Ggp-7N-GbX" id="YJF-uq-S4Y"/>
<outlet property="menuTerminalInspector" destination="QwP-M5-fvh" id="wJi-Dh-S9f"/> <outlet property="menuTerminalInspector" destination="QwP-M5-fvh" id="wJi-Dh-S9f"/>
<outlet property="menuToggleFullScreen" destination="8kY-Pi-KaY" id="yQg-6V-OO6"/> <outlet property="menuToggleFullScreen" destination="8kY-Pi-KaY" id="yQg-6V-OO6"/>
<outlet property="menuToggleVisibility" destination="DOX-wA-ilh" id="iBj-Bc-2bq"/> <outlet property="menuToggleVisibility" destination="DOX-wA-ilh" id="iBj-Bc-2bq"/>
@ -143,10 +148,22 @@
<action selector="splitRight:" target="-1" id="cv2-Xg-FR4"/> <action selector="splitRight:" target="-1" id="cv2-Xg-FR4"/>
</connections> </connections>
</menuItem> </menuItem>
<menuItem title="Split Left" id="Ppv-GP-lQU">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="splitLeft:" target="-1" id="Cey-Mf-bD2"/>
</connections>
</menuItem>
<menuItem title="Split Down" id="UDZ-4y-6xL"> <menuItem title="Split Down" id="UDZ-4y-6xL">
<modifierMask key="keyEquivalentModifierMask"/> <modifierMask key="keyEquivalentModifierMask"/>
<connections> <connections>
<action selector="splitDown:" target="-1" id="c6x-CF-u52"/> <action selector="splitDown:" target="-1" id="Zej-CF-6nO"/>
</connections>
</menuItem>
<menuItem title="Split Up" id="Ggp-7N-GbX">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="splitUp:" target="-1" id="bbi-dK-pOS"/>
</connections> </connections>
</menuItem> </menuItem>
<menuItem isSeparatorItem="YES" id="sjq-M1-UGS"/> <menuItem isSeparatorItem="YES" id="sjq-M1-UGS"/>
@ -232,6 +249,13 @@
</connections> </connections>
</menuItem> </menuItem>
<menuItem isSeparatorItem="YES" id="L3L-I8-sqk"/> <menuItem isSeparatorItem="YES" id="L3L-I8-sqk"/>
<menuItem title="Change Title..." id="24I-xg-qIq">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="changeTitle:" target="-1" id="XuL-QB-Q9l"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="Vkj-tP-dMZ"/>
<menuItem title="Quick Terminal" id="1pv-LF-NBJ"> <menuItem title="Quick Terminal" id="1pv-LF-NBJ">
<modifierMask key="keyEquivalentModifierMask"/> <modifierMask key="keyEquivalentModifierMask"/>
<connections> <connections>
@ -270,12 +294,6 @@
<action selector="toggleGhosttyFullScreen:" target="-1" id="QB9-7R-xyc"/> <action selector="toggleGhosttyFullScreen:" target="-1" id="QB9-7R-xyc"/>
</connections> </connections>
</menuItem> </menuItem>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
</connections>
</menuItem>
<menuItem title="Show/Hide All Terminals" id="DOX-wA-ilh"> <menuItem title="Show/Hide All Terminals" id="DOX-wA-ilh">
<modifierMask key="keyEquivalentModifierMask"/> <modifierMask key="keyEquivalentModifierMask"/>
<connections> <connections>
@ -370,6 +388,20 @@
</items> </items>
</menu> </menu>
</menuItem> </menuItem>
<menuItem isSeparatorItem="YES" id="dgt-Tx-d4e"/>
<menuItem title="Return To Default Size" id="Gbx-Vi-OGC" userLabel="Return To Default Size">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="returnToDefaultSize:" target="-1" id="Bpt-GO-UU1"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="CpM-rI-Sc1"/>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
</connections>
</menuItem>
</items> </items>
</menu> </menu>
</menuItem> </menuItem>

View File

@ -3,12 +3,6 @@ import Cocoa
import SwiftUI import SwiftUI
import GhosttyKit import GhosttyKit
// This is a Apple's private function that we need to call to get the active space.
@_silgen_name("CGSGetActiveSpace")
func CGSGetActiveSpace(_ cid: Int) -> size_t
@_silgen_name("CGSMainConnectionID")
func CGSMainConnectionID() -> Int
/// Controller for the "quick" terminal. /// Controller for the "quick" terminal.
class QuickTerminalController: BaseTerminalController { class QuickTerminalController: BaseTerminalController {
override var windowNibName: NSNib.Name? { "QuickTerminal" } override var windowNibName: NSNib.Name? { "QuickTerminal" }
@ -25,7 +19,7 @@ class QuickTerminalController: BaseTerminalController {
private var previousApp: NSRunningApplication? = nil private var previousApp: NSRunningApplication? = nil
// The active space when the quick terminal was last shown. // The active space when the quick terminal was last shown.
private var previousActiveSpace: size_t = 0 private var previousActiveSpace: CGSSpace? = nil
/// Non-nil if we have hidden dock state. /// Non-nil if we have hidden dock state.
private var hiddenDock: HiddenDock? = nil private var hiddenDock: HiddenDock? = nil
@ -51,7 +45,7 @@ class QuickTerminalController: BaseTerminalController {
object: nil) object: nil)
center.addObserver( center.addObserver(
self, self,
selector: #selector(onToggleFullscreen), selector: #selector(onToggleFullscreen(notification:)),
name: Ghostty.Notification.ghosttyToggleFullscreen, name: Ghostty.Notification.ghosttyToggleFullscreen,
object: nil) object: nil)
center.addObserver( center.addObserver(
@ -59,6 +53,11 @@ class QuickTerminalController: BaseTerminalController {
selector: #selector(ghosttyConfigDidChange(_:)), selector: #selector(ghosttyConfigDidChange(_:)),
name: .ghosttyConfigDidChange, name: .ghosttyConfigDidChange,
object: nil) object: nil)
center.addObserver(
self,
selector: #selector(onNewTab),
name: Ghostty.Notification.ghosttyNewTab,
object: nil)
} }
required init?(coder: NSCoder) { required init?(coder: NSCoder) {
@ -149,14 +148,24 @@ class QuickTerminalController: BaseTerminalController {
animateOut() animateOut()
case .move: case .move:
let currentActiveSpace = CGSGetActiveSpace(CGSMainConnectionID()) let currentActiveSpace = CGSSpace.active()
if previousActiveSpace == currentActiveSpace { if previousActiveSpace == currentActiveSpace {
// We haven't moved spaces. We lost focus to another app on the // We haven't moved spaces. We lost focus to another app on the
// current space. Animate out. // current space. Animate out.
animateOut() animateOut()
} else { } else {
// We've moved to a different space. Bring the quick terminal back // We've moved to a different space.
// into view.
// If we're fullscreen, we need to exit fullscreen because the visible
// bounds may have changed causing a new behavior.
if let fullscreenStyle, fullscreenStyle.isFullscreen {
fullscreenStyle.exit()
DispatchQueue.main.async {
self.onToggleFullscreen()
}
}
// Make the window visible again on this space
DispatchQueue.main.async { DispatchQueue.main.async {
self.window?.makeKeyAndOrderFront(nil) self.window?.makeKeyAndOrderFront(nil)
} }
@ -219,7 +228,7 @@ class QuickTerminalController: BaseTerminalController {
} }
// Set previous active space // Set previous active space
self.previousActiveSpace = CGSGetActiveSpace(CGSMainConnectionID()) self.previousActiveSpace = CGSSpace.active()
// Animate the window in // Animate the window in
animateWindowIn(window: window, from: position) animateWindowIn(window: window, from: position)
@ -437,14 +446,7 @@ class QuickTerminalController: BaseTerminalController {
} }
} }
// MARK: First Responder private func showNoNewTabAlert() {
@IBAction override func closeWindow(_ sender: Any) {
// Instead of closing the window, we animate it out.
animateOut()
}
@IBAction func newTab(_ sender: Any?) {
guard let window else { return } guard let window else { return }
let alert = NSAlert() let alert = NSAlert()
alert.messageText = "Cannot Create New Tab" alert.messageText = "Cannot Create New Tab"
@ -454,11 +456,27 @@ class QuickTerminalController: BaseTerminalController {
alert.beginSheetModal(for: window) alert.beginSheetModal(for: window)
} }
// MARK: First Responder
@IBAction override func closeWindow(_ sender: Any) {
// Instead of closing the window, we animate it out.
animateOut()
}
@IBAction func newTab(_ sender: Any?) {
showNoNewTabAlert()
}
@IBAction func toggleGhosttyFullScreen(_ sender: Any) { @IBAction func toggleGhosttyFullScreen(_ sender: Any) {
guard let surface = focusedSurface?.surface else { return } guard let surface = focusedSurface?.surface else { return }
ghostty.toggleFullscreen(surface: surface) ghostty.toggleFullscreen(surface: surface)
} }
@IBAction func toggleTerminalInspector(_ sender: Any?) {
guard let surface = focusedSurface?.surface else { return }
ghostty.toggleTerminalInspector(surface: surface)
}
// MARK: Notifications // MARK: Notifications
@objc private func applicationWillTerminate(_ notification: Notification) { @objc private func applicationWillTerminate(_ notification: Notification) {
@ -471,9 +489,29 @@ class QuickTerminalController: BaseTerminalController {
@objc private func onToggleFullscreen(notification: SwiftUI.Notification) { @objc private func onToggleFullscreen(notification: SwiftUI.Notification) {
guard let target = notification.object as? Ghostty.SurfaceView else { return } guard let target = notification.object as? Ghostty.SurfaceView else { return }
guard target == self.focusedSurface else { return } guard target == self.focusedSurface else { return }
onToggleFullscreen()
}
// We ignore the requested mode and always use non-native for the quick terminal private func onToggleFullscreen() {
toggleFullscreen(mode: .nonNative) // We ignore the configured fullscreen style and always use non-native
// because the way the quick terminal works doesn't support native.
let mode: FullscreenMode
if (NSApp.isFrontmost) {
// If we're frontmost and we have a notch then we keep padding
// so all lines of the terminal are visible.
if (window?.screen?.hasNotch ?? false) {
mode = .nonNativePaddedNotch
} else {
mode = .nonNative
}
} else {
// An additional detail is that if the is NOT frontmost, then our
// NSApp.presentationOptions will not take effect so we must always
// do the visible menu mode since we can't get rid of the menu.
mode = .nonNativeVisibleMenu
}
toggleFullscreen(mode: mode)
} }
@objc private func ghosttyConfigDidChange(_ notification: Notification) { @objc private func ghosttyConfigDidChange(_ notification: Notification) {
@ -492,6 +530,14 @@ class QuickTerminalController: BaseTerminalController {
syncAppearance() syncAppearance()
} }
@objc private func onNewTab(notification: SwiftUI.Notification) {
guard let surfaceView = notification.object as? Ghostty.SurfaceView else { return }
guard let window = surfaceView.window else { return }
guard window.windowController is QuickTerminalController else { return }
// Tabs aren't supported with Quick Terminals or derivatives
showNoNewTabAlert()
}
private struct DerivedConfig { private struct DerivedConfig {
let quickTerminalScreen: QuickTerminalScreen let quickTerminalScreen: QuickTerminalScreen
let quickTerminalAnimationDuration: Double let quickTerminalAnimationDuration: Double

View File

@ -413,6 +413,14 @@ class BaseTerminalController: NSWindowController,
override func windowDidLoad() { override func windowDidLoad() {
guard let window else { return } guard let window else { return }
// If there is a hardcoded title in the configuration, we set that
// immediately. Future `set_title` apprt actions will override this
// if necessary but this ensures our window loads with the proper
// title immediately rather than on another event loop tick (see #5934)
if let title = derivedConfig.title {
window.title = title
}
// We always initialize our fullscreen style to native if we can because // We always initialize our fullscreen style to native if we can because
// initialization sets up some state (i.e. observers). If its set already // initialization sets up some state (i.e. observers). If its set already
// somehow we don't do this. // somehow we don't do this.
@ -521,11 +529,21 @@ class BaseTerminalController: NSWindowController,
ghostty.split(surface: surface, direction: GHOSTTY_SPLIT_DIRECTION_RIGHT) ghostty.split(surface: surface, direction: GHOSTTY_SPLIT_DIRECTION_RIGHT)
} }
@IBAction func splitLeft(_ sender: Any) {
guard let surface = focusedSurface?.surface else { return }
ghostty.split(surface: surface, direction: GHOSTTY_SPLIT_DIRECTION_LEFT)
}
@IBAction func splitDown(_ sender: Any) { @IBAction func splitDown(_ sender: Any) {
guard let surface = focusedSurface?.surface else { return } guard let surface = focusedSurface?.surface else { return }
ghostty.split(surface: surface, direction: GHOSTTY_SPLIT_DIRECTION_DOWN) ghostty.split(surface: surface, direction: GHOSTTY_SPLIT_DIRECTION_DOWN)
} }
@IBAction func splitUp(_ sender: Any) {
guard let surface = focusedSurface?.surface else { return }
ghostty.split(surface: surface, direction: GHOSTTY_SPLIT_DIRECTION_UP)
}
@IBAction func splitZoom(_ sender: Any) { @IBAction func splitZoom(_ sender: Any) {
guard let surface = focusedSurface?.surface else { return } guard let surface = focusedSurface?.surface else { return }
ghostty.splitToggleZoom(surface: surface) ghostty.splitToggleZoom(surface: surface)
@ -607,17 +625,20 @@ class BaseTerminalController: NSWindowController,
} }
private struct DerivedConfig { private struct DerivedConfig {
let title: String?
let macosTitlebarProxyIcon: Ghostty.MacOSTitlebarProxyIcon let macosTitlebarProxyIcon: Ghostty.MacOSTitlebarProxyIcon
let windowStepResize: Bool let windowStepResize: Bool
let focusFollowsMouse: Bool let focusFollowsMouse: Bool
init() { init() {
self.title = nil
self.macosTitlebarProxyIcon = .visible self.macosTitlebarProxyIcon = .visible
self.windowStepResize = false self.windowStepResize = false
self.focusFollowsMouse = false self.focusFollowsMouse = false
} }
init(_ config: Ghostty.Config) { init(_ config: Ghostty.Config) {
self.title = config.title
self.macosTitlebarProxyIcon = config.macosTitlebarProxyIcon self.macosTitlebarProxyIcon = config.macosTitlebarProxyIcon
self.windowStepResize = config.windowStepResize self.windowStepResize = config.windowStepResize
self.focusFollowsMouse = config.focusFollowsMouse self.focusFollowsMouse = config.focusFollowsMouse

View File

@ -27,6 +27,9 @@ class TerminalController: BaseTerminalController {
/// The notification cancellable for focused surface property changes. /// The notification cancellable for focused surface property changes.
private var surfaceAppearanceCancellables: Set<AnyCancellable> = [] private var surfaceAppearanceCancellables: Set<AnyCancellable> = []
/// This will be set to the initial frame of the window from the xib on load.
private var initialFrame: NSRect? = nil
init(_ ghostty: Ghostty.App, init(_ ghostty: Ghostty.App,
withBaseConfig base: Ghostty.SurfaceConfiguration? = nil, withBaseConfig base: Ghostty.SurfaceConfiguration? = nil,
withSurfaceTree tree: Ghostty.SplitNode? = nil withSurfaceTree tree: Ghostty.SplitNode? = nil
@ -65,6 +68,12 @@ class TerminalController: BaseTerminalController {
selector: #selector(onCloseTab), selector: #selector(onCloseTab),
name: .ghosttyCloseTab, name: .ghosttyCloseTab,
object: nil) object: nil)
center.addObserver(
self,
selector: #selector(onResetWindowSize),
name: .ghosttyResetWindowSize,
object: nil
)
center.addObserver( center.addObserver(
self, self,
selector: #selector(ghosttyConfigDidChange(_:)), selector: #selector(ghosttyConfigDidChange(_:)),
@ -76,6 +85,18 @@ class TerminalController: BaseTerminalController {
selector: #selector(onFrameDidChange), selector: #selector(onFrameDidChange),
name: NSView.frameDidChangeNotification, name: NSView.frameDidChangeNotification,
object: nil) object: nil)
center.addObserver(
self,
selector: #selector(onEqualizeSplits),
name: Ghostty.Notification.didEqualizeSplits,
object: nil
)
center.addObserver(
self,
selector: #selector(onCloseWindow),
name: .ghosttyCloseWindow,
object: nil
)
} }
required init?(coder: NSCoder) { required init?(coder: NSCoder) {
@ -212,6 +233,9 @@ class TerminalController: BaseTerminalController {
// Set our explicit appearance if we need to based on the configuration. // Set our explicit appearance if we need to based on the configuration.
window.appearance = surfaceConfig.windowAppearance window.appearance = surfaceConfig.windowAppearance
// Update our window light/darkness based on our updated background color
window.isLightTheme = OSColor(surfaceConfig.backgroundColor).isLightColor
// If our window is not visible, then we do nothing. Some things such as blurring // If our window is not visible, then we do nothing. Some things such as blurring
// have no effect if the window is not visible. Ultimately, we'll have this called // have no effect if the window is not visible. Ultimately, we'll have this called
// at some point when a surface becomes focused. // at some point when a surface becomes focused.
@ -305,6 +329,55 @@ class TerminalController: BaseTerminalController {
y: frame.maxY - (CGFloat(y) + window.frame.height))) y: frame.maxY - (CGFloat(y) + window.frame.height)))
} }
/// Returns the default size of the window. This is contextual based on the focused surface because
/// the focused surface may specify a different default size than others.
private var defaultSize: NSRect? {
guard let screen = window?.screen ?? NSScreen.main else { return nil }
if derivedConfig.maximize {
return screen.visibleFrame
} else if let focusedSurface,
let initialSize = focusedSurface.initialSize {
// Get the current frame of the window
guard var frame = window?.frame else { return nil }
// Calculate the chrome size (window size minus view size)
let chromeWidth = frame.size.width - focusedSurface.frame.size.width
let chromeHeight = frame.size.height - focusedSurface.frame.size.height
// Calculate the new width and height, clamping to the screen's size
let newWidth = min(initialSize.width + chromeWidth, screen.visibleFrame.width)
let newHeight = min(initialSize.height + chromeHeight, screen.visibleFrame.height)
// Update the frame size while keeping the window's position intact
frame.size.width = newWidth
frame.size.height = newHeight
// Ensure the window doesn't go outside the screen boundaries
frame.origin.x = max(screen.frame.origin.x, min(frame.origin.x, screen.frame.maxX - newWidth))
frame.origin.y = max(screen.frame.origin.y, min(frame.origin.y, screen.frame.maxY - newHeight))
return frame
}
guard let initialFrame else { return nil }
guard var frame = window?.frame else { return nil }
// Calculate the new width and height, clamping to the screen's size
let newWidth = min(initialFrame.size.width, screen.visibleFrame.width)
let newHeight = min(initialFrame.size.height, screen.visibleFrame.height)
// Update the frame size while keeping the window's position intact
frame.size.width = newWidth
frame.size.height = newHeight
// Ensure the window doesn't go outside the screen boundaries
frame.origin.x = max(screen.frame.origin.x, min(frame.origin.x, screen.frame.maxX - newWidth))
frame.origin.y = max(screen.frame.origin.y, min(frame.origin.y, screen.frame.maxY - newHeight))
return frame
}
//MARK: - NSWindowController //MARK: - NSWindowController
override func windowWillLoad() { override func windowWillLoad() {
@ -353,6 +426,9 @@ class TerminalController: BaseTerminalController {
super.windowDidLoad() super.windowDidLoad()
guard let window = window as? TerminalWindow else { return } guard let window = window as? TerminalWindow else { return }
// Store our initial frame so we can know our default later.
initialFrame = window.frame
// I copy this because we may change the source in the future but also because // I copy this because we may change the source in the future but also because
// I regularly audit our codebase for "ghostty.config" access because generally // I regularly audit our codebase for "ghostty.config" access because generally
// you shouldn't use it. Its safe in this case because for a new window we should // you shouldn't use it. Its safe in this case because for a new window we should
@ -369,32 +445,15 @@ class TerminalController: BaseTerminalController {
// If window decorations are disabled, remove our title // If window decorations are disabled, remove our title
if (!config.windowDecorations) { window.styleMask.remove(.titled) } if (!config.windowDecorations) { window.styleMask.remove(.titled) }
// If we have only a single surface (no splits) and that surface requested // If we have only a single surface (no splits) and there is a default size then
// an initial size then we set it here now. // we should resize to that default size.
if case let .leaf(leaf) = surfaceTree { if case let .leaf(leaf) = surfaceTree {
if let initialSize = leaf.surface.initialSize, // If this is our first surface then our focused surface will be nil
let screen = window.screen ?? NSScreen.main { // so we force the focused surface to the leaf.
// Get the current frame of the window focusedSurface = leaf.surface
var frame = window.frame
// Calculate the chrome size (window size minus view size) if let defaultSize {
let chromeWidth = frame.size.width - leaf.surface.frame.size.width window.setFrame(defaultSize, display: true)
let chromeHeight = frame.size.height - leaf.surface.frame.size.height
// Calculate the new width and height, clamping to the screen's size
let newWidth = min(initialSize.width + chromeWidth, screen.visibleFrame.width)
let newHeight = min(initialSize.height + chromeHeight, screen.visibleFrame.height)
// Update the frame size while keeping the window's position intact
frame.size.width = newWidth
frame.size.height = newHeight
// Ensure the window doesn't go outside the screen boundaries
frame.origin.x = max(screen.frame.origin.x, min(frame.origin.x, screen.frame.maxX - newWidth))
frame.origin.y = max(screen.frame.origin.y, min(frame.origin.y, screen.frame.maxY - newHeight))
// Set the updated frame to the window
window.setFrame(frame, display: true)
} }
} }
@ -571,6 +630,11 @@ class TerminalController: BaseTerminalController {
window.close() window.close()
} }
@IBAction func returnToDefaultSize(_ sender: Any?) {
guard let defaultSize else { return }
window?.setFrame(defaultSize, display: true)
}
@IBAction override func closeWindow(_ sender: Any?) { @IBAction override func closeWindow(_ sender: Any?) {
guard let window = window else { return } guard let window = window else { return }
guard let tabGroup = window.tabGroup else { guard let tabGroup = window.tabGroup else {
@ -784,6 +848,18 @@ class TerminalController: BaseTerminalController {
closeTab(self) closeTab(self)
} }
@objc private func onCloseWindow(notification: SwiftUI.Notification) {
guard let target = notification.object as? Ghostty.SurfaceView else { return }
guard surfaceTree?.contains(view: target) ?? false else { return }
closeWindow(self)
}
@objc private func onResetWindowSize(notification: SwiftUI.Notification) {
guard let target = notification.object as? Ghostty.SurfaceView else { return }
guard surfaceTree?.contains(view: target) ?? false else { return }
returnToDefaultSize(nil)
}
@objc private func onToggleFullscreen(notification: SwiftUI.Notification) { @objc private func onToggleFullscreen(notification: SwiftUI.Notification) {
guard let target = notification.object as? Ghostty.SurfaceView else { return } guard let target = notification.object as? Ghostty.SurfaceView else { return }
guard target == self.focusedSurface else { return } guard target == self.focusedSurface else { return }
@ -801,18 +877,69 @@ class TerminalController: BaseTerminalController {
toggleFullscreen(mode: fullscreenMode) toggleFullscreen(mode: fullscreenMode)
} }
@objc private func onEqualizeSplits(_ notification: Notification) {
guard let target = notification.object as? Ghostty.SurfaceView else { return }
// Check if target surface is in current controller's tree
guard surfaceTree?.contains(view: target) ?? false else { return }
if case .split(let container) = surfaceTree {
_ = container.equalize()
}
}
struct DerivedConfig { struct DerivedConfig {
let backgroundColor: Color let backgroundColor: Color
let macosTitlebarStyle: String let macosTitlebarStyle: String
let maximize: Bool
init() { init() {
self.backgroundColor = Color(NSColor.windowBackgroundColor) self.backgroundColor = Color(NSColor.windowBackgroundColor)
self.macosTitlebarStyle = "system" self.macosTitlebarStyle = "system"
self.maximize = false
} }
init(_ config: Ghostty.Config) { init(_ config: Ghostty.Config) {
self.backgroundColor = config.backgroundColor self.backgroundColor = config.backgroundColor
self.macosTitlebarStyle = config.macosTitlebarStyle self.macosTitlebarStyle = config.macosTitlebarStyle
self.maximize = config.maximize
} }
} }
} }
extension TerminalController: NSMenuItemValidation {
func validateMenuItem(_ item: NSMenuItem) -> Bool {
switch item.action {
case #selector(returnToDefaultSize):
guard let window else { return false }
// Native fullscreen windows can't revert to default size.
if window.styleMask.contains(.fullScreen) {
return false
}
// If we're fullscreen at all then we can't change size
if fullscreenStyle?.isFullscreen ?? false {
return false
}
// If our window is already the default size or we don't have a
// default size, then disable.
guard let defaultSize,
window.frame.size != .init(
width: defaultSize.size.width,
height: defaultSize.size.height
)
else {
return false
}
return true
default:
return true
}
}
}

View File

@ -86,7 +86,7 @@ class TerminalManager {
// fullscreen for the logic later in this method. // fullscreen for the logic later in this method.
c.toggleFullscreen(mode: .native) c.toggleFullscreen(mode: .native)
case .nonNative, .nonNativeVisibleMenu: case .nonNative, .nonNativeVisibleMenu, .nonNativePaddedNotch:
// If we're non-native then we have to do it on a later loop // If we're non-native then we have to do it on a later loop
// so that the content view is setup. // so that the content view is setup.
DispatchQueue.main.async { DispatchQueue.main.async {
@ -95,11 +95,8 @@ class TerminalManager {
} }
} }
// If our app isn't active, we make it active. All new_window actions // All new_window actions force our app to be active.
// force our app to be active. NSApp.activate(ignoringOtherApps: true)
if !NSApp.isActive {
NSApp.activate(ignoringOtherApps: true)
}
// We're dispatching this async because otherwise the lastCascadePoint doesn't // We're dispatching this async because otherwise the lastCascadePoint doesn't
// take effect. Our best theory is there is some next-event-loop-tick logic // take effect. Our best theory is there is some next-event-loop-tick logic
@ -128,6 +125,9 @@ class TerminalManager {
} }
private func newTab(to parent: NSWindow, withBaseConfig base: Ghostty.SurfaceConfiguration?) { private func newTab(to parent: NSWindow, withBaseConfig base: Ghostty.SurfaceConfiguration?) {
// Making sure that we're dealing with a TerminalController
guard parent.windowController is TerminalController else { return }
// If our parent is in non-native fullscreen, then new tabs do not work. // If our parent is in non-native fullscreen, then new tabs do not work.
// See: https://github.com/mitchellh/ghostty/issues/392 // See: https://github.com/mitchellh/ghostty/issues/392
if let controller = parent.windowController as? TerminalController, if let controller = parent.windowController as? TerminalController,

View File

@ -95,6 +95,23 @@ fileprivate class CenteredDynamicLabel: NSTextField {
setContentHuggingPriority(.defaultLow, for: .horizontal) setContentHuggingPriority(.defaultLow, for: .horizontal)
setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
} }
// Vertically center the text
override func draw(_ dirtyRect: NSRect) {
guard let attributedString = self.attributedStringValue.mutableCopy() as? NSMutableAttributedString else {
super.draw(dirtyRect)
return
}
let textSize = attributedString.size()
let yOffset = (self.bounds.height - textSize.height) / 2 - 1 // -1 to center it better
let centeredRect = NSRect(x: self.bounds.origin.x, y: self.bounds.origin.y + yOffset,
width: self.bounds.width, height: textSize.height)
attributedString.draw(in: centeredRect)
}
} }
extension NSToolbarItem.Identifier { extension NSToolbarItem.Identifier {

View File

@ -3,6 +3,10 @@ import Cocoa
class TerminalWindow: NSWindow { class TerminalWindow: NSWindow {
@objc dynamic var keyEquivalent: String = "" @objc dynamic var keyEquivalent: String = ""
/// This is used to determine if certain elements should be drawn light or dark and should
/// be updated whenever the window background color or surrounding elements changes.
var isLightTheme: Bool = false
lazy var titlebarColor: NSColor = backgroundColor { lazy var titlebarColor: NSColor = backgroundColor {
didSet { didSet {
guard let titlebarContainer else { return } guard let titlebarContainer else { return }
@ -295,7 +299,6 @@ class TerminalWindow: NSWindow {
if newTabButtonImageLayer == nil { if newTabButtonImageLayer == nil {
let isLightTheme = backgroundColor.isLightColor
let fillColor: NSColor = isLightTheme ? .black.withAlphaComponent(0.85) : .white.withAlphaComponent(0.85) let fillColor: NSColor = isLightTheme ? .black.withAlphaComponent(0.85) : .white.withAlphaComponent(0.85)
let newImage = NSImage(size: newTabButtonImage.size, flipped: false) { rect in let newImage = NSImage(size: newTabButtonImage.size, flipped: false) { rect in
newTabButtonImage.draw(in: rect) newTabButtonImage.draw(in: rect)
@ -714,7 +717,7 @@ fileprivate class WindowButtonsBackdropView: NSView {
init(window: TerminalWindow) { init(window: TerminalWindow) {
self.terminalWindow = window self.terminalWindow = window
self.isLightTheme = window.backgroundColor.isLightColor self.isLightTheme = window.isLightTheme
super.init(frame: .zero) super.init(frame: .zero)

View File

@ -13,6 +13,9 @@ extension FullscreenMode {
case GHOSTTY_FULLSCREEN_NON_NATIVE_VISIBLE_MENU: case GHOSTTY_FULLSCREEN_NON_NATIVE_VISIBLE_MENU:
.nonNativeVisibleMenu .nonNativeVisibleMenu
case GHOSTTY_FULLSCREEN_NON_NATIVE_PADDED_NOTCH:
.nonNativePaddedNotch
default: default:
nil nil
} }

View File

@ -451,6 +451,9 @@ extension Ghostty {
case GHOSTTY_ACTION_CLOSE_TAB: case GHOSTTY_ACTION_CLOSE_TAB:
closeTab(app, target: target) closeTab(app, target: target)
case GHOSTTY_ACTION_CLOSE_WINDOW:
closeWindow(app, target: target)
case GHOSTTY_ACTION_TOGGLE_FULLSCREEN: case GHOSTTY_ACTION_TOGGLE_FULLSCREEN:
toggleFullscreen(app, target: target, mode: action.action.toggle_fullscreen) toggleFullscreen(app, target: target, mode: action.action.toggle_fullscreen)
@ -484,6 +487,9 @@ extension Ghostty {
case GHOSTTY_ACTION_SET_TITLE: case GHOSTTY_ACTION_SET_TITLE:
setTitle(app, target: target, v: action.action.set_title) setTitle(app, target: target, v: action.action.set_title)
case GHOSTTY_ACTION_PROMPT_TITLE:
return promptTitle(app, target: target)
case GHOSTTY_ACTION_PWD: case GHOSTTY_ACTION_PWD:
pwdChanged(app, target: target, v: action.action.pwd) pwdChanged(app, target: target, v: action.action.pwd)
@ -505,6 +511,9 @@ extension Ghostty {
case GHOSTTY_ACTION_INITIAL_SIZE: case GHOSTTY_ACTION_INITIAL_SIZE:
setInitialSize(app, target: target, v: action.action.initial_size) setInitialSize(app, target: target, v: action.action.initial_size)
case GHOSTTY_ACTION_RESET_WINDOW_SIZE:
resetWindowSize(app, target: target)
case GHOSTTY_ACTION_CELL_SIZE: case GHOSTTY_ACTION_CELL_SIZE:
setCellSize(app, target: target, v: action.action.cell_size) setCellSize(app, target: target, v: action.action.cell_size)
@ -529,6 +538,9 @@ extension Ghostty {
case GHOSTTY_ACTION_COLOR_CHANGE: case GHOSTTY_ACTION_COLOR_CHANGE:
colorChange(app, target: target, change: action.action.color_change) colorChange(app, target: target, change: action.action.color_change)
case GHOSTTY_ACTION_RING_BELL:
ringBell(app, target: target)
case GHOSTTY_ACTION_CLOSE_ALL_WINDOWS: case GHOSTTY_ACTION_CLOSE_ALL_WINDOWS:
fallthrough fallthrough
case GHOSTTY_ACTION_TOGGLE_TAB_OVERVIEW: case GHOSTTY_ACTION_TOGGLE_TAB_OVERVIEW:
@ -680,6 +692,26 @@ extension Ghostty {
} }
} }
private static func closeWindow(_ app: ghostty_app_t, target: ghostty_target_s) {
switch (target.tag) {
case GHOSTTY_TARGET_APP:
Ghostty.logger.warning("close window does nothing with an app target")
return
case GHOSTTY_TARGET_SURFACE:
guard let surface = target.target.surface else { return }
guard let surfaceView = self.surfaceView(from: surface) else { return }
NotificationCenter.default.post(
name: .ghosttyCloseWindow,
object: surfaceView
)
default:
assertionFailure()
}
}
private static func toggleFullscreen( private static func toggleFullscreen(
_ app: ghostty_app_t, _ app: ghostty_app_t,
target: ghostty_target_s, target: ghostty_target_s,
@ -718,6 +750,30 @@ extension Ghostty {
appDelegate.toggleVisibility(self) appDelegate.toggleVisibility(self)
} }
private static func ringBell(
_ app: ghostty_app_t,
target: ghostty_target_s) {
switch (target.tag) {
case GHOSTTY_TARGET_APP:
// Technically we could still request app attention here but there
// are no known cases where the bell is rang with an app target so
// I think its better to warn.
Ghostty.logger.warning("ring bell does nothing with an app target")
return
case GHOSTTY_TARGET_SURFACE:
guard let surface = target.target.surface else { return }
guard let surfaceView = self.surfaceView(from: surface) else { return }
NotificationCenter.default.post(
name: .ghosttyBellDidRing,
object: surfaceView
)
default:
assertionFailure()
}
}
private static func moveTab( private static func moveTab(
_ app: ghostty_app_t, _ app: ghostty_app_t,
target: ghostty_target_s, target: ghostty_target_s,
@ -1007,6 +1063,26 @@ extension Ghostty {
} }
} }
private static func promptTitle(
_ app: ghostty_app_t,
target: ghostty_target_s) -> Bool {
switch (target.tag) {
case GHOSTTY_TARGET_APP:
Ghostty.logger.warning("set title prompt does nothing with an app target")
return false
case GHOSTTY_TARGET_SURFACE:
guard let surface = target.target.surface else { return false }
guard let surfaceView = self.surfaceView(from: surface) else { return false }
surfaceView.promptTitle()
default:
assertionFailure()
}
return true
}
private static func pwdChanged( private static func pwdChanged(
_ app: ghostty_app_t, _ app: ghostty_app_t,
target: ghostty_target_s, target: ghostty_target_s,
@ -1108,7 +1184,7 @@ extension Ghostty {
v: ghostty_action_initial_size_s) { v: ghostty_action_initial_size_s) {
switch (target.tag) { switch (target.tag) {
case GHOSTTY_TARGET_APP: case GHOSTTY_TARGET_APP:
Ghostty.logger.warning("mouse over link does nothing with an app target") Ghostty.logger.warning("initial size does nothing with an app target")
return return
case GHOSTTY_TARGET_SURFACE: case GHOSTTY_TARGET_SURFACE:
@ -1122,6 +1198,28 @@ extension Ghostty {
} }
} }
private static func resetWindowSize(
_ app: ghostty_app_t,
target: ghostty_target_s) {
switch (target.tag) {
case GHOSTTY_TARGET_APP:
Ghostty.logger.warning("reset window size does nothing with an app target")
return
case GHOSTTY_TARGET_SURFACE:
guard let surface = target.target.surface else { return }
guard let surfaceView = self.surfaceView(from: surface) else { return }
NotificationCenter.default.post(
name: .ghosttyResetWindowSize,
object: surfaceView
)
default:
assertionFailure()
}
}
private static func setCellSize( private static func setCellSize(
_ app: ghostty_app_t, _ app: ghostty_app_t,
target: ghostty_target_s, target: ghostty_target_s,

View File

@ -116,6 +116,14 @@ extension Ghostty {
/// details on what each means. We only add documentation if there is a strange conversion /// details on what each means. We only add documentation if there is a strange conversion
/// due to the embedded library and Swift. /// due to the embedded library and Swift.
var bellFeatures: BellFeatures {
guard let config = self.config else { return .init() }
var v: CUnsignedInt = 0
let key = "bell-features"
guard ghostty_config_get(config, &v, key, UInt(key.count)) else { return .init() }
return .init(rawValue: v)
}
var initialWindow: Bool { var initialWindow: Bool {
guard let config = self.config else { return true } guard let config = self.config else { return true }
var v = true; var v = true;
@ -132,6 +140,15 @@ extension Ghostty {
return v return v
} }
var title: String? {
guard let config = self.config else { return nil }
var v: UnsafePointer<Int8>? = nil
let key = "title"
guard ghostty_config_get(config, &v, key, UInt(key.count)) else { return nil }
guard let ptr = v else { return nil }
return String(cString: ptr)
}
var windowSaveState: String { var windowSaveState: String {
guard let config = self.config else { return "" } guard let config = self.config else { return "" }
var v: UnsafePointer<Int8>? = nil var v: UnsafePointer<Int8>? = nil
@ -216,6 +233,8 @@ extension Ghostty {
.nonNative .nonNative
case "visible-menu": case "visible-menu":
.nonNativeVisibleMenu .nonNativeVisibleMenu
case "padded-notch":
.nonNativePaddedNotch
default: default:
defaultValue defaultValue
} }
@ -300,6 +319,16 @@ extension Ghostty {
return buffer.map { .init(ghostty: $0) } return buffer.map { .init(ghostty: $0) }
} }
var macosHidden: MacHidden {
guard let config = self.config else { return .never }
var v: UnsafePointer<Int8>? = nil
let key = "macos-hidden"
guard ghostty_config_get(config, &v, key, UInt(key.count)) else { return .never }
guard let ptr = v else { return .never }
let str = String(cString: ptr)
return MacHidden(rawValue: str) ?? .never
}
var focusFollowsMouse : Bool { var focusFollowsMouse : Bool {
guard let config = self.config else { return false } guard let config = self.config else { return false }
var v = false; var v = false;
@ -502,6 +531,14 @@ extension Ghostty {
_ = ghostty_config_get(config, &v, key, UInt(key.count)) _ = ghostty_config_get(config, &v, key, UInt(key.count))
return v return v
} }
var maximize: Bool {
guard let config = self.config else { return true }
var v = false;
let key = "maximize"
_ = ghostty_config_get(config, &v, key, UInt(key.count))
return v
}
} }
} }
@ -514,6 +551,17 @@ extension Ghostty.Config {
case download case download
} }
struct BellFeatures: OptionSet {
let rawValue: CUnsignedInt
static let system = BellFeatures(rawValue: 1 << 0)
}
enum MacHidden : String {
case never
case always
}
enum ResizeOverlay : String { enum ResizeOverlay : String {
case always case always
case never case never

View File

@ -50,7 +50,6 @@ extension Ghostty {
var body: some View { var body: some View {
let center = NotificationCenter.default let center = NotificationCenter.default
let pubZoom = center.publisher(for: Notification.didToggleSplitZoom) let pubZoom = center.publisher(for: Notification.didToggleSplitZoom)
let pubEqualize = center.publisher(for: Notification.didEqualizeSplits)
// If we're zoomed, we don't render anything, we are transparent. This // If we're zoomed, we don't render anything, we are transparent. This
// ensures that the View stays around so we don't lose our state, but // ensures that the View stays around so we don't lose our state, but
@ -76,7 +75,6 @@ extension Ghostty {
container: container container: container
) )
.onReceive(pubZoom) { onZoom(notification: $0) } .onReceive(pubZoom) { onZoom(notification: $0) }
.onReceive(pubEqualize) { onEqualize(notification: $0) }
} }
} }
.navigationTitle(surfaceTitle ?? "Ghostty") .navigationTitle(surfaceTitle ?? "Ghostty")
@ -137,11 +135,6 @@ extension Ghostty {
} }
} }
} }
func onEqualize(notification: SwiftUI.Notification) {
guard case .split(let c) = node else { return }
_ = c.equalize()
}
} }
/// A noSplit leaf node of a split tree. /// A noSplit leaf node of a split tree.

View File

@ -3,13 +3,66 @@ import GhosttyKit
extension NSEvent { extension NSEvent {
/// Create a Ghostty key event for a given keyboard action. /// Create a Ghostty key event for a given keyboard action.
func ghosttyKeyEvent(_ action: ghostty_input_action_e) -> ghostty_input_key_s { ///
var key_ev = ghostty_input_key_s() /// This will not set the "text" or "composing" fields since these can't safely be set
/// with the information or lifetimes given.
///
/// The translationMods should be set to the modifiers used for actual character
/// translation if available.
func ghosttyKeyEvent(
_ action: ghostty_input_action_e,
translationMods: NSEvent.ModifierFlags? = nil
) -> ghostty_input_key_s {
var key_ev: ghostty_input_key_s = .init()
key_ev.action = action key_ev.action = action
key_ev.mods = Ghostty.ghosttyMods(modifierFlags)
key_ev.keycode = UInt32(keyCode) key_ev.keycode = UInt32(keyCode)
// We can't infer or set these safely from this method. Since text is
// a cString, we can't use self.characters because of garbage collection.
// We have to let the caller handle this.
key_ev.text = nil key_ev.text = nil
key_ev.composing = false key_ev.composing = false
// macOS provides no easy way to determine the consumed modifiers for
// producing text. We apply a simple heuristic here that has worked for years
// so far: control and command never contribute to the translation of text,
// assume everything else did.
key_ev.mods = Ghostty.ghosttyMods(modifierFlags)
key_ev.consumed_mods = Ghostty.ghosttyMods(
(translationMods ?? modifierFlags)
.subtracting([.control, .command]))
// Our unshifted codepoint is the codepoint with no modifiers. We
// ignore multi-codepoint values.
key_ev.unshifted_codepoint = 0
if type == .keyDown || type == .keyUp {
if let charactersIgnoringModifiers,
let codepoint = charactersIgnoringModifiers.unicodeScalars.first
{
key_ev.unshifted_codepoint = codepoint.value
}
}
return key_ev return key_ev
} }
/// Returns the text to set for a key event for Ghostty.
///
/// This namely contains logic to avoid control characters, since we handle control character
/// mapping manually within Ghostty.
var ghosttyCharacters: String? {
// If we have no characters associated with this event we do nothing.
guard let characters else { return nil }
// If we have a single control character, then we return the characters
// without control pressed. We do this because we handle control character
// encoding directly within Ghostty's KeyEncoder.
if characters.count == 1,
let scalar = characters.unicodeScalars.first,
scalar.value < 0x20 {
return self.characters(byApplyingModifiers: modifierFlags.subtracting(.control))
}
return nil
}
} }

View File

@ -247,6 +247,15 @@ extension Notification.Name {
/// Close tab /// Close tab
static let ghosttyCloseTab = Notification.Name("com.mitchellh.ghostty.closeTab") static let ghosttyCloseTab = Notification.Name("com.mitchellh.ghostty.closeTab")
/// Close window
static let ghosttyCloseWindow = Notification.Name("com.mitchellh.ghostty.closeWindow")
/// Resize the window to a default size.
static let ghosttyResetWindowSize = Notification.Name("com.mitchellh.ghostty.resetWindowSize")
/// Ring the bell
static let ghosttyBellDidRing = Notification.Name("com.mitchellh.ghostty.ghosttyBellDidRing")
} }
// NOTE: I am moving all of these to Notification.Name extensions over time. This // NOTE: I am moving all of these to Notification.Name extensions over time. This

View File

@ -59,6 +59,15 @@ extension Ghostty {
@EnvironmentObject private var ghostty: Ghostty.App @EnvironmentObject private var ghostty: Ghostty.App
var title: String {
var result = surfaceView.title
if (surfaceView.bell) {
result = "🔔 \(result)"
}
return result
}
var body: some View { var body: some View {
let center = NotificationCenter.default let center = NotificationCenter.default
@ -74,7 +83,7 @@ extension Ghostty {
Surface(view: surfaceView, size: geo.size) Surface(view: surfaceView, size: geo.size)
.focused($surfaceFocus) .focused($surfaceFocus)
.focusedValue(\.ghosttySurfaceTitle, surfaceView.title) .focusedValue(\.ghosttySurfaceTitle, title)
.focusedValue(\.ghosttySurfacePwd, surfaceView.pwd) .focusedValue(\.ghosttySurfacePwd, surfaceView.pwd)
.focusedValue(\.ghosttySurfaceView, surfaceView) .focusedValue(\.ghosttySurfaceView, surfaceView)
.focusedValue(\.ghosttySurfaceCellSize, surfaceView.cellSize) .focusedValue(\.ghosttySurfaceCellSize, surfaceView.cellSize)

View File

@ -63,6 +63,9 @@ extension Ghostty {
/// dynamically updated. Otherwise, the background color is the default background color. /// dynamically updated. Otherwise, the background color is the default background color.
@Published private(set) var backgroundColor: Color? = nil @Published private(set) var backgroundColor: Color? = nil
/// True when the bell is active. This is set inactive on focus or event.
@Published private(set) var bell: Bool = false
// An initial size to request for a window. This will only affect // An initial size to request for a window. This will only affect
// then the view is moved to a new window. // then the view is moved to a new window.
var initialSize: NSSize? = nil var initialSize: NSSize? = nil
@ -124,6 +127,11 @@ extension Ghostty {
// A timer to fallback to ghost emoji if no title is set within the grace period // A timer to fallback to ghost emoji if no title is set within the grace period
private var titleFallbackTimer: Timer? private var titleFallbackTimer: Timer?
// This is the title from the terminal. This is nil if we're currently using
// the terminal title as the main title property. If the title is set manually
// by the user, this is set to the prior value (which may be empty, but non-nil).
private var titleFromTerminal: String?
/// Event monitor (see individual events for why) /// Event monitor (see individual events for why)
private var eventMonitor: Any? = nil private var eventMonitor: Any? = nil
@ -185,6 +193,11 @@ extension Ghostty {
selector: #selector(ghosttyColorDidChange(_:)), selector: #selector(ghosttyColorDidChange(_:)),
name: .ghosttyColorDidChange, name: .ghosttyColorDidChange,
object: self) object: self)
center.addObserver(
self,
selector: #selector(ghosttyBellDidRing(_:)),
name: .ghosttyBellDidRing,
object: self)
center.addObserver( center.addObserver(
self, self,
selector: #selector(windowDidChangeScreen), selector: #selector(windowDidChangeScreen),
@ -196,7 +209,14 @@ extension Ghostty {
self.eventMonitor = NSEvent.addLocalMonitorForEvents( self.eventMonitor = NSEvent.addLocalMonitorForEvents(
matching: [ matching: [
// We need keyUp because command+key events don't trigger keyUp. // We need keyUp because command+key events don't trigger keyUp.
.keyUp .keyUp,
// We need leftMouseDown to determine if we should focus ourselves
// when the app/window isn't in focus. We do this instead of
// "acceptsFirstMouse" because that forces us to also handle the
// event and encode the event to the pty which we want to avoid.
// (Issue 2595)
.leftMouseDown,
] ]
) { [weak self] event in self?.localEventHandler(event) } ) { [weak self] event in self?.localEventHandler(event) }
@ -288,9 +308,12 @@ extension Ghostty {
SecureInput.shared.setScoped(ObjectIdentifier(self), focused: focused) SecureInput.shared.setScoped(ObjectIdentifier(self), focused: focused)
} }
// On macOS 13+ we can store our continuous clock...
if (focused) { if (focused) {
// On macOS 13+ we can store our continuous clock...
focusInstant = ContinuousClock.now focusInstant = ContinuousClock.now
// We unset our bell state if we gained focus
bell = false
} }
} }
@ -380,6 +403,45 @@ extension Ghostty {
NSCursor.setHiddenUntilMouseMoves(!visible) NSCursor.setHiddenUntilMouseMoves(!visible)
} }
/// Set the title by prompting the user.
func promptTitle() {
// Create an alert dialog
let alert = NSAlert()
alert.messageText = "Change Terminal Title"
alert.informativeText = "Leave blank to restore the default."
alert.alertStyle = .informational
// Add a text field to the alert
let textField = NSTextField(frame: NSRect(x: 0, y: 0, width: 250, height: 24))
textField.stringValue = title
alert.accessoryView = textField
// Add buttons
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
let response = alert.runModal()
// Check if the user clicked "OK"
if response == .alertFirstButtonReturn {
// Get the input text
let newTitle = textField.stringValue
if newTitle.isEmpty {
// Empty means that user wants the title to be set automatically
// We also need to reload the config for the "title" property to be
// used again by this tab.
let prevTitle = titleFromTerminal ?? "👻"
titleFromTerminal = nil
setTitle(prevTitle)
} else {
// Set the title and prevent it from being changed automatically
titleFromTerminal = title
title = newTitle
}
}
}
func setTitle(_ title: String) { func setTitle(_ title: String) {
// This fixes an issue where very quick changes to the title could // This fixes an issue where very quick changes to the title could
// cause an unpleasant flickering. We set a timer so that we can // cause an unpleasant flickering. We set a timer so that we can
@ -390,6 +452,11 @@ extension Ghostty {
withTimeInterval: 0.075, withTimeInterval: 0.075,
repeats: false repeats: false
) { [weak self] _ in ) { [weak self] _ in
// Set the title if it wasn't manually set.
guard self?.titleFromTerminal == nil else {
self?.titleFromTerminal = title
return
}
self?.title = title self?.title = title
} }
} }
@ -401,11 +468,40 @@ extension Ghostty {
case .keyUp: case .keyUp:
localEventKeyUp(event) localEventKeyUp(event)
case .leftMouseDown:
localEventLeftMouseDown(event)
default: default:
event event
} }
} }
private func localEventLeftMouseDown(_ event: NSEvent) -> NSEvent? {
// We only want to process events that are on this window.
guard let window,
event.window != nil,
window == event.window else { return event }
// The clicked location in this window should be this view.
let location = convert(event.locationInWindow, from: nil)
guard hitTest(location) == self else { return event }
// We only want to grab focus if either our app or window was
// not focused.
guard !NSApp.isActive || !window.isKeyWindow else { return event }
// If we're already focused we do nothing
guard !focused else { return event }
// Make ourselves the first responder
window.makeFirstResponder(self)
// We have to keep processing the event so that AppKit can properly
// focus the window and dispatch events. If you return nil here then
// nobody gets a windowDidBecomeKey event and so on.
return event
}
private func localEventKeyUp(_ event: NSEvent) -> NSEvent? { private func localEventKeyUp(_ event: NSEvent) -> NSEvent? {
// We only care about events with "command" because all others will // We only care about events with "command" because all others will
// trigger the normal responder chain. // trigger the normal responder chain.
@ -471,6 +567,11 @@ extension Ghostty {
} }
} }
@objc private func ghosttyBellDidRing(_ notification: SwiftUI.Notification) {
// Bell state goes to true
bell = true
}
@objc private func windowDidChangeScreen(notification: SwiftUI.Notification) { @objc private func windowDidChangeScreen(notification: SwiftUI.Notification) {
guard let window = self.window else { return } guard let window = self.window else { return }
guard let object = notification.object as? NSWindow, window == object else { return } guard let object = notification.object as? NSWindow, window == object else { return }
@ -571,14 +672,6 @@ extension Ghostty {
ghostty_surface_draw(surface); ghostty_surface_draw(surface);
} }
override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
// "Override this method in a subclass to allow instances to respond to
// click-through. This allows the user to click on a view in an inactive
// window, activating the view with one click, instead of clicking first
// to make the window active and then clicking the view."
return true
}
override func mouseDown(with event: NSEvent) { override func mouseDown(with event: NSEvent) {
guard let surface = self.surface else { return } guard let surface = self.surface else { return }
let mods = Ghostty.ghosttyMods(event.modifierFlags) let mods = Ghostty.ghosttyMods(event.modifierFlags)
@ -666,6 +759,13 @@ extension Ghostty {
override func mouseExited(with event: NSEvent) { override func mouseExited(with event: NSEvent) {
guard let surface = self.surface else { return } guard let surface = self.surface else { return }
// If the mouse is being dragged then we don't have to emit
// this because we get mouse drag events even if we've already
// exited the viewport (i.e. mouseDragged)
if NSEvent.pressedMouseButtons != 0 {
return
}
// Negative values indicate cursor has left the viewport // Negative values indicate cursor has left the viewport
let mods = Ghostty.ghosttyMods(event.modifierFlags) let mods = Ghostty.ghosttyMods(event.modifierFlags)
ghostty_surface_mouse_pos(surface, -1, -1, mods) ghostty_surface_mouse_pos(surface, -1, -1, mods)
@ -771,6 +871,9 @@ extension Ghostty {
return return
} }
// On any keyDown event we unset our bell state
bell = false
// We need to translate the mods (maybe) to handle configs such as option-as-alt // We need to translate the mods (maybe) to handle configs such as option-as-alt
let translationModsGhostty = Ghostty.eventModifierFlags( let translationModsGhostty = Ghostty.eventModifierFlags(
mods: ghostty_surface_key_translation_mods( mods: ghostty_surface_key_translation_mods(
@ -835,6 +938,11 @@ extension Ghostty {
nil nil
} }
// If we are in a keyDown then we don't need to redispatch a command-modded
// key event (see docs for this field) so reset this to nil because
// `interpretKeyEvents` may dispach it.
self.lastPerformKeyEvent = nil
self.interpretKeyEvents([translationEvent]) self.interpretKeyEvents([translationEvent])
// If our keyboard changed from this we just assume an input method // If our keyboard changed from this we just assume an input method
@ -843,29 +951,32 @@ extension Ghostty {
return return
} }
// If we have text, then we've composed a character, send that down. We do this // If we have marked text, we're in a preedit state. The order we
// first because if we completed a preedit, the text will be available here // do this and the key event callbacks below doesn't matter since
// AND we'll have a preedit. // we control the preedit state only through the preedit API.
var handled: Bool = false syncPreedit(clearIfNeeded: markedTextBefore)
if let list = keyTextAccumulator, list.count > 0 { if let list = keyTextAccumulator, list.count > 0 {
handled = true // If we have text, then we've composed a character, send that down.
// These never have "composing" set to true because these are the
// result of a composition.
for text in list { for text in list {
_ = keyAction(action, event: event, text: text) _ = keyAction(
action,
event: event,
translationEvent: translationEvent,
text: text
)
} }
} } else {
// We have no accumulated text so this is a normal key event.
// If we have marked text, we're in a preedit state. Send that down. _ = keyAction(
// If we don't have marked text but we had marked text before, then the preedit action,
// was cleared so we want to send down an empty string to ensure we've cleared event: event,
// the preedit. translationEvent: translationEvent,
if (markedText.length > 0 || markedTextBefore) { text: translationEvent.ghosttyCharacters,
handled = true composing: markedText.length > 0
_ = keyAction(action, event: event, preedit: markedText.string) )
}
if (!handled) {
// No text or anything, we want to handle this manually.
_ = keyAction(action, event: event)
} }
} }
@ -873,6 +984,34 @@ extension Ghostty {
_ = keyAction(GHOSTTY_ACTION_RELEASE, event: event) _ = keyAction(GHOSTTY_ACTION_RELEASE, event: event)
} }
/// Records the timestamp of the last event to performKeyEquivalent that we need to save.
/// We currently save all commands with command or control set.
///
/// For command+key inputs, the AppKit input stack calls performKeyEquivalent to give us a chance
/// to handle them first. If we return "false" then it goes through the standard AppKit responder chain.
/// For an NSTextInputClient, that may redirect some commands _before_ our keyDown gets called.
/// Concretely: Command+Period will do: performKeyEquivalent, doCommand ("cancel:"). In doCommand,
/// we need to know that we actually want to handle that in keyDown, so we send it back through the
/// event dispatch system and use this timestamp as an identity to know to actually send it to keyDown.
///
/// Why not send it to keyDown always? Because if the user rebinds a command to something we
/// actually handle then we do want the standard response chain to handle the key input. Unfortunately,
/// we can't know what a command is bound to at a system level until we let it flow through the system.
/// That's the crux of the problem.
///
/// So, we have to send it back through if we didn't handle it.
///
/// The next part of the problem is comparing NSEvent identity seems pretty nasty. I couldn't
/// find a good way to do it. I originally stored a weak ref and did identity comparison but that
/// doesn't work and for reasons I couldn't figure out the value gets mangled (fields don't match
/// before/after the assignment). I suspect it has something to do with the fact an NSEvent is wrapping
/// a lower level event pointer and its just not surviving the Swift runtime somehow. I don't know.
///
/// The best thing I could find was to store the event timestamp which has decent granularity
/// and compare that. To further complicate things, some events are synthetic and have a zero
/// timestamp so we have to protect against that. Fun!
var lastPerformKeyEvent: TimeInterval?
/// Special case handling for some control keys /// Special case handling for some control keys
override func performKeyEquivalent(with event: NSEvent) -> Bool { override func performKeyEquivalent(with event: NSEvent) -> Bool {
switch (event.type) { switch (event.type) {
@ -907,16 +1046,6 @@ extension Ghostty {
let equivalent: String let equivalent: String
switch (event.charactersIgnoringModifiers) { switch (event.charactersIgnoringModifiers) {
case "/":
// Treat C-/ as C-_. We do this because C-/ makes macOS make a beep
// sound and we don't like the beep sound.
if (!event.modifierFlags.contains(.control) ||
!event.modifierFlags.isDisjoint(with: [.shift, .command, .option])) {
return false
}
equivalent = "_"
case "\r": case "\r":
// Pass C-<return> through verbatim // Pass C-<return> through verbatim
// (prevent the default context menu equivalent) // (prevent the default context menu equivalent)
@ -926,15 +1055,42 @@ extension Ghostty {
equivalent = "\r" equivalent = "\r"
case ".": default:
if (!event.modifierFlags.contains(.command)) { // It looks like some part of AppKit sometimes generates synthetic NSEvents
// with a zero timestamp. We never process these at this point. Concretely,
// this happens for me when pressing Cmd+period with default bindings. This
// binds to "cancel" which goes through AppKit to produce a synthetic "escape".
//
// Question: should we be ignoring all synthetic events? Should we be finding
// synthetic escape and ignoring it? I feel like Cmd+period could map to a
// escape binding by accident, but it hasn't happened yet...
if event.timestamp == 0 {
return false return false
} }
equivalent = "." // All of this logic here re: lastCommandEvent is to workaround some
// nasty behavior. See the docs for lastCommandEvent for more info.
default: // Ignore all other non-command events. This lets the event continue
// Ignore other events // through the AppKit event systems.
if (!event.modifierFlags.contains(.command) &&
!event.modifierFlags.contains(.control)) {
// Reset since we got a non-command event.
lastPerformKeyEvent = nil
return false
}
// If we have a prior command binding and the timestamp matches exactly
// then we pass it through to keyDown for encoding.
if let lastPerformKeyEvent {
self.lastPerformKeyEvent = nil
if lastPerformKeyEvent == event.timestamp {
equivalent = event.characters ?? ""
break
}
}
lastPerformKeyEvent = event.timestamp
return false return false
} }
@ -1002,34 +1158,28 @@ extension Ghostty {
_ = keyAction(action, event: event) _ = keyAction(action, event: event)
} }
private func keyAction(_ action: ghostty_input_action_e, event: NSEvent) -> Bool {
guard let surface = self.surface else { return false }
return ghostty_surface_key(surface, event.ghosttyKeyEvent(action))
}
private func keyAction( private func keyAction(
_ action: ghostty_input_action_e, _ action: ghostty_input_action_e,
event: NSEvent, preedit: String event: NSEvent,
translationEvent: NSEvent? = nil,
text: String? = nil,
composing: Bool = false
) -> Bool { ) -> Bool {
guard let surface = self.surface else { return false } guard let surface = self.surface else { return false }
return preedit.withCString { ptr in var key_ev = event.ghosttyKeyEvent(action, translationMods: translationEvent?.modifierFlags)
var key_ev = event.ghosttyKeyEvent(action) key_ev.composing = composing
key_ev.text = ptr
key_ev.composing = true
return ghostty_surface_key(surface, key_ev)
}
}
private func keyAction( // For text, we only encode UTF8 if we don't have a single control
_ action: ghostty_input_action_e, // character. Control characters are encoded by Ghostty itself.
event: NSEvent, text: String // Without this, `ctrl+enter` does the wrong thing.
) -> Bool { if let text, text.count > 0,
guard let surface = self.surface else { return false } let codepoint = text.utf8.first, codepoint >= 0x20 {
return text.withCString { ptr in
return text.withCString { ptr in key_ev.text = ptr
var key_ev = event.ghosttyKeyEvent(action) return ghostty_surface_key(surface, key_ev)
key_ev.text = ptr }
} else {
return ghostty_surface_key(surface, key_ev) return ghostty_surface_key(surface, key_ev)
} }
} }
@ -1112,11 +1262,15 @@ extension Ghostty {
menu.addItem(.separator()) menu.addItem(.separator())
menu.addItem(withTitle: "Split Right", action: #selector(splitRight(_:)), keyEquivalent: "") menu.addItem(withTitle: "Split Right", action: #selector(splitRight(_:)), keyEquivalent: "")
menu.addItem(withTitle: "Split Left", action: #selector(splitLeft(_:)), keyEquivalent: "")
menu.addItem(withTitle: "Split Down", action: #selector(splitDown(_:)), keyEquivalent: "") menu.addItem(withTitle: "Split Down", action: #selector(splitDown(_:)), keyEquivalent: "")
menu.addItem(withTitle: "Split Up", action: #selector(splitUp(_:)), keyEquivalent: "")
menu.addItem(.separator()) menu.addItem(.separator())
menu.addItem(withTitle: "Reset Terminal", action: #selector(resetTerminal(_:)), keyEquivalent: "") menu.addItem(withTitle: "Reset Terminal", action: #selector(resetTerminal(_:)), keyEquivalent: "")
menu.addItem(withTitle: "Toggle Terminal Inspector", action: #selector(toggleTerminalInspector(_:)), keyEquivalent: "") menu.addItem(withTitle: "Toggle Terminal Inspector", action: #selector(toggleTerminalInspector(_:)), keyEquivalent: "")
menu.addItem(.separator())
menu.addItem(withTitle: "Change Title...", action: #selector(changeTitle(_:)), keyEquivalent: "")
return menu return menu
} }
@ -1169,11 +1323,21 @@ extension Ghostty {
ghostty_surface_split(surface, GHOSTTY_SPLIT_DIRECTION_RIGHT) ghostty_surface_split(surface, GHOSTTY_SPLIT_DIRECTION_RIGHT)
} }
@IBAction func splitLeft(_ sender: Any) {
guard let surface = self.surface else { return }
ghostty_surface_split(surface, GHOSTTY_SPLIT_DIRECTION_LEFT)
}
@IBAction func splitDown(_ sender: Any) { @IBAction func splitDown(_ sender: Any) {
guard let surface = self.surface else { return } guard let surface = self.surface else { return }
ghostty_surface_split(surface, GHOSTTY_SPLIT_DIRECTION_DOWN) ghostty_surface_split(surface, GHOSTTY_SPLIT_DIRECTION_DOWN)
} }
@IBAction func splitUp(_ sender: Any) {
guard let surface = self.surface else { return }
ghostty_surface_split(surface, GHOSTTY_SPLIT_DIRECTION_UP)
}
@objc func resetTerminal(_ sender: Any) { @objc func resetTerminal(_ sender: Any) {
guard let surface = self.surface else { return } guard let surface = self.surface else { return }
let action = "reset" let action = "reset"
@ -1190,6 +1354,10 @@ extension Ghostty {
} }
} }
@IBAction func changeTitle(_ sender: Any) {
promptTitle()
}
/// Show a user notification and associate it with this surface /// Show a user notification and associate it with this surface
func showUserNotification(title: String, body: String) { func showUserNotification(title: String, body: String) {
let content = UNMutableNotificationContent() let content = UNMutableNotificationContent()
@ -1287,10 +1455,21 @@ extension Ghostty.SurfaceView: NSTextInputClient {
default: default:
print("unknown marked text: \(string)") print("unknown marked text: \(string)")
} }
// If we're not in a keyDown event, then we want to update our preedit
// text immediately. This can happen due to external events, for example
// changing keyboard layouts while composing: (1) set US intl (2) type '
// to enter dead key state (3)
if keyTextAccumulator == nil {
syncPreedit()
}
} }
func unmarkText() { func unmarkText() {
self.markedText.mutableString.setString("") if self.markedText.length > 0 {
self.markedText.mutableString.setString("")
syncPreedit()
}
} }
func validAttributesForMarkedText() -> [NSAttributedString.Key] { func validAttributesForMarkedText() -> [NSAttributedString.Key] {
@ -1413,12 +1592,42 @@ extension Ghostty.SurfaceView: NSTextInputClient {
} }
} }
/// This function needs to exist for two reasons:
/// 1. Prevents an audible NSBeep for unimplemented actions.
/// 2. Allows us to properly encode super+key input events that we don't handle
override func doCommand(by selector: Selector) { override func doCommand(by selector: Selector) {
// This currently just prevents NSBeep from interpretKeyEvents but in the future // If we are being processed by performKeyEquivalent with a command binding,
// we may want to make some of this work. // we send it back through the event system so it can be encoded.
if let lastPerformKeyEvent,
let current = NSApp.currentEvent,
lastPerformKeyEvent == current.timestamp
{
NSApp.sendEvent(current)
return
}
print("SEL: \(selector)") print("SEL: \(selector)")
} }
/// Sync the preedit state based on the markedText value to libghostty
private func syncPreedit(clearIfNeeded: Bool = true) {
guard let surface else { return }
if markedText.length > 0 {
let str = markedText.string
let len = str.utf8CString.count
if len > 0 {
markedText.string.withCString { ptr in
// Subtract 1 for the null terminator
ghostty_surface_preedit(surface, ptr, UInt(len - 1))
}
}
} else if clearIfNeeded {
// If we had marked text before but don't now, we're no longer
// in a preedit state so we can clear it.
ghostty_surface_preedit(surface, nil, 0)
}
}
} }
// MARK: Services // MARK: Services

View File

@ -35,6 +35,9 @@ extension Ghostty {
// on supported platforms. // on supported platforms.
@Published var focusInstant: ContinuousClock.Instant? = nil @Published var focusInstant: ContinuousClock.Instant? = nil
/// True when the bell is active. This is set inactive on focus or event.
@Published var bell: Bool = false
// Returns sizing information for the surface. This is the raw C // Returns sizing information for the surface. This is the raw C
// structure because I'm lazy. // structure because I'm lazy.
var surfaceSize: ghostty_surface_size_s? { var surfaceSize: ghostty_surface_size_s? {

View File

@ -6,6 +6,7 @@ enum FullscreenMode {
case native case native
case nonNative case nonNative
case nonNativeVisibleMenu case nonNativeVisibleMenu
case nonNativePaddedNotch
/// Initializes the fullscreen style implementation for the mode. This will not toggle any /// Initializes the fullscreen style implementation for the mode. This will not toggle any
/// fullscreen properties. This may fail if the window isn't configured properly for a given /// fullscreen properties. This may fail if the window isn't configured properly for a given
@ -20,6 +21,9 @@ enum FullscreenMode {
case .nonNativeVisibleMenu: case .nonNativeVisibleMenu:
return NonNativeFullscreenVisibleMenu(window) return NonNativeFullscreenVisibleMenu(window)
case .nonNativePaddedNotch:
return NonNativeFullscreenPaddedNotch(window)
} }
} }
} }
@ -141,6 +145,7 @@ class NonNativeFullscreen: FullscreenBase, FullscreenStyle {
struct Properties { struct Properties {
var hideMenu: Bool = true var hideMenu: Bool = true
var paddedNotch: Bool = false
} }
private var savedState: SavedState? private var savedState: SavedState?
@ -175,7 +180,7 @@ class NonNativeFullscreen: FullscreenBase, FullscreenStyle {
} }
// Hide the menu if requested // Hide the menu if requested
if (properties.hideMenu) { if (properties.hideMenu && savedState.menu) {
hideMenu() hideMenu()
} }
@ -219,7 +224,9 @@ class NonNativeFullscreen: FullscreenBase, FullscreenStyle {
if savedState.dock { if savedState.dock {
unhideDock() unhideDock()
} }
unhideMenu() if (properties.hideMenu && savedState.menu) {
unhideMenu()
}
// Restore our saved state // Restore our saved state
window.styleMask = savedState.styleMask window.styleMask = savedState.styleMask
@ -268,7 +275,8 @@ class NonNativeFullscreen: FullscreenBase, FullscreenStyle {
// calculate this ourselves. // calculate this ourselves.
var frame = screen.frame var frame = screen.frame
if (!properties.hideMenu) { if (!NSApp.presentationOptions.contains(.autoHideMenuBar) &&
!NSApp.presentationOptions.contains(.hideMenuBar)) {
// We need to subtract the menu height since we're still showing it. // We need to subtract the menu height since we're still showing it.
frame.size.height -= NSApp.mainMenu?.menuBarHeight ?? 0 frame.size.height -= NSApp.mainMenu?.menuBarHeight ?? 0
@ -278,6 +286,9 @@ class NonNativeFullscreen: FullscreenBase, FullscreenStyle {
// put an #available check, but it was in a bug fix release so I think // put an #available check, but it was in a bug fix release so I think
// if a bug is reported to Ghostty we can just advise the user to // if a bug is reported to Ghostty we can just advise the user to
// update. // update.
} else if (properties.paddedNotch) {
// We are hiding the menu, we may need to avoid the notch.
frame.size.height -= screen.safeAreaInsets.top
} }
return frame return frame
@ -332,6 +343,7 @@ class NonNativeFullscreen: FullscreenBase, FullscreenStyle {
let contentFrame: NSRect let contentFrame: NSRect
let styleMask: NSWindow.StyleMask let styleMask: NSWindow.StyleMask
let dock: Bool let dock: Bool
let menu: Bool
init?(_ window: NSWindow) { init?(_ window: NSWindow) {
guard let contentView = window.contentView else { return nil } guard let contentView = window.contentView else { return nil }
@ -342,6 +354,18 @@ class NonNativeFullscreen: FullscreenBase, FullscreenStyle {
self.contentFrame = window.convertToScreen(contentView.frame) self.contentFrame = window.convertToScreen(contentView.frame)
self.styleMask = window.styleMask self.styleMask = window.styleMask
self.dock = window.screen?.hasDock ?? false self.dock = window.screen?.hasDock ?? false
// We hide the menu only if this window is not on any fullscreen
// spaces. We do this because fullscreen spaces already hide the
// menu and if we insert/remove this presentation option we get
// issues (see #7075)
let activeSpace = CGSSpace.active()
let spaces = CGSSpace.list(for: window.cgWindowId)
if spaces.contains(activeSpace) {
self.menu = activeSpace.type != .fullscreen
} else {
self.menu = spaces.allSatisfy { $0.type != .fullscreen }
}
} }
} }
} }
@ -349,3 +373,7 @@ class NonNativeFullscreen: FullscreenBase, FullscreenStyle {
class NonNativeFullscreenVisibleMenu: NonNativeFullscreen { class NonNativeFullscreenVisibleMenu: NonNativeFullscreen {
override var properties: Properties { Properties(hideMenu: false) } override var properties: Properties { Properties(hideMenu: false) }
} }
class NonNativeFullscreenPaddedNotch: NonNativeFullscreen {
override var properties: Properties { Properties(paddedNotch: true) }
}

View File

@ -1,5 +1,7 @@
import Cocoa import Cocoa
// MARK: Presentation Options
extension NSApplication { extension NSApplication {
private static var presentationOptionCounts: [NSApplication.PresentationOptions.Element: UInt] = [:] private static var presentationOptionCounts: [NSApplication.PresentationOptions.Element: UInt] = [:]
@ -29,3 +31,13 @@ extension NSApplication.PresentationOptions.Element: @retroactive Hashable {
hasher.combine(rawValue) hasher.combine(rawValue)
} }
} }
// MARK: Frontmost
extension NSApplication {
/// True if the application is frontmost. This isn't exactly the same as isActive because
/// an app can be active but not be frontmost if the window with activity is an NSPanel.
var isFrontmost: Bool {
NSWorkspace.shared.frontmostApplication?.bundleIdentifier == Bundle.main.bundleIdentifier
}
}

View File

@ -34,4 +34,11 @@ extension NSScreen {
return visibleFrame.height < (frame.height - max(menuHeight, notchInset) - boundaryAreaPadding) return visibleFrame.height < (frame.height - max(menuHeight, notchInset) - boundaryAreaPadding)
} }
/// Returns true if the screen has a visible notch (i.e., a non-zero safe area inset at the top).
var hasNotch: Bool {
// We assume that a top safe area means notch, since we don't currently
// know any other situation this is true.
return safeAreaInsets.top > 0
}
} }

View File

@ -0,0 +1,8 @@
import AppKit
extension NSWindow {
/// Get the CGWindowID type for the window (used for low level CoreGraphics APIs).
var cgWindowId: CGWindowID {
CGWindowID(windowNumber)
}
}

View File

@ -0,0 +1,81 @@
import AppKit
// MARK: - CGS Private API Declarations
typealias CGSConnectionID = Int32
typealias CGSSpaceID = size_t
@_silgen_name("CGSMainConnectionID")
private func CGSMainConnectionID() -> CGSConnectionID
@_silgen_name("CGSGetActiveSpace")
private func CGSGetActiveSpace(_ cid: CGSConnectionID) -> CGSSpaceID
@_silgen_name("CGSSpaceGetType")
private func CGSSpaceGetType(_ cid: CGSConnectionID, _ spaceID: CGSSpaceID) -> CGSSpaceType
@_silgen_name("CGSCopySpacesForWindows")
func CGSCopySpacesForWindows(
_ cid: CGSConnectionID,
_ mask: CGSSpaceMask,
_ windowIDs: CFArray
) -> Unmanaged<CFArray>?
// MARK: - CGS Space
/// https://github.com/NUIKit/CGSInternal/blob/c4f6f559d624dc1cfc2bf24c8c19dbf653317fcf/CGSSpace.h#L40
/// converted to Swift
struct CGSSpaceMask: OptionSet {
let rawValue: UInt32
static let includesCurrent = CGSSpaceMask(rawValue: 1 << 0)
static let includesOthers = CGSSpaceMask(rawValue: 1 << 1)
static let includesUser = CGSSpaceMask(rawValue: 1 << 2)
static let includesVisible = CGSSpaceMask(rawValue: 1 << 16)
static let currentSpace: CGSSpaceMask = [.includesUser, .includesCurrent]
static let otherSpaces: CGSSpaceMask = [.includesOthers, .includesCurrent]
static let allSpaces: CGSSpaceMask = [.includesUser, .includesOthers, .includesCurrent]
static let allVisibleSpaces: CGSSpaceMask = [.includesVisible, .allSpaces]
}
/// Represents a unique identifier for a macOS Space (Desktop, Fullscreen, etc).
struct CGSSpace: Hashable, CustomStringConvertible {
let rawValue: CGSSpaceID
var description: String {
"SpaceID(\(rawValue))"
}
/// Returns the currently active space.
static func active() -> CGSSpace {
let space = CGSGetActiveSpace(CGSMainConnectionID())
return .init(rawValue: space)
}
/// List the spaces for the given window.
static func list(for windowID: CGWindowID, mask: CGSSpaceMask = .allSpaces) -> [CGSSpace] {
guard let spaces = CGSCopySpacesForWindows(
CGSMainConnectionID(),
mask,
[windowID] as CFArray
) else { return [] }
guard let spaceIDs = spaces.takeRetainedValue() as? [CGSSpaceID] else { return [] }
return spaceIDs.map(CGSSpace.init)
}
}
// MARK: - CGS Space Types
enum CGSSpaceType: UInt32 {
case user = 0
case system = 2
case fullscreen = 4
}
extension CGSSpace {
var type: CGSSpaceType {
CGSSpaceGetType(CGSMainConnectionID(), rawValue)
}
}

View File

@ -0,0 +1,43 @@
{
pkgs,
lib,
stdenv,
enableX11 ? true,
enableWayland ? true,
}:
[
pkgs.libGL
]
++ lib.optionals stdenv.hostPlatform.isLinux [
pkgs.bzip2
pkgs.expat
pkgs.fontconfig
pkgs.freetype
pkgs.harfbuzz
pkgs.libpng
pkgs.libxml2
pkgs.oniguruma
pkgs.simdutf
pkgs.zlib
pkgs.glslang
pkgs.spirv-cross
pkgs.libxkbcommon
pkgs.glib
pkgs.gobject-introspection
pkgs.gsettings-desktop-schemas
pkgs.gtk4
pkgs.libadwaita
]
++ lib.optionals (stdenv.hostPlatform.isLinux && enableX11) [
pkgs.xorg.libX11
pkgs.xorg.libXcursor
pkgs.xorg.libXi
pkgs.xorg.libXrandr
]
++ lib.optionals (stdenv.hostPlatform.isLinux && enableWayland) [
pkgs.gtk4-layer-shell
pkgs.wayland
]

View File

@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -o nounset -o pipefail -o errexit
find src -name \*.blp -exec blueprint-compiler format {} \+
find src -name \*.blp -exec blueprint-compiler compile --output=/dev/null {} \;

View File

@ -1,4 +1,16 @@
#!/usr/bin/env bash #!/usr/bin/env bash
#
# This script checks if the build.zig.zon.nix file is up-to-date.
# If the `--update` flag is passed, it will update all necessary
# files to be up to date.
#
# The files owned by this are:
#
# - build.zig.zon.nix
# - build.zig.zon.txt
# - build.zig.zon.json
#
# All of these are auto-generated and should not be edited manually.
# Nothing in this script should fail. # Nothing in this script should fail.
set -e set -e
@ -22,43 +34,71 @@ help() {
echo "commit, and submit a PR with the update:" echo "commit, and submit a PR with the update:"
echo "" echo ""
echo " ./nix/build-support/check-zig-cache-hash.sh --update" echo " ./nix/build-support/check-zig-cache-hash.sh --update"
echo " git add build.zig.zon.nix" echo " git add build.zig.zon.nix build.zig.zon.txt build.zig.zon.json"
echo " git commit -m \"nix: update build.zig.zon.nix\"" echo " git commit -m \"nix: update build.zig.zon.nix build.zig.zon.txt build.zig.zon.json\""
echo "" echo ""
} }
BUILD_ZIG_ZON="$(realpath "$(dirname "$0")/../../build.zig.zon")" ROOT="$(realpath "$(dirname "$0")/../../")"
BUILD_ZIG_ZON_LOCK="$(realpath "$(dirname "$0")/../../build.zig.zon2json-lock")" BUILD_ZIG_ZON="$ROOT/build.zig.zon"
BUILD_ZIG_ZON_NIX="$(realpath "$(dirname "$0")/../../build.zig.zon.nix")" BUILD_ZIG_ZON_NIX="$ROOT/build.zig.zon.nix"
BUILD_ZIG_ZON_TXT="$ROOT/build.zig.zon.txt"
BUILD_ZIG_ZON_JSON="$ROOT/build.zig.zon.json"
if [ -f "${BUILD_ZIG_ZON_NIX}" ]; then if [ -f "${BUILD_ZIG_ZON_NIX}" ]; then
OLD_HASH=$(sha512sum "${BUILD_ZIG_ZON_NIX}" | awk '{print $1}') OLD_HASH_NIX=$(sha512sum "${BUILD_ZIG_ZON_NIX}" | awk '{print $1}')
elif [ "$1" != "--update" ]; then elif [ "$1" != "--update" ]; then
echo -e "\nERROR: build.zig.zon.nix missing." echo -e "\nERROR: build.zig.zon.nix missing."
help help
exit 1 exit 1
fi fi
rm -f "$BUILD_ZIG_ZON_LOCK" if [ -f "${BUILD_ZIG_ZON_TXT}" ]; then
zon2nix "$BUILD_ZIG_ZON" > "$WORK_DIR/build.zig.zon.nix" OLD_HASH_TXT=$(sha512sum "${BUILD_ZIG_ZON_TXT}" | awk '{print $1}')
elif [ "$1" != "--update" ]; then
echo -e "\nERROR: build.zig.zon.txt missing."
help
exit 1
fi
if [ -f "${BUILD_ZIG_ZON_JSON}" ]; then
OLD_HASH_JSON=$(sha512sum "${BUILD_ZIG_ZON_JSON}" | awk '{print $1}')
elif [ "$1" != "--update" ]; then
echo -e "\nERROR: build.zig.zon.json missing."
help
exit 1
fi
zon2nix "$BUILD_ZIG_ZON" --nix "$WORK_DIR/build.zig.zon.nix" --txt "$WORK_DIR/build.zig.zon.txt" --json "$WORK_DIR/build.zig.zon.json"
alejandra --quiet "$WORK_DIR/build.zig.zon.nix" alejandra --quiet "$WORK_DIR/build.zig.zon.nix"
rm -f "$BUILD_ZIG_ZON_LOCK" prettier --write "$WORK_DIR/build.zig.zon.json"
NEW_HASH=$(sha512sum "$WORK_DIR/build.zig.zon.nix" | awk '{print $1}') NEW_HASH_NIX=$(sha512sum "$WORK_DIR/build.zig.zon.nix" | awk '{print $1}')
NEW_HASH_TXT=$(sha512sum "$WORK_DIR/build.zig.zon.txt" | awk '{print $1}')
NEW_HASH_JSON=$(sha512sum "$WORK_DIR/build.zig.zon.json" | awk '{print $1}')
if [ "${OLD_HASH}" == "${NEW_HASH}" ]; then if [ "${OLD_HASH_NIX}" == "${NEW_HASH_NIX}" ] && [ "${OLD_HASH_TXT}" == "${NEW_HASH_TXT}" ] && [ "${OLD_HASH_JSON}" == "${NEW_HASH_JSON}" ]; then
echo -e "\nOK: build.zig.zon.nix unchanged." echo -e "\nOK: build.zig.zon.nix unchanged."
echo -e "OK: build.zig.zon.txt unchanged."
echo -e "OK: build.zig.zon.json unchanged."
exit 0 exit 0
elif [ "$1" != "--update" ]; then elif [ "$1" != "--update" ]; then
echo -e "\nERROR: build.zig.zon.nix needs to be updated." echo -e "\nERROR: build.zig.zon.nix, build.zig.zon.txt, or build.zig.zon.json needs to be updated.\n"
echo "" echo " * Old build.zig.zon.nix hash: ${OLD_HASH_NIX}"
echo " * Old hash: ${OLD_HASH}" echo " * New build.zig.zon.nix hash: ${NEW_HASH_NIX}"
echo " * New hash: ${NEW_HASH}" echo " * Old build.zig.zon.txt hash: ${OLD_HASH_TXT}"
echo " * New build.zig.zon.txt hash: ${NEW_HASH_TXT}"
echo " * Old build.zig.zon.json hash: ${OLD_HASH_JSON}"
echo " * New build.zig.zon.json hash: ${NEW_HASH_JSON}"
help help
exit 1 exit 1
else else
mv "$WORK_DIR/build.zig.zon.nix" "$BUILD_ZIG_ZON_NIX" mv "$WORK_DIR/build.zig.zon.nix" "$BUILD_ZIG_ZON_NIX"
echo -e "\nOK: build.zig.zon.nix updated." echo -e "\nOK: build.zig.zon.nix updated."
mv "$WORK_DIR/build.zig.zon.txt" "$BUILD_ZIG_ZON_TXT"
echo -e "OK: build.zig.zon.txt updated."
mv "$WORK_DIR/build.zig.zon.json" "$BUILD_ZIG_ZON_JSON"
echo -e "OK: build.zig.zon.json updated."
exit 0 exit 0
fi fi

View File

@ -0,0 +1,27 @@
#!/bin/sh
# NOTE THIS IS A TEMPORARY SCRIPT TO SUPPORT PACKAGE MAINTAINERS.
#
# A future Zig version will hopefully fix the issue where
# `zig build --fetch` doesn't fetch transitive dependencies[1]. When that
# is resolved, we won't need any special machinery for the general use case
# at all and packagers can just use `zig build --fetch`.
#
# [1]: https://github.com/ziglang/zig/issues/20976
if [ -z ${ZIG_GLOBAL_CACHE_DIR+x} ]
then
echo "must set ZIG_GLOBAL_CACHE_DIR!"
exit 1
fi
# Go through each line of our build.zig.zon.txt and fetch it.
SCRIPT_PATH="$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)"
ZON_TXT_FILE="$SCRIPT_PATH/../../build.zig.zon.txt"
while IFS= read -r url; do
echo "Fetching: $url"
zig fetch "$url" >/dev/null 2>&1 || {
echo "Failed to fetch: $url" >&2
exit 1
}
done < "$ZON_TXT_FILE"

View File

@ -0,0 +1,17 @@
{
pkgs,
lib,
stdenv,
}:
lib.makeSearchPath "lib/girepository-1.0" (map (lib.getOutput "lib") (lib.optionals stdenv.hostPlatform.isLinux [
pkgs.cairo
pkgs.gdk-pixbuf
pkgs.glib
pkgs.gobject-introspection
pkgs.graphene
pkgs.gtk4
pkgs.gtk4-layer-shell
pkgs.harfbuzz
pkgs.libadwaita
pkgs.pango
]))

View File

@ -0,0 +1,10 @@
{
pkgs,
lib,
stdenv,
enableX11 ? true,
enableWayland ? true,
}:
lib.makeLibraryPath (import ./build-inputs.nix {
inherit pkgs lib stdenv enableX11 enableWayland;
})

View File

@ -0,0 +1,30 @@
#!/bin/sh
#
# This script generates a directory that can be uploaded to blob
# storage to mirror our dependencies. The dependencies are unmodified
# so their checksum and content hashes will match.
set -e # Exit immediately if a command exits with a non-zero status
SCRIPT_PATH="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
INPUT_FILE="$SCRIPT_PATH/../../build.zig.zon2json-lock"
OUTPUT_DIR="blob"
# Ensure the output directory exists
mkdir -p "$OUTPUT_DIR"
# Use jq to iterate over the JSON and download files
jq -r 'to_entries[] | "\(.key) \(.value.name) \(.value.url)"' "$INPUT_FILE" | while read -r key name url; do
# Skip URLs that don't start with http(s). They aren't necessary for
# our mirror.
if ! echo "$url" | grep -Eq "^https?://"; then
continue
fi
# Extract the file extension from the URL
extension=$(echo "$url" | grep -oE '\.[a-z0-9]+(\.[a-z0-9]+)?$')
filename="${name}-${key}${extension}"
echo "$url -> $filename"
curl -L -o "$OUTPUT_DIR/$filename" "$url"
done

View File

@ -14,6 +14,7 @@
python3, python3,
qemu, qemu,
scdoc, scdoc,
snapcraft,
valgrind, valgrind,
#, vulkan-loader # unused #, vulkan-loader # unused
vttest, vttest,
@ -30,14 +31,16 @@
glib, glib,
glslang, glslang,
gtk4, gtk4,
gtk4-layer-shell,
gobject-introspection, gobject-introspection,
libadwaita, libadwaita,
blueprint-compiler, blueprint-compiler,
gettext,
adwaita-icon-theme, adwaita-icon-theme,
hicolor-icon-theme, hicolor-icon-theme,
harfbuzz, harfbuzz,
libpng, libpng,
libGL, libxkbcommon,
libX11, libX11,
libXcursor, libXcursor,
libXext, libXext,
@ -49,54 +52,33 @@
simdutf, simdutf,
zlib, zlib,
alejandra, alejandra,
jq,
minisign, minisign,
pandoc, pandoc,
hyperfine, hyperfine,
typos, typos,
uv,
wayland, wayland,
wayland-scanner, wayland-scanner,
wayland-protocols, wayland-protocols,
zig2nix, zon2nix,
system, system,
pkgs,
}: let }: let
# See package.nix. Keep in sync. # See package.nix. Keep in sync.
rpathLibs = ld_library_path = import ./build-support/ld-library-path.nix {
[ inherit pkgs lib stdenv;
libGL };
] gi_typelib_path = import ./build-support/gi-typelib-path.nix {
++ lib.optionals stdenv.hostPlatform.isLinux [ inherit pkgs lib stdenv;
bzip2 };
expat
fontconfig
freetype
harfbuzz
libpng
libxml2
oniguruma
simdutf
zlib
glslang
spirv-cross
libX11
libXcursor
libXi
libXrandr
libadwaita
gtk4
glib
gobject-introspection
wayland
];
in in
mkShell { mkShell {
name = "ghostty"; name = "ghostty";
packages = packages =
[ [
# For builds # For builds
jq
llvmPackages_latest.llvm llvmPackages_latest.llvm
minisign minisign
ncurses ncurses
@ -105,7 +87,7 @@ in
scdoc scdoc
zig zig
zip zip
zig2nix.packages.${system}.zon2nix zon2nix.packages.${system}.zon2nix
# For web and wasm stuff # For web and wasm stuff
nodejs nodejs
@ -124,6 +106,18 @@ in
# wasm # wasm
wabt wabt
wasmtime wasmtime
# Localization
gettext
# CI
uv
# We need these GTK-related deps on all platform so we can build
# dist tarballs.
blueprint-compiler
libadwaita
gtk4
] ]
++ lib.optionals stdenv.hostPlatform.isLinux [ ++ lib.optionals stdenv.hostPlatform.isLinux [
# My nix shell environment installs the non-interactive version # My nix shell environment installs the non-interactive version
@ -135,6 +129,7 @@ in
qemu qemu
gdb gdb
snapcraft
valgrind valgrind
wraptest wraptest
@ -152,6 +147,7 @@ in
glslang glslang
spirv-cross spirv-cross
libxkbcommon
libX11 libX11
libXcursor libXcursor
libXext libXext
@ -160,9 +156,7 @@ in
libXrandr libXrandr
# Only needed for GTK builds # Only needed for GTK builds
blueprint-compiler gtk4-layer-shell
libadwaita
gtk4
glib glib
gobject-introspection gobject-introspection
wayland wayland
@ -172,7 +166,8 @@ in
# This should be set onto the rpath of the ghostty binary if you want # This should be set onto the rpath of the ghostty binary if you want
# it to be "portable" across the system. # it to be "portable" across the system.
LD_LIBRARY_PATH = lib.makeLibraryPath rpathLibs; LD_LIBRARY_PATH = ld_library_path;
GI_TYPELIB_PATH = gi_typelib_path;
shellHook = shellHook =
(lib.optionalString stdenv.hostPlatform.isLinux '' (lib.optionalString stdenv.hostPlatform.isLinux ''
@ -189,5 +184,9 @@ in
# and we need iOS too. # and we need iOS too.
unset SDKROOT unset SDKROOT
unset DEVELOPER_DIR unset DEVELOPER_DIR
# We need to remove "xcrun" from the PATH. It is injected by
# some dependency but we need to rely on system Xcode tools
export PATH=$(echo "$PATH" | awk -v RS=: -v ORS=: '$0 !~ /xcrun/ || $0 == "/usr/bin" {print}' | sed 's/:$//')
''); '');
} }

View File

@ -1,39 +1,24 @@
{ {
lib, lib,
stdenv, stdenv,
bzip2,
callPackage, callPackage,
expat,
fontconfig,
freetype,
harfbuzz,
libpng,
oniguruma,
zlib,
libGL,
glib,
gtk4,
gobject-introspection, gobject-introspection,
libadwaita,
blueprint-compiler, blueprint-compiler,
libxml2,
gettext,
wrapGAppsHook4, wrapGAppsHook4,
gsettings-desktop-schemas,
git, git,
ncurses, ncurses,
pkg-config, pkg-config,
zig_0_13, zig_0_14,
pandoc, pandoc,
revision ? "dirty", revision ? "dirty",
optimize ? "Debug", optimize ? "Debug",
enableX11 ? true, enableX11 ? true,
libX11,
libXcursor,
libXi,
libXrandr,
enableWayland ? true, enableWayland ? true,
wayland,
wayland-protocols, wayland-protocols,
wayland-scanner, wayland-scanner,
pkgs,
}: let }: let
# The Zig hook has no way to select the release type without actual # The Zig hook has no way to select the release type without actual
# overriding of the default flags. # overriding of the default flags.
@ -42,13 +27,19 @@
# https://github.com/ziglang/zig/issues/14281#issuecomment-1624220653 is # https://github.com/ziglang/zig/issues/14281#issuecomment-1624220653 is
# ultimately acted on and has made its way to a nixpkgs implementation, this # ultimately acted on and has made its way to a nixpkgs implementation, this
# can probably be removed in favor of that. # can probably be removed in favor of that.
zig_hook = zig_0_13.hook.overrideAttrs { zig_hook = zig_0_14.hook.overrideAttrs {
zig_default_flags = "-Dcpu=baseline -Doptimize=${optimize} --color off"; zig_default_flags = "-Dcpu=baseline -Doptimize=${optimize} --color off";
}; };
gi_typelib_path = import ./build-support/gi-typelib-path.nix {
inherit pkgs lib stdenv;
};
buildInputs = import ./build-support/build-inputs.nix {
inherit pkgs lib stdenv enableX11 enableWayland;
};
in in
stdenv.mkDerivation (finalAttrs: { stdenv.mkDerivation (finalAttrs: {
pname = "ghostty"; pname = "ghostty";
version = "1.1.2"; version = "1.1.4";
# We limit source like this to try and reduce the amount of rebuilds as possible # We limit source like this to try and reduce the amount of rebuilds as possible
# thus we only provide the source that is needed for the build # thus we only provide the source that is needed for the build
@ -62,6 +53,7 @@ in
../dist/linux ../dist/linux
../images ../images
../include ../include
../po
../pkg ../pkg
../src ../src
../vendor ../vendor
@ -84,43 +76,20 @@ in
gobject-introspection gobject-introspection
wrapGAppsHook4 wrapGAppsHook4
blueprint-compiler blueprint-compiler
libxml2 # for xmllint
gettext
] ]
++ lib.optionals enableWayland [ ++ lib.optionals enableWayland [
wayland-scanner wayland-scanner
wayland-protocols wayland-protocols
]; ];
buildInputs = buildInputs = buildInputs;
[
libGL
]
++ lib.optionals stdenv.hostPlatform.isLinux [
bzip2
expat
fontconfig
freetype
harfbuzz
libpng
oniguruma
zlib
libadwaita
gtk4
glib
gsettings-desktop-schemas
]
++ lib.optionals enableX11 [
libX11
libXcursor
libXi
libXrandr
]
++ lib.optionals enableWayland [
wayland
];
dontConfigure = true; dontConfigure = true;
GI_TYPELIB_PATH = gi_typelib_path;
zigBuildFlags = [ zigBuildFlags = [
"--system" "--system"
"${finalAttrs.deps}" "${finalAttrs.deps}"

3
nix/zigCacheHash.nix Normal file
View File

@ -0,0 +1,3 @@
# This file is auto-generated! check build-support/check-zig-cache-hash.sh for
# more details.
"sha256-S8kS+gO17dl9LJGKL1+kgDUre+vPTmdTvXzgc585Fl8="

View File

@ -1,5 +1,7 @@
.{ .{
.name = "apple-sdk", .name = .apple_sdk,
.version = "0.1.0", .version = "0.1.0",
.dependencies = .{}, .dependencies = .{},
.fingerprint = 0xdde52860f7c464d2,
.paths = .{""},
} }

View File

@ -4,85 +4,85 @@ pub fn build(b: *std.Build) !void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{}); const optimize = b.standardOptimizeOption(.{});
const upstream = b.dependency("breakpad", .{});
const lib = b.addStaticLibrary(.{ const lib = b.addStaticLibrary(.{
.name = "breakpad", .name = "breakpad",
.target = target, .target = target,
.optimize = optimize, .optimize = optimize,
}); });
lib.linkLibCpp(); lib.linkLibCpp();
lib.addIncludePath(upstream.path("src"));
lib.addIncludePath(b.path("vendor")); lib.addIncludePath(b.path("vendor"));
if (target.result.isDarwin()) { if (target.result.os.tag.isDarwin()) {
const apple_sdk = @import("apple_sdk"); const apple_sdk = @import("apple_sdk");
try apple_sdk.addPaths(b, &lib.root_module); try apple_sdk.addPaths(b, lib.root_module);
} }
var flags = std.ArrayList([]const u8).init(b.allocator); var flags = std.ArrayList([]const u8).init(b.allocator);
defer flags.deinit(); defer flags.deinit();
try flags.appendSlice(&.{}); try flags.appendSlice(&.{});
lib.addCSourceFiles(.{ if (b.lazyDependency("breakpad", .{})) |upstream| {
.root = upstream.path(""), lib.addIncludePath(upstream.path("src"));
.files = common,
.flags = flags.items,
});
if (target.result.isDarwin()) {
lib.addCSourceFiles(.{ lib.addCSourceFiles(.{
.root = upstream.path(""), .root = upstream.path(""),
.files = common_apple, .files = common,
.flags = flags.items,
});
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = client_apple,
.flags = flags.items, .flags = flags.items,
}); });
switch (target.result.os.tag) { if (target.result.os.tag.isDarwin()) {
.macos => { lib.addCSourceFiles(.{
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = common_mac,
.flags = flags.items,
});
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = client_mac,
.flags = flags.items,
});
},
.ios => lib.addCSourceFiles(.{
.root = upstream.path(""), .root = upstream.path(""),
.files = client_ios, .files = common_apple,
.flags = flags.items, .flags = flags.items,
}), });
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = client_apple,
.flags = flags.items,
});
else => {}, switch (target.result.os.tag) {
.macos => {
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = common_mac,
.flags = flags.items,
});
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = client_mac,
.flags = flags.items,
});
},
.ios => lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = client_ios,
.flags = flags.items,
}),
else => {},
}
} }
}
if (target.result.os.tag == .linux) { if (target.result.os.tag == .linux) {
lib.addCSourceFiles(.{ lib.addCSourceFiles(.{
.root = upstream.path(""), .root = upstream.path(""),
.files = common_linux, .files = common_linux,
.flags = flags.items, .flags = flags.items,
}); });
lib.addCSourceFiles(.{ lib.addCSourceFiles(.{
.root = upstream.path(""), .root = upstream.path(""),
.files = client_linux, .files = client_linux,
.flags = flags.items, .flags = flags.items,
}); });
} }
lib.installHeadersDirectory( lib.installHeadersDirectory(
upstream.path("src"), upstream.path("src"),
"", "",
.{ .include_extensions = &.{".h"} }, .{ .include_extensions = &.{".h"} },
); );
}
b.installArtifact(lib); b.installArtifact(lib);
} }

View File

@ -1,11 +1,13 @@
.{ .{
.name = "breakpad", .name = .breakpad,
.version = "0.1.0", .version = "0.1.0",
.fingerprint = 0xfe9f9e4c76d5f962,
.paths = .{""}, .paths = .{""},
.dependencies = .{ .dependencies = .{
.breakpad = .{ .breakpad = .{
.url = "https://github.com/getsentry/breakpad/archive/b99f444ba5f6b98cac261cbb391d8766b34a5918.tar.gz", .url = "https://deps.files.ghostty.org/breakpad-b99f444ba5f6b98cac261cbb391d8766b34a5918.tar.gz",
.hash = "12207fd37bb8251919c112dcdd8f616a491857b34a451f7e4486490077206dc2a1ea", .hash = "N-V-__8AALw2uwF_03u4JRkZwRLc3Y9hakkYV7NKRR9-RIZJ",
.lazy = true,
}, },
.apple_sdk = .{ .path = "../apple-sdk" }, .apple_sdk = .{ .path = "../apple-sdk" },

View File

@ -40,7 +40,13 @@ pub fn build(b: *std.Build) !void {
.@"enable-libpng" = true, .@"enable-libpng" = true,
}); });
lib.linkLibrary(freetype.artifact("freetype")); lib.linkLibrary(freetype.artifact("freetype"));
module.addIncludePath(freetype.builder.dependency("freetype", .{}).path("include"));
if (freetype.builder.lazyDependency(
"freetype",
.{},
)) |freetype_dep| {
module.addIncludePath(freetype_dep.path("include"));
}
} }
lib.addIncludePath(imgui.path("")); lib.addIncludePath(imgui.path(""));
@ -76,9 +82,9 @@ pub fn build(b: *std.Build) !void {
.flags = flags.items, .flags = flags.items,
}); });
if (target.result.isDarwin()) { if (target.result.os.tag.isDarwin()) {
if (!target.query.isNative()) { if (!target.query.isNative()) {
try @import("apple_sdk").addPaths(b, &lib.root_module); try @import("apple_sdk").addPaths(b, lib.root_module);
try @import("apple_sdk").addPaths(b, module); try @import("apple_sdk").addPaths(b, module);
} }
lib.addCSourceFile(.{ lib.addCSourceFile(.{

View File

@ -1,13 +1,15 @@
.{ .{
.name = "cimgui", .name = .cimgui,
.version = "1.90.6", // -docking branch .version = "1.90.6", // -docking branch
.fingerprint = 0x49726f5f8acbc90d,
.paths = .{""}, .paths = .{""},
.dependencies = .{ .dependencies = .{
// This should be kept in sync with the submodule in the cimgui source // This should be kept in sync with the submodule in the cimgui source
// code in ./vendor/ to be safe that they're compatible. // code in ./vendor/ to be safe that they're compatible.
.imgui = .{ .imgui = .{
.url = "https://github.com/ocornut/imgui/archive/e391fe2e66eb1c96b1624ae8444dc64c23146ef4.tar.gz", // ocornut/imgui
.hash = "1220bc6b9daceaf7c8c60f3c3998058045ba0c5c5f48ae255ff97776d9cd8bfc6402", .url = "https://deps.files.ghostty.org/imgui-1220bc6b9daceaf7c8c60f3c3998058045ba0c5c5f48ae255ff97776d9cd8bfc6402.tar.gz",
.hash = "N-V-__8AAH0GaQC8a52s6vfIxg88OZgFgEW6DFxfSK4lX_l3",
}, },
.apple_sdk = .{ .path = "../apple-sdk" }, .apple_sdk = .{ .path = "../apple-sdk" },

View File

@ -64,7 +64,6 @@ fn buildLib(b: *std.Build, module: *std.Build.Module, options: anytype) !*std.Bu
const libxml2_iconv_enabled = options.libxml2_iconv_enabled; const libxml2_iconv_enabled = options.libxml2_iconv_enabled;
const freetype_enabled = options.freetype_enabled; const freetype_enabled = options.freetype_enabled;
const upstream = b.dependency("fontconfig", .{});
const lib = b.addStaticLibrary(.{ const lib = b.addStaticLibrary(.{
.name = "fontconfig", .name = "fontconfig",
.target = target, .target = target,
@ -75,9 +74,7 @@ fn buildLib(b: *std.Build, module: *std.Build.Module, options: anytype) !*std.Bu
lib.linkSystemLibrary("pthread"); lib.linkSystemLibrary("pthread");
} }
lib.addIncludePath(upstream.path(""));
lib.addIncludePath(b.path("override/include")); lib.addIncludePath(b.path("override/include"));
module.addIncludePath(upstream.path(""));
module.addIncludePath(b.path("override/include")); module.addIncludePath(b.path("override/include"));
var flags = std.ArrayList([]const u8).init(b.allocator); var flags = std.ArrayList([]const u8).init(b.allocator);
@ -188,11 +185,12 @@ fn buildLib(b: *std.Build, module: *std.Build.Module, options: anytype) !*std.Bu
if (b.systemIntegrationOption("freetype", .{})) { if (b.systemIntegrationOption("freetype", .{})) {
lib.linkSystemLibrary2("freetype2", dynamic_link_opts); lib.linkSystemLibrary2("freetype2", dynamic_link_opts);
} else { } else {
const freetype_dep = b.dependency( if (b.lazyDependency(
"freetype", "freetype",
.{ .target = target, .optimize = optimize }, .{ .target = target, .optimize = optimize },
); )) |freetype_dep| {
lib.linkLibrary(freetype_dep.artifact("freetype")); lib.linkLibrary(freetype_dep.artifact("freetype"));
}
} }
} }
@ -214,26 +212,31 @@ fn buildLib(b: *std.Build, module: *std.Build.Module, options: anytype) !*std.Bu
if (b.systemIntegrationOption("libxml2", .{})) { if (b.systemIntegrationOption("libxml2", .{})) {
lib.linkSystemLibrary2("libxml-2.0", dynamic_link_opts); lib.linkSystemLibrary2("libxml-2.0", dynamic_link_opts);
} else { } else {
const libxml2_dep = b.dependency("libxml2", .{ if (b.lazyDependency("libxml2", .{
.target = target, .target = target,
.optimize = optimize, .optimize = optimize,
.iconv = libxml2_iconv_enabled, .iconv = libxml2_iconv_enabled,
}); })) |libxml2_dep| {
lib.linkLibrary(libxml2_dep.artifact("xml2")); lib.linkLibrary(libxml2_dep.artifact("xml2"));
}
} }
} }
lib.addCSourceFiles(.{ if (b.lazyDependency("fontconfig", .{})) |upstream| {
.root = upstream.path(""), lib.addIncludePath(upstream.path(""));
.files = srcs, module.addIncludePath(upstream.path(""));
.flags = flags.items, lib.addCSourceFiles(.{
}); .root = upstream.path(""),
.files = srcs,
.flags = flags.items,
});
lib.installHeadersDirectory( lib.installHeadersDirectory(
upstream.path("fontconfig"), upstream.path("fontconfig"),
"fontconfig", "fontconfig",
.{ .include_extensions = &.{".h"} }, .{ .include_extensions = &.{".h"} },
); );
}
b.installArtifact(lib); b.installArtifact(lib);

View File

@ -1,13 +1,16 @@
.{ .{
.name = "fontconfig", .name = .fontconfig,
.version = "2.14.2", .version = "2.14.2",
.fingerprint = 0x4a79a5a40c6d6d8,
.paths = .{""},
.dependencies = .{ .dependencies = .{
.fontconfig = .{ .fontconfig = .{
.url = "https://deps.files.ghostty.org/fontconfig-2.14.2.tar.gz", .url = "https://deps.files.ghostty.org/fontconfig-2.14.2.tar.gz",
.hash = "12201149afb3326c56c05bb0a577f54f76ac20deece63aa2f5cd6ff31a4fa4fcb3b7", .hash = "N-V-__8AAIrfdwARSa-zMmxWwFuwpXf1T3asIN7s5jqi9c1v",
.lazy = true,
}, },
.freetype = .{ .path = "../freetype" }, .freetype = .{ .path = "../freetype", .lazy = true },
.libxml2 = .{ .path = "../libxml2" }, .libxml2 = .{ .path = "../libxml2", .lazy = true },
}, },
} }

View File

@ -84,7 +84,7 @@ pub const Property = enum {
pub fn cval(self: Property) [:0]const u8 { pub fn cval(self: Property) [:0]const u8 {
@setEvalBranchQuota(10_000); @setEvalBranchQuota(10_000);
inline for (@typeInfo(Property).Enum.fields) |field| { inline for (@typeInfo(Property).@"enum".fields) |field| {
if (self == @field(Property, field.name)) { if (self == @field(Property, field.name)) {
// Build our string in a comptime context so it is a binary // Build our string in a comptime context so it is a binary
// constant and not stack allocated. // constant and not stack allocated.

View File

@ -61,20 +61,17 @@ fn buildLib(b: *std.Build, module: *std.Build.Module, options: anytype) !*std.Bu
const libpng_enabled = options.libpng_enabled; const libpng_enabled = options.libpng_enabled;
const upstream = b.dependency("freetype", .{});
const lib = b.addStaticLibrary(.{ const lib = b.addStaticLibrary(.{
.name = "freetype", .name = "freetype",
.target = target, .target = target,
.optimize = optimize, .optimize = optimize,
}); });
lib.linkLibC(); lib.linkLibC();
lib.addIncludePath(upstream.path("include")); if (target.result.os.tag.isDarwin()) {
if (target.result.isDarwin()) {
const apple_sdk = @import("apple_sdk"); const apple_sdk = @import("apple_sdk");
try apple_sdk.addPaths(b, &lib.root_module); try apple_sdk.addPaths(b, lib.root_module);
} }
module.addIncludePath(upstream.path("include"));
var flags = std.ArrayList([]const u8).init(b.allocator); var flags = std.ArrayList([]const u8).init(b.allocator);
defer flags.deinit(); defer flags.deinit();
try flags.appendSlice(&.{ try flags.appendSlice(&.{
@ -114,48 +111,52 @@ fn buildLib(b: *std.Build, module: *std.Build.Module, options: anytype) !*std.Bu
} }
} }
lib.addCSourceFiles(.{ if (b.lazyDependency("freetype", .{})) |upstream| {
.root = upstream.path(""), lib.addIncludePath(upstream.path("include"));
.files = srcs, module.addIncludePath(upstream.path("include"));
.flags = flags.items, lib.addCSourceFiles(.{
}); .root = upstream.path(""),
.files = srcs,
.flags = flags.items,
});
switch (target.result.os.tag) { switch (target.result.os.tag) {
.linux => lib.addCSourceFile(.{ .linux => lib.addCSourceFile(.{
.file = upstream.path("builds/unix/ftsystem.c"), .file = upstream.path("builds/unix/ftsystem.c"),
.flags = flags.items,
}),
.windows => lib.addCSourceFile(.{
.file = upstream.path("builds/windows/ftsystem.c"),
.flags = flags.items,
}),
else => lib.addCSourceFile(.{
.file = upstream.path("src/base/ftsystem.c"),
.flags = flags.items,
}),
}
switch (target.result.os.tag) {
.windows => {
lib.addCSourceFile(.{
.file = upstream.path("builds/windows/ftdebug.c"),
.flags = flags.items, .flags = flags.items,
}); }),
lib.addWin32ResourceFile(.{ .windows => lib.addCSourceFile(.{
.file = upstream.path("src/base/ftver.rc"), .file = upstream.path("builds/windows/ftsystem.c"),
}); .flags = flags.items,
}, }),
else => lib.addCSourceFile(.{ else => lib.addCSourceFile(.{
.file = upstream.path("src/base/ftdebug.c"), .file = upstream.path("src/base/ftsystem.c"),
.flags = flags.items, .flags = flags.items,
}), }),
} }
switch (target.result.os.tag) {
.windows => {
lib.addCSourceFile(.{
.file = upstream.path("builds/windows/ftdebug.c"),
.flags = flags.items,
});
lib.addWin32ResourceFile(.{
.file = upstream.path("src/base/ftver.rc"),
});
},
else => lib.addCSourceFile(.{
.file = upstream.path("src/base/ftdebug.c"),
.flags = flags.items,
}),
}
lib.installHeader(b.path("freetype-zig.h"), "freetype-zig.h"); lib.installHeader(b.path("freetype-zig.h"), "freetype-zig.h");
lib.installHeadersDirectory( lib.installHeadersDirectory(
upstream.path("include"), upstream.path("include"),
"", "",
.{ .include_extensions = &.{".h"} }, .{ .include_extensions = &.{".h"} },
); );
}
b.installArtifact(lib); b.installArtifact(lib);

View File

@ -1,11 +1,14 @@
.{ .{
.name = "freetype", .name = .freetype,
.version = "2.13.2", .version = "2.13.2",
.fingerprint = 0xac2059b6f7bbfe0a,
.paths = .{""}, .paths = .{""},
.dependencies = .{ .dependencies = .{
// freetype/freetype
.freetype = .{ .freetype = .{
.url = "https://github.com/freetype/freetype/archive/refs/tags/VER-2-13-2.tar.gz", .url = "https://deps.files.ghostty.org/freetype-1220b81f6ecfb3fd222f76cf9106fecfa6554ab07ec7fdc4124b9bb063ae2adf969d.tar.gz",
.hash = "1220b81f6ecfb3fd222f76cf9106fecfa6554ab07ec7fdc4124b9bb063ae2adf969d", .hash = "N-V-__8AAKLKpwC4H27Ps_0iL3bPkQb-z6ZVSrB-x_3EEkub",
.lazy = true,
}, },
.apple_sdk = .{ .path = "../apple-sdk" }, .apple_sdk = .{ .path = "../apple-sdk" },

View File

@ -278,7 +278,9 @@ pub const LoadFlags = packed struct {
color: bool = false, color: bool = false,
compute_metrics: bool = false, compute_metrics: bool = false,
bitmap_metrics_only: bool = false, bitmap_metrics_only: bool = false,
_padding2: u9 = 0, _padding2: u1 = 0,
no_svg: bool = false,
_padding3: u7 = 0,
test { test {
// This must always be an i32 size so we can bitcast directly. // This must always be an i32 size so we can bitcast directly.

209
pkg/glfw/Cursor.zig Normal file
View File

@ -0,0 +1,209 @@
//! Represents a cursor and provides facilities for setting cursor images.
const std = @import("std");
const testing = std.testing;
const c = @import("c.zig").c;
const Image = @import("Image.zig");
const internal_debug = @import("internal_debug.zig");
const Cursor = @This();
ptr: *c.GLFWcursor,
/// Standard system cursor shapes.
///
/// These are the standard cursor shapes that can be requested from the platform (window system).
pub const Shape = enum(i32) {
/// The regular arrow cursor shape.
arrow = c.GLFW_ARROW_CURSOR,
/// The text input I-beam cursor shape.
ibeam = c.GLFW_IBEAM_CURSOR,
/// The crosshair cursor shape.
crosshair = c.GLFW_CROSSHAIR_CURSOR,
/// The pointing hand cursor shape.
///
/// NOTE: This supersedes the old `hand` enum.
pointing_hand = c.GLFW_POINTING_HAND_CURSOR,
/// The horizontal resize/move arrow shape.
///
/// The horizontal resize/move arrow shape. This is usually a horizontal double-headed arrow.
//
// NOTE: This supersedes the old `hresize` enum.
resize_ew = c.GLFW_RESIZE_EW_CURSOR,
/// The vertical resize/move arrow shape.
///
/// The vertical resize/move shape. This is usually a vertical double-headed arrow.
///
/// NOTE: This supersedes the old `vresize` enum.
resize_ns = c.GLFW_RESIZE_NS_CURSOR,
/// The top-left to bottom-right diagonal resize/move arrow shape.
///
/// The top-left to bottom-right diagonal resize/move shape. This is usually a diagonal
/// double-headed arrow.
///
/// macos: This shape is provided by a private system API and may fail CursorUnavailable in the
/// future.
///
/// x11: This shape is provided by a newer standard not supported by all cursor themes.
///
/// wayland: This shape is provided by a newer standard not supported by all cursor themes.
resize_nwse = c.GLFW_RESIZE_NWSE_CURSOR,
/// The top-right to bottom-left diagonal resize/move arrow shape.
///
/// The top-right to bottom-left diagonal resize/move shape. This is usually a diagonal
/// double-headed arrow.
///
/// macos: This shape is provided by a private system API and may fail with CursorUnavailable
/// in the future.
///
/// x11: This shape is provided by a newer standard not supported by all cursor themes.
///
/// wayland: This shape is provided by a newer standard not supported by all cursor themes.
resize_nesw = c.GLFW_RESIZE_NESW_CURSOR,
/// The omni-directional resize/move cursor shape.
///
/// The omni-directional resize cursor/move shape. This is usually either a combined horizontal
/// and vertical double-headed arrow or a grabbing hand.
resize_all = c.GLFW_RESIZE_ALL_CURSOR,
/// The operation-not-allowed shape.
///
/// The operation-not-allowed shape. This is usually a circle with a diagonal line through it.
///
/// x11: This shape is provided by a newer standard not supported by all cursor themes.
///
/// wayland: This shape is provided by a newer standard not supported by all cursor themes.
not_allowed = c.GLFW_NOT_ALLOWED_CURSOR,
};
/// Creates a custom cursor.
///
/// Creates a new custom cursor image that can be set for a window with glfw.Cursor.set. The cursor
/// can be destroyed with glfwCursor.destroy. Any remaining cursors are destroyed by glfw.terminate.
///
/// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with
/// the red channel first. They are arranged canonically as packed sequential rows, starting from
/// the top-left corner.
///
/// The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor
/// image. Like all other coordinate systems in GLFW, the X-axis points to the right and the Y-axis
/// points down.
///
/// @param[in] image The desired cursor image.
/// @param[in] xhot The desired x-coordinate, in pixels, of the cursor hotspot.
/// @param[in] yhot The desired y-coordinate, in pixels, of the cursor hotspot.
/// @return The handle of the created cursor.
///
/// Possible errors include glfw.ErrorCode.PlatformError and glfw.ErrorCode.InvalidValue
/// null is returned in the event of an error.
///
/// @pointer_lifetime The specified image data is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_object, glfw.Cursor.destroy, glfw.Cursor.createStandard
pub inline fn create(image: Image, xhot: i32, yhot: i32) ?Cursor {
internal_debug.assertInitialized();
const img = image.toC();
if (c.glfwCreateCursor(&img, @as(c_int, @intCast(xhot)), @as(c_int, @intCast(yhot)))) |cursor| return Cursor{ .ptr = cursor };
return null;
}
/// Creates a cursor with a standard shape.
///
/// Returns a cursor with a standard shape, that can be set for a window with glfw.Window.setCursor.
/// The images for these cursors come from the system cursor theme and their exact appearance will
/// vary between platforms.
///
/// Most of these shapes are guaranteed to exist on every supported platform but a few may not be
/// present. See the table below for details.
///
/// | Cursor shape | Windows | macOS | X11 | Wayland |
/// |------------------|---------|-----------------|-------------------|-------------------|
/// | `.arrow` | Yes | Yes | Yes | Yes |
/// | `.ibeam` | Yes | Yes | Yes | Yes |
/// | `.crosshair` | Yes | Yes | Yes | Yes |
/// | `.pointing_hand` | Yes | Yes | Yes | Yes |
/// | `.resize_ew` | Yes | Yes | Yes | Yes |
/// | `.resize_ns` | Yes | Yes | Yes | Yes |
/// | `.resize_nwse` | Yes | Yes<sup>1</sup> | Maybe<sup>2</sup> | Maybe<sup>2</sup> |
/// | `.resize_nesw` | Yes | Yes<sup>1</sup> | Maybe<sup>2</sup> | Maybe<sup>2</sup> |
/// | `.resize_all` | Yes | Yes | Yes | Yes |
/// | `.not_allowed` | Yes | Yes | Maybe<sup>2</sup> | Maybe<sup>2</sup> |
///
/// 1. This uses a private system API and may fail in the future.
/// 2. This uses a newer standard that not all cursor themes support.
///
/// If the requested shape is not available, this function emits a CursorUnavailable error
/// Possible errors include glfw.ErrorCode.PlatformError and glfw.ErrorCode.CursorUnavailable.
/// null is returned in the event of an error.
///
/// thread_safety: This function must only be called from the main thread.
///
/// see also: cursor_object, glfwCreateCursor
pub inline fn createStandard(shape: Shape) ?Cursor {
internal_debug.assertInitialized();
if (c.glfwCreateStandardCursor(@as(c_int, @intCast(@intFromEnum(shape))))) |cursor| return Cursor{ .ptr = cursor };
return null;
}
/// Destroys a cursor.
///
/// This function destroys a cursor previously created with glfw.Cursor.create. Any remaining
/// cursors will be destroyed by glfw.terminate.
///
/// If the specified cursor is current for any window, that window will be reverted to the default
/// cursor. This does not affect the cursor mode.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: cursor_object, glfw.createCursor
pub inline fn destroy(self: Cursor) void {
internal_debug.assertInitialized();
c.glfwDestroyCursor(self.ptr);
}
test "create" {
const allocator = testing.allocator;
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const image = try Image.init(allocator, 32, 32, 32 * 32 * 4);
defer image.deinit(allocator);
const cursor = glfw.Cursor.create(image, 0, 0);
if (cursor) |cur| cur.destroy();
}
test "createStandard" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const cursor = glfw.Cursor.createStandard(.ibeam);
if (cursor) |cur| cur.destroy();
}

74
pkg/glfw/GammaRamp.zig Normal file
View File

@ -0,0 +1,74 @@
//! Gamma ramp for monitors and related functions.
//!
//! It may be .owned (e.g. in the case of a gamma ramp initialized by you for passing into
//! glfw.Monitor.setGammaRamp) or not .owned (e.g. in the case of one gotten via
//! glfw.Monitor.getGammaRamp.) If it is .owned, deinit should be called to free the memory. It is
//! safe to call deinit even if not .owned.
//!
//! see also: monitor_gamma, glfw.Monitor.getGammaRamp
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const c = @import("c.zig").c;
const GammaRamp = @This();
red: []u16,
green: []u16,
blue: []u16,
owned: ?[]u16,
/// Initializes a new owned gamma ramp with the given array size and undefined values.
///
/// see also: glfw.Monitor.getGammaRamp
pub inline fn init(allocator: mem.Allocator, size: usize) !GammaRamp {
const buf = try allocator.alloc(u16, size * 3);
return GammaRamp{
.red = buf[size * 0 .. (size * 0) + size],
.green = buf[size * 1 .. (size * 1) + size],
.blue = buf[size * 2 .. (size * 2) + size],
.owned = buf,
};
}
/// Turns a GLFW / C gamma ramp into the nicer Zig type, and sets `.owned = false`.
///
/// The returned memory is valid for as long as the GLFW C memory is valid.
pub inline fn fromC(native: c.GLFWgammaramp) GammaRamp {
return GammaRamp{
.red = native.red[0..native.size],
.green = native.green[0..native.size],
.blue = native.blue[0..native.size],
.owned = null,
};
}
/// Turns the nicer Zig type into a GLFW / C gamma ramp, for passing into GLFW C functions.
///
/// The returned memory is valid for as long as the Zig memory is valid.
pub inline fn toC(self: GammaRamp) c.GLFWgammaramp {
std.debug.assert(self.red.len == self.green.len);
std.debug.assert(self.red.len == self.blue.len);
return c.GLFWgammaramp{
.red = &self.red[0],
.green = &self.green[0],
.blue = &self.blue[0],
.size = @as(c_uint, @intCast(self.red.len)),
};
}
/// Deinitializes the memory using the allocator iff `.owned = true`.
pub inline fn deinit(self: GammaRamp, allocator: mem.Allocator) void {
if (self.owned) |buf| allocator.free(buf);
}
test "conversion" {
const allocator = testing.allocator;
const ramp = try GammaRamp.init(allocator, 256);
defer ramp.deinit(allocator);
const glfw = ramp.toC();
_ = GammaRamp.fromC(glfw);
}

82
pkg/glfw/Image.zig Normal file
View File

@ -0,0 +1,82 @@
//! Image data
//!
//!
//! This describes a single 2D image. See the documentation for each related function what the
//! expected pixel format is.
//!
//! see also: cursor_custom, window_icon
//!
//! It may be .owned (e.g. in the case of an image initialized by you for passing into glfw) or not
//! .owned (e.g. in the case of one gotten via glfw) If it is .owned, deinit should be called to
//! free the memory. It is safe to call deinit even if not .owned.
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const c = @import("c.zig").c;
const Image = @This();
/// The width of this image, in pixels.
width: u32,
/// The height of this image, in pixels.
height: u32,
/// The pixel data of this image, arranged left-to-right, top-to-bottom.
pixels: []u8,
/// Whether or not the pixels data is owned by you (true) or GLFW (false).
owned: bool,
/// Initializes a new owned image with the given size and pixel_data_len of undefined .pixel values.
pub inline fn init(allocator: mem.Allocator, width: u32, height: u32, pixel_data_len: usize) !Image {
const buf = try allocator.alloc(u8, pixel_data_len);
return Image{
.width = width,
.height = height,
.pixels = buf,
.owned = true,
};
}
/// Turns a GLFW / C image into the nicer Zig type, and sets `.owned = false`.
///
/// The length of pixel data must be supplied, as GLFW's image type does not itself describe the
/// number of bytes required per pixel / the length of the pixel data array.
///
/// The returned memory is valid for as long as the GLFW C memory is valid.
pub inline fn fromC(native: c.GLFWimage, pixel_data_len: usize) Image {
return Image{
.width = @as(u32, @intCast(native.width)),
.height = @as(u32, @intCast(native.height)),
.pixels = native.pixels[0..pixel_data_len],
.owned = false,
};
}
/// Turns the nicer Zig type into a GLFW / C image, for passing into GLFW C functions.
///
/// The returned memory is valid for as long as the Zig memory is valid.
pub inline fn toC(self: Image) c.GLFWimage {
return c.GLFWimage{
.width = @as(c_int, @intCast(self.width)),
.height = @as(c_int, @intCast(self.height)),
.pixels = &self.pixels[0],
};
}
/// Deinitializes the memory using the allocator iff `.owned = true`.
pub inline fn deinit(self: Image, allocator: mem.Allocator) void {
if (self.owned) allocator.free(self.pixels);
}
test "conversion" {
const allocator = testing.allocator;
const image = try Image.init(allocator, 256, 256, 256 * 256 * 4);
defer image.deinit(allocator);
const glfw = image.toC();
_ = Image.fromC(glfw, image.width * image.height * 4);
}

642
pkg/glfw/Joystick.zig Normal file
View File

@ -0,0 +1,642 @@
//! Represents a Joystick or gamepad
//!
//! It can be manually crafted via e.g. `glfw.Joystick{.jid = .one}`, but more
//! typically you'll want to discover the joystick using `glfw.Joystick.setCallback`.
const std = @import("std");
const c = @import("c.zig").c;
const Window = @import("Window.zig");
const Action = @import("action.zig").Action;
const GamepadAxis = @import("gamepad_axis.zig").GamepadAxis;
const GamepadButton = @import("gamepad_button.zig").GamepadButton;
const Hat = @import("hat.zig").Hat;
const internal_debug = @import("internal_debug.zig");
const Joystick = @This();
/// The GLFW joystick ID.
jid: Id,
/// Joystick IDs.
///
/// See glfw.Joystick.setCallback for how these are used.
pub const Id = enum(c_int) {
one = c.GLFW_JOYSTICK_1,
two = c.GLFW_JOYSTICK_2,
three = c.GLFW_JOYSTICK_3,
four = c.GLFW_JOYSTICK_4,
five = c.GLFW_JOYSTICK_5,
six = c.GLFW_JOYSTICK_6,
seven = c.GLFW_JOYSTICK_7,
eight = c.GLFW_JOYSTICK_8,
nine = c.GLFW_JOYSTICK_9,
ten = c.GLFW_JOYSTICK_10,
eleven = c.GLFW_JOYSTICK_11,
twelve = c.GLFW_JOYSTICK_12,
thirteen = c.GLFW_JOYSTICK_13,
fourteen = c.GLFW_JOYSTICK_14,
fifteen = c.GLFW_JOYSTICK_15,
sixteen = c.GLFW_JOYSTICK_16,
pub const last = @as(@This(), @enumFromInt(c.GLFW_JOYSTICK_LAST));
};
/// Gamepad input state
///
/// This describes the input state of a gamepad.
///
/// see also: gamepad, glfwGetGamepadState
const GamepadState = extern struct {
/// The states of each gamepad button (see gamepad_buttons), `glfw.Action.press` or `glfw.Action.release`.
///
/// Use the enumeration helper e.g. `.getButton(.dpad_up)` to access these indices.
buttons: [15]u8,
/// The states of each gamepad axis (see gamepad_axes), in the range -1.0 to 1.0 inclusive.
///
/// Use the enumeration helper e.g. `.getAxis(.left_x)` to access these indices.
axes: [6]f32,
/// Returns the state of the specified gamepad button.
pub fn getButton(self: @This(), which: GamepadButton) Action {
return @as(Action, @enumFromInt(self.buttons[@as(u32, @intCast(@intFromEnum(which)))]));
}
/// Returns the status of the specified gamepad axis, in the range -1.0 to 1.0 inclusive.
pub fn getAxis(self: @This(), which: GamepadAxis) f32 {
return self.axes[@as(u32, @intCast(@intFromEnum(which)))];
}
};
/// Returns whether the specified joystick is present.
///
/// This function returns whether the specified joystick is present.
///
/// There is no need to call this function before other functions that accept a joystick ID, as
/// they all check for presence before performing any other work.
///
/// @return `true` if the joystick is present, or `false` otherwise.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick
pub inline fn present(self: Joystick) bool {
internal_debug.assertInitialized();
const is_present = c.glfwJoystickPresent(@intFromEnum(self.jid));
return is_present == c.GLFW_TRUE;
}
/// Returns the values of all axes of the specified joystick.
///
/// This function returns the values of all axes of the specified joystick. Each element in the
/// array is a value between -1.0 and 1.0.
///
/// If the specified joystick is not present this function will return null but will not generate
/// an error. This can be used instead of first calling glfw.Joystick.present.
///
/// @return An array of axis values, or null if the joystick is not present.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned array is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected or the library is
/// terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_axis
/// Replaces `glfwGetJoystickPos`.
pub inline fn getAxes(self: Joystick) ?[]const f32 {
internal_debug.assertInitialized();
var count: c_int = undefined;
const axes = c.glfwGetJoystickAxes(@intFromEnum(self.jid), &count);
if (axes == null) return null;
return axes[0..@as(u32, @intCast(count))];
}
/// Returns the state of all buttons of the specified joystick.
///
/// This function returns the state of all buttons of the specified joystick. Each element in the
/// array is either `glfw.Action.press` or `glfw.Action.release`.
///
/// For backward compatibility with earlier versions that did not have glfw.Joystick.getHats, the
/// button array also includes all hats, each represented as four buttons. The hats are in the same
/// order as returned by glfw.Joystick.getHats and are in the order _up_, _right_, _down_ and
/// _left_. To disable these extra buttons, set the glfw.joystick_hat_buttons init hint before
/// initialization.
///
/// If the specified joystick is not present this function will return null but will not generate an
/// error. This can be used instead of first calling glfw.Joystick.present.
///
/// @return An array of button states, or null if the joystick is not present.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned array is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_button
pub inline fn getButtons(self: Joystick) ?[]const u8 {
internal_debug.assertInitialized();
var count: c_int = undefined;
const buttons = c.glfwGetJoystickButtons(@intFromEnum(self.jid), &count);
if (buttons == null) return null;
return buttons[0..@as(u32, @intCast(count))];
}
/// Returns the state of all hats of the specified joystick.
///
/// This function returns the state of all hats of the specified joystick. Each element in the array
/// is one of the following values:
///
/// | Name | Value |
/// |---------------------------|---------------------------------------------|
/// | `glfw.RawHats.centered` | 0 |
/// | `glfw.RawHats.up` | 1 |
/// | `glfw.RawHats.right` | 2 |
/// | `glfw.RawHats.down` | 4 |
/// | `glfw.RawHats.left` | 8 |
/// | `glfw.RawHats.right_up` | `glfw.RawHats.right` \| `glfw.RawHats.up` |
/// | `glfw.RawHats.right_down` | `glfw.RawHats.right` \| `glfw.RawHats.down` |
/// | `glfw.RawHats.left_up` | `glfw.RawHats.left` \| `glfw.RawHats.up` |
/// | `glfw.RawHats.left_down` | `glfw.RawHats.left` \| `glfw.RawHats.down` |
///
/// The diagonal directions are bitwise combinations of the primary (up, right, down and left)
/// directions, since the Zig GLFW wrapper returns a packed struct it is trivial to test for these:
///
/// ```
/// if (hats.up and hats.right) {
/// // up-right!
/// }
/// ```
///
/// If the specified joystick is not present this function will return null but will not generate an
/// error. This can be used instead of first calling glfw.Joystick.present.
///
/// @return An array of hat states, or null if the joystick is not present.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned array is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected, this function is called
/// again for that joystick or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_hat
pub inline fn getHats(self: Joystick) ?[]const Hat {
internal_debug.assertInitialized();
var count: c_int = undefined;
const hats = c.glfwGetJoystickHats(@intFromEnum(self.jid), &count);
if (hats == null) return null;
const slice = hats[0..@as(u32, @intCast(count))];
return @as(*const []const Hat, @ptrCast(&slice)).*;
}
/// Returns the name of the specified joystick.
///
/// This function returns the name, encoded as UTF-8, of the specified joystick. The returned string
/// is allocated and freed by GLFW. You should not free it yourself.
///
/// If the specified joystick is not present this function will return null but will not generate an
/// error. This can be used instead of first calling glfw.Joystick.present.
///
/// @return The UTF-8 encoded name of the joystick, or null if the joystick is not present or an
/// error occurred.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_name
pub inline fn getName(self: Joystick) ?[:0]const u8 {
internal_debug.assertInitialized();
const name_opt = c.glfwGetJoystickName(@intFromEnum(self.jid));
return if (name_opt) |name|
std.mem.span(@as([*:0]const u8, @ptrCast(name)))
else
null;
}
/// Returns the SDL compatible GUID of the specified joystick.
///
/// This function returns the SDL compatible GUID, as a UTF-8 encoded hexadecimal string, of the
/// specified joystick. The returned string is allocated and freed by GLFW. You should not free it
/// yourself.
///
/// The GUID is what connects a joystick to a gamepad mapping. A connected joystick will always have
/// a GUID even if there is no gamepad mapping assigned to it.
///
/// If the specified joystick is not present this function will return null but will not generate an
/// error. This can be used instead of first calling glfw.Joystick.present.
///
/// The GUID uses the format introduced in SDL 2.0.5. This GUID tries to uniquely identify the make
/// and model of a joystick but does not identify a specific unit, e.g. all wired Xbox 360
/// controllers will have the same GUID on that platform. The GUID for a unit may vary between
/// platforms depending on what hardware information the platform specific APIs provide.
///
/// @return The UTF-8 encoded GUID of the joystick, or null if the joystick is not present.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// null is additionally returned in the event of an error.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad
pub inline fn getGUID(self: Joystick) ?[:0]const u8 {
internal_debug.assertInitialized();
const guid_opt = c.glfwGetJoystickGUID(@intFromEnum(self.jid));
return if (guid_opt) |guid|
std.mem.span(@as([*:0]const u8, @ptrCast(guid)))
else
null;
}
/// Sets the user pointer of the specified joystick.
///
/// This function sets the user-defined pointer of the specified joystick. The current value is
/// retained until the joystick is disconnected. The initial value is null.
///
/// This function may be called from the joystick callback, even for a joystick that is being disconnected.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: joystick_userptr, glfw.Joystick.getUserPointer
pub inline fn setUserPointer(self: Joystick, comptime T: type, pointer: *T) void {
internal_debug.assertInitialized();
c.glfwSetJoystickUserPointer(@intFromEnum(self.jid), @as(*anyopaque, @ptrCast(pointer)));
}
/// Returns the user pointer of the specified joystick.
///
/// This function returns the current value of the user-defined pointer of the specified joystick.
/// The initial value is null.
///
/// This function may be called from the joystick callback, even for a joystick that is being
/// disconnected.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: joystick_userptr, glfw.Joystick.setUserPointer
pub inline fn getUserPointer(self: Joystick, comptime PointerType: type) ?PointerType {
internal_debug.assertInitialized();
const ptr = c.glfwGetJoystickUserPointer(@intFromEnum(self.jid));
if (ptr) |p| return @as(PointerType, @ptrCast(@alignCast(p)));
return null;
}
/// Describes an event relating to a joystick.
pub const Event = enum(c_int) {
/// The device was connected.
connected = c.GLFW_CONNECTED,
/// The device was disconnected.
disconnected = c.GLFW_DISCONNECTED,
};
/// Sets the joystick configuration callback.
///
/// This function sets the joystick configuration callback, or removes the currently set callback.
/// This is called when a joystick is connected to or disconnected from the system.
///
/// For joystick connection and disconnection events to be delivered on all platforms, you need to
/// call one of the event processing (see events) functions. Joystick disconnection may also be
/// detected and the callback called by joystick functions. The function will then return whatever
/// it returns if the joystick is not present.
///
/// @param[in] callback The new callback, or null to remove the currently set callback.
///
/// @callback_param `jid` The joystick that was connected or disconnected.
/// @callback_param `event` One of `.connected` or `.disconnected`. Future releases may add
/// more events.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: joystick_event
pub inline fn setCallback(comptime callback: ?fn (joystick: Joystick, event: Event) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn joystickCallbackWrapper(jid: c_int, event: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
Joystick{ .jid = @as(Joystick.Id, @enumFromInt(jid)) },
@as(Event, @enumFromInt(event)),
});
}
};
if (c.glfwSetJoystickCallback(CWrapper.joystickCallbackWrapper) != null) return;
} else {
if (c.glfwSetJoystickCallback(null) != null) return;
}
}
/// Adds the specified SDL_GameControllerDB gamepad mappings.
///
/// This function parses the specified ASCII encoded string and updates the internal list with any
/// gamepad mappings it finds. This string may contain either a single gamepad mapping or many
/// mappings separated by newlines. The parser supports the full format of the `gamecontrollerdb.txt`
/// source file including empty lines and comments.
///
/// See gamepad_mapping for a description of the format.
///
/// If there is already a gamepad mapping for a given GUID in the internal list, it will be
/// replaced by the one passed to this function. If the library is terminated and re-initialized
/// the internal list will revert to the built-in default.
///
/// @param[in] string The string containing the gamepad mappings.
///
/// Possible errors include glfw.ErrorCode.InvalidValue.
/// Returns a boolean indicating success.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad, glfw.Joystick.isGamepad, glfwGetGamepadName
///
///
/// @ingroup input
pub inline fn updateGamepadMappings(gamepad_mappings: [*:0]const u8) bool {
internal_debug.assertInitialized();
return c.glfwUpdateGamepadMappings(gamepad_mappings) == c.GLFW_TRUE;
}
/// Returns whether the specified joystick has a gamepad mapping.
///
/// This function returns whether the specified joystick is both present and has a gamepad mapping.
///
/// If the specified joystick is present but does not have a gamepad mapping this function will
/// return `false` but will not generate an error. Call glfw.Joystick.present to check if a
/// joystick is present regardless of whether it has a mapping.
///
/// @return `true` if a joystick is both present and has a gamepad mapping, or `false` otherwise.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum.
/// Additionally returns false in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad, glfw.Joystick.getGamepadState
pub inline fn isGamepad(self: Joystick) bool {
internal_debug.assertInitialized();
const is_gamepad = c.glfwJoystickIsGamepad(@intFromEnum(self.jid));
return is_gamepad == c.GLFW_TRUE;
}
/// Returns the human-readable gamepad name for the specified joystick.
///
/// This function returns the human-readable name of the gamepad from the gamepad mapping assigned
/// to the specified joystick.
///
/// If the specified joystick is not present or does not have a gamepad mapping this function will
/// return null, not an error. Call glfw.Joystick.present to check whether it is
/// present regardless of whether it has a mapping.
///
/// @return The UTF-8 encoded name of the gamepad, or null if the joystick is not present or does
/// not have a mapping.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum.
/// Additionally returns null in the event of an error.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified joystick is disconnected, the gamepad mappings are
/// updated or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad, glfw.Joystick.isGamepad
pub inline fn getGamepadName(self: Joystick) ?[:0]const u8 {
internal_debug.assertInitialized();
const name_opt = c.glfwGetGamepadName(@intFromEnum(self.jid));
return if (name_opt) |name|
std.mem.span(@as([*:0]const u8, @ptrCast(name)))
else
null;
}
/// Retrieves the state of the joystick remapped as a gamepad.
///
/// This function retrieves the state of the joystick remapped to an Xbox-like gamepad.
///
/// If the specified joystick is not present or does not have a gamepad mapping this function will
/// return `false`. Call glfw.joystickPresent to check whether it is present regardless of whether
/// it has a mapping.
///
/// The Guide button may not be available for input as it is often hooked by the system or the
/// Steam client.
///
/// Not all devices have all the buttons or axes provided by GamepadState. Unavailable buttons
/// and axes will always report `glfw.Action.release` and 0.0 respectively.
///
/// @param[in] jid The joystick (see joysticks) to query.
/// @param[out] state The gamepad input state of the joystick.
/// @return the gamepad input state if successful, or null if no joystick is connected or it has no
/// gamepad mapping.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum.
/// Returns null in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: gamepad, glfw.UpdateGamepadMappings, glfw.Joystick.isGamepad
pub inline fn getGamepadState(self: Joystick) ?GamepadState {
internal_debug.assertInitialized();
var state: GamepadState = undefined;
const success = c.glfwGetGamepadState(@intFromEnum(self.jid), @as(*c.GLFWgamepadstate, @ptrCast(&state)));
return if (success == c.GLFW_TRUE) state else null;
}
test "present" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.present();
}
test "getAxes" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getAxes();
}
test "getButtons" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getButtons();
}
test "getHats" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
if (joystick.getHats()) |hats| {
for (hats) |hat| {
if (hat.down and hat.up) {
// down-up!
}
}
}
}
test "getName" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getName();
}
test "getGUID" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getGUID();
}
test "setUserPointer_syntax" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
// Must be called from joystick callback, we cannot test it.
_ = joystick;
_ = setUserPointer;
}
test "getUserPointer_syntax" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
// Must be called from joystick callback, we cannot test it.
_ = joystick;
_ = getUserPointer;
}
test "setCallback" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
glfw.Joystick.setCallback((struct {
pub fn callback(joystick: Joystick, event: Event) void {
_ = joystick;
_ = event;
}
}).callback);
}
test "updateGamepadMappings_syntax" {
// We don't have a gamepad mapping to test with, just confirm the syntax is good.
_ = updateGamepadMappings;
}
test "isGamepad" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.isGamepad();
}
test "getGamepadName" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getGamepadName();
}
test "getGamepadState" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const joystick = glfw.Joystick{ .jid = .one };
_ = joystick.getGamepadState();
_ = (std.mem.zeroes(GamepadState)).getAxis(.left_x);
_ = (std.mem.zeroes(GamepadState)).getButton(.dpad_up);
}

26
pkg/glfw/LICENSE Normal file
View File

@ -0,0 +1,26 @@
Copyright (c) 2021 Hexops Contributors (given via the Git commit history).
Copyright (c) 2025 Mitchell Hashimoto
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

599
pkg/glfw/Monitor.zig Normal file
View File

@ -0,0 +1,599 @@
//! Monitor type and related functions
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const c = @import("c.zig").c;
const GammaRamp = @import("GammaRamp.zig");
const VideoMode = @import("VideoMode.zig");
const internal_debug = @import("internal_debug.zig");
const Monitor = @This();
handle: *c.GLFWmonitor,
/// A monitor position, in screen coordinates, of the upper left corner of the monitor on the
/// virtual screen.
const Pos = struct {
/// The x coordinate.
x: u32,
/// The y coordinate.
y: u32,
};
/// Returns the position of the monitor's viewport on the virtual screen.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getPos(self: Monitor) Pos {
internal_debug.assertInitialized();
var xpos: c_int = 0;
var ypos: c_int = 0;
c.glfwGetMonitorPos(self.handle, &xpos, &ypos);
return Pos{ .x = @as(u32, @intCast(xpos)), .y = @as(u32, @intCast(ypos)) };
}
/// The monitor workarea, in screen coordinates.
///
/// This is the position of the upper-left corner of the work area of the monitor, along with the
/// work area size. The work area is defined as the area of the monitor not occluded by the
/// window system task bar where present. If no task bar exists then the work area is the
/// monitor resolution in screen coordinates.
const Workarea = struct {
x: u32,
y: u32,
width: u32,
height: u32,
};
/// Retrieves the work area of the monitor.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// A zero value is returned in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_workarea
pub inline fn getWorkarea(self: Monitor) Workarea {
internal_debug.assertInitialized();
var xpos: c_int = 0;
var ypos: c_int = 0;
var width: c_int = 0;
var height: c_int = 0;
c.glfwGetMonitorWorkarea(self.handle, &xpos, &ypos, &width, &height);
return Workarea{ .x = @as(u32, @intCast(xpos)), .y = @as(u32, @intCast(ypos)), .width = @as(u32, @intCast(width)), .height = @as(u32, @intCast(height)) };
}
/// The physical size, in millimetres, of the display area of a monitor.
const PhysicalSize = struct {
width_mm: u32,
height_mm: u32,
};
/// Returns the physical size of the monitor.
///
/// Some platforms do not provide accurate monitor size information, either because the monitor
/// [EDID](https://en.wikipedia.org/wiki/Extended_display_identification_data)
/// data is incorrect or because the driver does not report it accurately.
///
/// win32: On Windows 8 and earlier the physical size is calculated from
/// the current resolution and system DPI instead of querying the monitor EDID data
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getPhysicalSize(self: Monitor) PhysicalSize {
internal_debug.assertInitialized();
var width_mm: c_int = 0;
var height_mm: c_int = 0;
c.glfwGetMonitorPhysicalSize(self.handle, &width_mm, &height_mm);
return PhysicalSize{ .width_mm = @as(u32, @intCast(width_mm)), .height_mm = @as(u32, @intCast(height_mm)) };
}
/// The content scale for a monitor.
///
/// This is the ratio between the current DPI and the platform's default DPI. This is especially
/// important for text and any UI elements. If the pixel dimensions of your UI scaled by this look
/// appropriate on your machine then it should appear at a reasonable size on other machines
/// regardless of their DPI and scaling settings. This relies on the system DPI and scaling
/// settings being somewhat correct.
///
/// The content scale may depend on both the monitor resolution and pixel density and on users
/// settings. It may be very different from the raw DPI calculated from the physical size and
/// current resolution.
const ContentScale = struct {
x_scale: f32,
y_scale: f32,
};
/// Returns the content scale for the monitor.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// A zero value is returned in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_scale, glfw.Window.getContentScale
pub inline fn getContentScale(self: Monitor) ContentScale {
internal_debug.assertInitialized();
var x_scale: f32 = 0;
var y_scale: f32 = 0;
c.glfwGetMonitorContentScale(self.handle, &x_scale, &y_scale);
return ContentScale{ .x_scale = @as(f32, @floatCast(x_scale)), .y_scale = @as(f32, @floatCast(y_scale)) };
}
/// Returns the name of the specified monitor.
///
/// This function returns a human-readable name, encoded as UTF-8, of the specified monitor. The
/// name typically reflects the make and model of the monitor and is not guaranteed to be unique
/// among the connected monitors.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the specified monitor is disconnected or the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_properties
pub inline fn getName(self: Monitor) [*:0]const u8 {
internal_debug.assertInitialized();
if (c.glfwGetMonitorName(self.handle)) |name| return @as([*:0]const u8, @ptrCast(name));
// `glfwGetMonitorName` returns `null` only for errors, but the only error is unreachable
// (NotInitialized)
unreachable;
}
/// Sets the user pointer of the specified monitor.
///
/// This function sets the user-defined pointer of the specified monitor. The current value is
/// retained until the monitor is disconnected.
///
/// This function may be called from the monitor callback, even for a monitor that is being
/// disconnected.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: monitor_userptr, glfw.Monitor.getUserPointer
pub inline fn setUserPointer(self: Monitor, comptime T: type, ptr: *T) void {
internal_debug.assertInitialized();
c.glfwSetMonitorUserPointer(self.handle, ptr);
}
/// Returns the user pointer of the specified monitor.
///
/// This function returns the current value of the user-defined pointer of the specified monitor.
///
/// This function may be called from the monitor callback, even for a monitor that is being
/// disconnected.
///
/// @thread_safety This function may be called from any thread. Access is not synchronized.
///
/// see also: monitor_userptr, glfw.Monitor.setUserPointer
pub inline fn getUserPointer(self: Monitor, comptime T: type) ?*T {
internal_debug.assertInitialized();
const ptr = c.glfwGetMonitorUserPointer(self.handle);
if (ptr == null) return null;
return @as(*T, @ptrCast(@alignCast(ptr.?)));
}
/// Returns the available video modes for the specified monitor.
///
/// This function returns an array of all video modes supported by the monitor. The returned slice
/// is sorted in ascending order, first by color bit depth (the sum of all channel depths) and
/// then by resolution area (the product of width and height), then resolution width and finally
/// by refresh rate.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
/// Returns null in the event of an error.
///
/// The returned slice memory is owned by the caller.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_modes, glfw.Monitor.getVideoMode
///
/// wayland: Gamma handling is privileged protocol, this function will thus never be implemented and
/// emits glfw.ErrorCode.FeatureUnavailable
///
/// TODO(glfw): rewrite this to not require any allocation.
pub inline fn getVideoModes(self: Monitor, allocator: mem.Allocator) mem.Allocator.Error!?[]VideoMode {
internal_debug.assertInitialized();
var count: c_int = 0;
if (c.glfwGetVideoModes(self.handle, &count)) |modes| {
const slice = try allocator.alloc(VideoMode, @as(u32, @intCast(count)));
var i: u32 = 0;
while (i < count) : (i += 1) {
slice[i] = VideoMode{ .handle = @as([*c]const c.GLFWvidmode, @ptrCast(modes))[i] };
}
return slice;
}
return null;
}
/// Returns the current mode of the specified monitor.
///
/// This function returns the current video mode of the specified monitor. If you have created a
/// full screen window for that monitor, the return value will depend on whether that window is
/// iconified.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
/// Additionally returns null in the event of an error.
///
/// @thread_safety This function must only be called from the main thread.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and will thus never be implemented and emits glfw.ErrorCode.FeatureUnavailable
///
/// see also: monitor_modes, glfw.Monitor.getVideoModes
pub inline fn getVideoMode(self: Monitor) ?VideoMode {
internal_debug.assertInitialized();
if (c.glfwGetVideoMode(self.handle)) |mode| return VideoMode{ .handle = mode.* };
return null;
}
/// Generates a gamma ramp and sets it for the specified monitor.
///
/// This function generates an appropriately sized gamma ramp from the specified exponent and then
/// calls glfw.Monitor.setGammaRamp with it. The value must be a finite number greater than zero.
///
/// The software controlled gamma ramp is applied _in addition_ to the hardware gamma correction,
/// which today is usually an approximation of sRGB gamma. This means that setting a perfectly
/// linear ramp, or gamma 1.0, will produce the default (usually sRGB-like) behavior.
///
/// For gamma correct rendering with OpenGL or OpenGL ES, see the glfw.srgb_capable hint.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
///
/// wayland: Gamma handling is privileged protocol, this function will thus never be implemented and
/// emits glfw.ErrorCode.FeatureUnavailable
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn setGamma(self: Monitor, gamma: f32) void {
internal_debug.assertInitialized();
std.debug.assert(!std.math.isNan(gamma));
std.debug.assert(gamma >= 0);
std.debug.assert(gamma <= std.math.f32_max);
c.glfwSetGamma(self.handle, gamma);
}
/// Returns the current gamma ramp for the specified monitor.
///
/// This function returns the current gamma ramp of the specified monitor.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Additionally returns null in the event of an error.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and returns glfw.ErrorCode.FeatureUnavailable.
///
/// The returned gamma ramp is `.owned = true` by GLFW, and is valid until the monitor is
/// disconnected, this function is called again, or `glfw.terminate()` is called.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn getGammaRamp(self: Monitor) ?GammaRamp {
internal_debug.assertInitialized();
if (c.glfwGetGammaRamp(self.handle)) |ramp| return GammaRamp.fromC(ramp.*);
return null;
}
/// Sets the current gamma ramp for the specified monitor.
///
/// This function sets the current gamma ramp for the specified monitor. The original gamma ramp
/// for that monitor is saved by GLFW the first time this function is called and is restored by
/// `glfw.terminate()`.
///
/// The software controlled gamma ramp is applied _in addition_ to the hardware gamma correction,
/// which today is usually an approximation of sRGB gamma. This means that setting a perfectly
/// linear ramp, or gamma 1.0, will produce the default (usually sRGB-like) behavior.
///
/// For gamma correct rendering with OpenGL or OpenGL ES, see the glfw.srgb_capable hint.
///
/// Possible errors include glfw.ErrorCode.PlatformError, glfw.ErrorCode.FeatureUnavailable.
///
/// The size of the specified gamma ramp should match the size of the current ramp for that
/// monitor. On win32, the gamma ramp size must be 256.
///
/// wayland: Gamma handling is a privileged protocol, this function will thus never be implemented
/// and returns glfw.ErrorCode.FeatureUnavailable.
///
/// @pointer_lifetime The specified gamma ramp is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_gamma
pub inline fn setGammaRamp(self: Monitor, ramp: GammaRamp) void {
internal_debug.assertInitialized();
c.glfwSetGammaRamp(self.handle, &ramp.toC());
}
/// Returns the currently connected monitors.
///
/// This function returns a slice of all currently connected monitors. The primary monitor is
/// always first. If no monitors were found, this function returns an empty slice.
///
/// The returned slice memory is owned by the caller. The underlying handles are owned by GLFW, and
/// are valid until the monitor configuration changes or `glfw.terminate` is called.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_monitors, monitor_event, glfw.monitor.getPrimary
pub inline fn getAll(allocator: mem.Allocator) mem.Allocator.Error![]Monitor {
internal_debug.assertInitialized();
var count: c_int = 0;
if (c.glfwGetMonitors(&count)) |monitors| {
const slice = try allocator.alloc(Monitor, @as(u32, @intCast(count)));
var i: u32 = 0;
while (i < count) : (i += 1) {
slice[i] = Monitor{ .handle = @as([*c]const ?*c.GLFWmonitor, @ptrCast(monitors))[i].? };
}
return slice;
}
// `glfwGetMonitors` returning null can be either an error or no monitors, but the only error is
// unreachable (NotInitialized)
return &[_]Monitor{};
}
/// Returns the primary monitor.
///
/// This function returns the primary monitor. This is usually the monitor where elements like
/// the task bar or global menu bar are located.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_monitors, glfw.monitors.getAll
pub inline fn getPrimary() ?Monitor {
internal_debug.assertInitialized();
if (c.glfwGetPrimaryMonitor()) |handle| return Monitor{ .handle = handle };
return null;
}
/// Describes an event relating to a monitor.
pub const Event = enum(c_int) {
/// The device was connected.
connected = c.GLFW_CONNECTED,
/// The device was disconnected.
disconnected = c.GLFW_DISCONNECTED,
};
/// Sets the monitor configuration callback.
///
/// This function sets the monitor configuration callback, or removes the currently set callback.
/// This is called when a monitor is connected to or disconnected from the system. Example:
///
/// ```
/// fn monitorCallback(monitor: glfw.Monitor, event: glfw.Monitor.Event, data: *MyData) void {
/// // data is the pointer you passed into setCallback.
/// // event is one of .connected or .disconnected
/// }
/// ...
/// glfw.Monitor.setCallback(MyData, &myData, monitorCallback)
/// ```
///
/// `event` may be one of .connected or .disconnected. More events may be added in the future.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: monitor_event
pub inline fn setCallback(comptime callback: ?fn (monitor: Monitor, event: Event) void) void {
internal_debug.assertInitialized();
if (callback) |user_callback| {
const CWrapper = struct {
pub fn monitorCallbackWrapper(monitor: ?*c.GLFWmonitor, event: c_int) callconv(.C) void {
@call(.always_inline, user_callback, .{
Monitor{ .handle = monitor.? },
@as(Event, @enumFromInt(event)),
});
}
};
if (c.glfwSetMonitorCallback(CWrapper.monitorCallbackWrapper) != null) return;
} else {
if (c.glfwSetMonitorCallback(null) != null) return;
}
}
test "getAll" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const allocator = testing.allocator;
const monitors = try getAll(allocator);
defer allocator.free(monitors);
}
test "getPrimary" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = getPrimary();
}
test "getPos" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getPos();
}
}
test "getWorkarea" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getWorkarea();
}
}
test "getPhysicalSize" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getPhysicalSize();
}
}
test "getContentScale" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getContentScale();
}
}
test "getName" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getName();
}
}
test "userPointer" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
var p = m.getUserPointer(u32);
try testing.expect(p == null);
var x: u32 = 5;
m.setUserPointer(u32, &x);
p = m.getUserPointer(u32);
try testing.expectEqual(p.?.*, 5);
}
}
test "setCallback" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
setCallback(struct {
fn callback(monitor: Monitor, event: Event) void {
_ = monitor;
_ = event;
}
}.callback);
}
test "getVideoModes" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
const allocator = testing.allocator;
const modes_maybe = try m.getVideoModes(allocator);
if (modes_maybe) |modes| {
defer allocator.free(modes);
}
}
}
test "getVideoMode" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
_ = m.getVideoMode();
}
}
test "set_getGammaRamp" {
const allocator = testing.allocator;
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const monitor = getPrimary();
if (monitor) |m| {
if (m.getGammaRamp()) |ramp| {
// Set it to the exact same value; if we do otherwise an our tests fail it wouldn't call
// terminate and our made-up gamma ramp would get stuck.
m.setGammaRamp(ramp);
// technically not needed here / noop because GLFW owns this gamma ramp.
defer ramp.deinit(allocator);
}
}
}

50
pkg/glfw/VideoMode.zig Normal file
View File

@ -0,0 +1,50 @@
//! Monitor video modes and related functions
//!
//! see also: glfw.Monitor.getVideoMode
const std = @import("std");
const c = @import("c.zig").c;
const VideoMode = @This();
handle: c.GLFWvidmode,
/// Returns the width of the video mode, in screen coordinates.
pub inline fn getWidth(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.width));
}
/// Returns the height of the video mode, in screen coordinates.
pub inline fn getHeight(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.height));
}
/// Returns the bit depth of the red channel of the video mode.
pub inline fn getRedBits(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.redBits));
}
/// Returns the bit depth of the green channel of the video mode.
pub inline fn getGreenBits(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.greenBits));
}
/// Returns the bit depth of the blue channel of the video mode.
pub inline fn getBlueBits(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.blueBits));
}
/// Returns the refresh rate of the video mode, in Hz.
pub inline fn getRefreshRate(self: VideoMode) u32 {
return @as(u32, @intCast(self.handle.refreshRate));
}
test "getters" {
const x = std.mem.zeroes(VideoMode);
_ = x.getWidth();
_ = x.getHeight();
_ = x.getRedBits();
_ = x.getGreenBits();
_ = x.getBlueBits();
_ = x.getRefreshRate();
}

3551
pkg/glfw/Window.zig Normal file

File diff suppressed because it is too large Load Diff

13
pkg/glfw/action.zig Normal file
View File

@ -0,0 +1,13 @@
const c = @import("c.zig").c;
/// Key and button actions
pub const Action = enum(c_int) {
/// The key or mouse button was released.
release = c.GLFW_RELEASE,
/// The key or mouse button was pressed.
press = c.GLFW_PRESS,
/// The key was held down until it repeated.
repeat = c.GLFW_REPEAT,
};

143
pkg/glfw/allocator.zig Normal file
View File

@ -0,0 +1,143 @@
// TODO: implement custom allocator support
// /*! @brief
// *
// * @sa @ref init_allocator
// * @sa @ref glfwInitAllocator
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// typedef struct GLFWallocator
// {
// GLFWallocatefun allocate;
// GLFWreallocatefun reallocate;
// GLFWdeallocatefun deallocate;
// void* user;
// } GLFWallocator;
// /*! @brief The function pointer type for memory allocation callbacks.
// *
// * This is the function pointer type for memory allocation callbacks. A memory
// * allocation callback function has the following signature:
// * @code
// * void* function_name(size_t size, void* user)
// * @endcode
// *
// * This function must return either a memory block at least `size` bytes long,
// * or `NULL` if allocation failed. Note that not all parts of GLFW handle allocation
// * failures gracefully yet.
// *
// * This function may be called during @ref glfwInit but before the library is
// * flagged as initialized, as well as during @ref glfwTerminate after the
// * library is no longer flagged as initialized.
// *
// * Any memory allocated by this function will be deallocated during library
// * termination or earlier.
// *
// * The size will always be greater than zero. Allocations of size zero are filtered out
// * before reaching the custom allocator.
// *
// * @param[in] size The minimum size, in bytes, of the memory block.
// * @param[in] user The user-defined pointer from the allocator.
// * @return The address of the newly allocated memory block, or `NULL` if an
// * error occurred.
// *
// * @pointer_lifetime The returned memory block must be valid at least until it
// * is deallocated.
// *
// * @reentrancy This function should not call any GLFW function.
// *
// * @thread_safety This function may be called from any thread that calls GLFW functions.
// *
// * @sa @ref init_allocator
// * @sa @ref GLFWallocator
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// typedef void* (* GLFWallocatefun)(size_t size, void* user);
// /*! @brief The function pointer type for memory reallocation callbacks.
// *
// * This is the function pointer type for memory reallocation callbacks.
// * A memory reallocation callback function has the following signature:
// * @code
// * void* function_name(void* block, size_t size, void* user)
// * @endcode
// *
// * This function must return a memory block at least `size` bytes long, or
// * `NULL` if allocation failed. Note that not all parts of GLFW handle allocation
// * failures gracefully yet.
// *
// * This function may be called during @ref glfwInit but before the library is
// * flagged as initialized, as well as during @ref glfwTerminate after the
// * library is no longer flagged as initialized.
// *
// * Any memory allocated by this function will be deallocated during library
// * termination or earlier.
// *
// * The block address will never be `NULL` and the size will always be greater than zero.
// * Reallocations of a block to size zero are converted into deallocations. Reallocations
// * of `NULL` to a non-zero size are converted into regular allocations.
// *
// * @param[in] block The address of the memory block to reallocate.
// * @param[in] size The new minimum size, in bytes, of the memory block.
// * @param[in] user The user-defined pointer from the allocator.
// * @return The address of the newly allocated or resized memory block, or
// * `NULL` if an error occurred.
// *
// * @pointer_lifetime The returned memory block must be valid at least until it
// * is deallocated.
// *
// * @reentrancy This function should not call any GLFW function.
// *
// * @thread_safety This function may be called from any thread that calls GLFW functions.
// *
// * @sa @ref init_allocator
// * @sa @ref GLFWallocator
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// typedef void* (* GLFWreallocatefun)(void* block, size_t size, void* user);
// /*! @brief The function pointer type for memory deallocation callbacks.
// *
// * This is the function pointer type for memory deallocation callbacks.
// * A memory deallocation callback function has the following signature:
// * @code
// * void function_name(void* block, void* user)
// * @endcode
// *
// * This function may deallocate the specified memory block. This memory block
// * will have been allocated with the same allocator.
// *
// * This function may be called during @ref glfwInit but before the library is
// * flagged as initialized, as well as during @ref glfwTerminate after the
// * library is no longer flagged as initialized.
// *
// * The block address will never be `NULL`. Deallocations of `NULL` are filtered out
// * before reaching the custom allocator.
// *
// * @param[in] block The address of the memory block to deallocate.
// * @param[in] user The user-defined pointer from the allocator.
// *
// * @pointer_lifetime The specified memory block will not be accessed by GLFW
// * after this function is called.
// *
// * @reentrancy This function should not call any GLFW function.
// *
// * @thread_safety This function may be called from any thread that calls GLFW functions.
// *
// * @sa @ref init_allocator
// * @sa @ref GLFWallocator
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// typedef void (* GLFWdeallocatefun)(void* block, void* user);

272
pkg/glfw/build.zig Normal file
View File

@ -0,0 +1,272 @@
const std = @import("std");
const apple_sdk = @import("apple_sdk");
pub fn build(b: *std.Build) !void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const module = b.addModule("glfw", .{
.root_source_file = b.path("main.zig"),
.target = target,
.optimize = optimize,
});
const lib = try buildLib(b, module, .{
.target = target,
.optimize = optimize,
});
const test_exe: ?*std.Build.Step.Compile = if (target.query.isNative()) exe: {
const exe = b.addTest(.{
.name = "test",
.root_source_file = b.path("main.zig"),
.target = target,
.optimize = optimize,
});
if (target.result.os.tag.isDarwin()) {
try apple_sdk.addPaths(b, exe.root_module);
}
const tests_run = b.addRunArtifact(exe);
const test_step = b.step("test", "Run tests");
test_step.dependOn(&tests_run.step);
// Uncomment this if we're debugging tests
b.installArtifact(exe);
break :exe exe;
} else null;
if (b.systemIntegrationOption("glfw3", .{})) {
module.linkSystemLibrary("glfw3", dynamic_link_opts);
if (test_exe) |exe| exe.linkSystemLibrary2("glfw3", dynamic_link_opts);
} else {
module.linkLibrary(lib);
b.installArtifact(lib);
if (test_exe) |exe| exe.linkLibrary(lib);
}
}
fn buildLib(
b: *std.Build,
module: *std.Build.Module,
options: anytype,
) !*std.Build.Step.Compile {
const target = options.target;
const optimize = options.optimize;
const use_x11 = b.option(
bool,
"x11",
"Build with X11. Only useful on Linux",
) orelse true;
const use_wl = b.option(
bool,
"wayland",
"Build with Wayland. Only useful on Linux",
) orelse true;
const use_opengl = b.option(
bool,
"opengl",
"Build with OpenGL; deprecated on MacOS",
) orelse false;
const use_gles = b.option(
bool,
"gles",
"Build with GLES; not supported on MacOS",
) orelse false;
const use_metal = b.option(
bool,
"metal",
"Build with Metal; only supported on MacOS",
) orelse true;
const lib = b.addStaticLibrary(.{
.name = "glfw",
.target = target,
.optimize = optimize,
});
lib.linkLibC();
const upstream = b.lazyDependency("glfw", .{}) orelse return lib;
lib.addIncludePath(upstream.path("include"));
module.addIncludePath(upstream.path("include"));
lib.installHeadersDirectory(upstream.path("include/GLFW"), "GLFW", .{});
switch (target.result.os.tag) {
.windows => {
lib.linkSystemLibrary("gdi32");
lib.linkSystemLibrary("user32");
lib.linkSystemLibrary("shell32");
if (use_opengl) {
lib.linkSystemLibrary("opengl32");
}
if (use_gles) {
lib.linkSystemLibrary("GLESv3");
}
const flags = [_][]const u8{"-D_GLFW_WIN32"};
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = &base_sources,
.flags = &flags,
});
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = &windows_sources,
.flags = &flags,
});
},
.macos => {
try apple_sdk.addPaths(b, lib.root_module);
try apple_sdk.addPaths(b, module);
// Transitive dependencies, explicit linkage of these works around
// ziglang/zig#17130
lib.linkFramework("CFNetwork");
lib.linkFramework("ApplicationServices");
lib.linkFramework("ColorSync");
lib.linkFramework("CoreText");
lib.linkFramework("ImageIO");
// Direct dependencies
lib.linkSystemLibrary("objc");
lib.linkFramework("IOKit");
lib.linkFramework("CoreFoundation");
lib.linkFramework("AppKit");
lib.linkFramework("CoreServices");
lib.linkFramework("CoreGraphics");
lib.linkFramework("Foundation");
if (use_metal) {
lib.linkFramework("Metal");
}
if (use_opengl) {
lib.linkFramework("OpenGL");
}
const flags = [_][]const u8{"-D_GLFW_COCOA"};
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = &base_sources,
.flags = &flags,
});
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = &macos_sources,
.flags = &flags,
});
},
// everything that isn't windows or mac is linux :P
else => {
var sources = std.BoundedArray([]const u8, 64).init(0) catch unreachable;
var flags = std.BoundedArray([]const u8, 16).init(0) catch unreachable;
sources.appendSlice(&base_sources) catch unreachable;
sources.appendSlice(&linux_sources) catch unreachable;
if (use_x11) {
lib.linkSystemLibrary2("X11", dynamic_link_opts);
lib.linkSystemLibrary2("xkbcommon", dynamic_link_opts);
sources.appendSlice(&linux_x11_sources) catch unreachable;
flags.append("-D_GLFW_X11") catch unreachable;
}
if (use_wl) {
lib.linkSystemLibrary2("wayland-client", dynamic_link_opts);
lib.root_module.addCMacro("WL_MARSHAL_FLAG_DESTROY", "1");
lib.addIncludePath(b.path("wayland-headers"));
sources.appendSlice(&linux_wl_sources) catch unreachable;
flags.append("-D_GLFW_WAYLAND") catch unreachable;
flags.append("-Wno-implicit-function-declaration") catch unreachable;
}
lib.addCSourceFiles(.{
.root = upstream.path(""),
.files = sources.slice(),
.flags = flags.slice(),
});
},
}
return lib;
}
// For dynamic linking, we prefer dynamic linking and to search by
// mode first. Mode first will search all paths for a dynamic library
// before falling back to static.
const dynamic_link_opts: std.Build.Module.LinkSystemLibraryOptions = .{
.preferred_link_mode = .dynamic,
.search_strategy = .mode_first,
};
const base_sources = [_][]const u8{
"src/context.c",
"src/egl_context.c",
"src/init.c",
"src/input.c",
"src/monitor.c",
"src/null_init.c",
"src/null_joystick.c",
"src/null_monitor.c",
"src/null_window.c",
"src/osmesa_context.c",
"src/platform.c",
"src/vulkan.c",
"src/window.c",
};
const linux_sources = [_][]const u8{
"src/linux_joystick.c",
"src/posix_module.c",
"src/posix_poll.c",
"src/posix_thread.c",
"src/posix_time.c",
"src/xkb_unicode.c",
};
const linux_wl_sources = [_][]const u8{
"src/wl_init.c",
"src/wl_monitor.c",
"src/wl_window.c",
};
const linux_x11_sources = [_][]const u8{
"src/glx_context.c",
"src/x11_init.c",
"src/x11_monitor.c",
"src/x11_window.c",
};
const windows_sources = [_][]const u8{
"src/wgl_context.c",
"src/win32_init.c",
"src/win32_joystick.c",
"src/win32_module.c",
"src/win32_monitor.c",
"src/win32_thread.c",
"src/win32_time.c",
"src/win32_window.c",
};
const macos_sources = [_][]const u8{
// C sources
"src/cocoa_time.c",
"src/posix_module.c",
"src/posix_thread.c",
// ObjC sources
"src/cocoa_init.m",
"src/cocoa_joystick.m",
"src/cocoa_monitor.m",
"src/cocoa_window.m",
"src/nsgl_context.m",
};

15
pkg/glfw/build.zig.zon Normal file
View File

@ -0,0 +1,15 @@
.{
.name = .glfw,
.version = "3.4.0",
.fingerprint = 0x3bbe0a5c667e2c62,
.paths = .{""},
.dependencies = .{
.glfw = .{
.url = "https://github.com/glfw/glfw/archive/e7ea71be039836da3a98cea55ae5569cb5eb885c.tar.gz",
.hash = "N-V-__8AAMrJSwAUGb9-vTzkNR-5LXS81MR__ZRVfF3tWgG6",
.lazy = true,
},
.apple_sdk = .{ .path = "../apple-sdk" },
},
}

6
pkg/glfw/c.zig Normal file
View File

@ -0,0 +1,6 @@
pub const c = @cImport({
// Must be uncommented for vulkan.zig to work
// @cDefine("GLFW_INCLUDE_VULKAN", "1");
@cDefine("GLFW_INCLUDE_NONE", "1");
@cInclude("GLFW/glfw3.h");
});

71
pkg/glfw/clipboard.zig Normal file
View File

@ -0,0 +1,71 @@
const std = @import("std");
const c = @import("c.zig").c;
const internal_debug = @import("internal_debug.zig");
/// Sets the clipboard to the specified string.
///
/// This function sets the system clipboard to the specified, UTF-8 encoded string.
///
/// @param[in] string A UTF-8 encoded string.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @pointer_lifetime The specified string is copied before this function returns.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: clipboard, glfwGetClipboardString
pub inline fn setClipboardString(value: [*:0]const u8) void {
internal_debug.assertInitialized();
c.glfwSetClipboardString(null, value);
}
/// Returns the contents of the clipboard as a string.
///
/// This function returns the contents of the system clipboard, if it contains or is convertible to
/// a UTF-8 encoded string. If the clipboard is empty or if its contents cannot be converted,
/// glfw.ErrorCode.FormatUnavailable is returned.
///
/// @return The contents of the clipboard as a UTF-8 encoded string.
///
/// Possible errors include glfw.ErrorCode.FormatUnavailable and glfw.ErrorCode.PlatformError.
/// null is returned in the event of an error.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the next call to glfw.getClipboardString or glfw.setClipboardString
/// or until the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: clipboard, glfwSetClipboardString
pub inline fn getClipboardString() ?[:0]const u8 {
internal_debug.assertInitialized();
if (c.glfwGetClipboardString(null)) |c_str| return std.mem.span(@as([*:0]const u8, @ptrCast(c_str)));
return null;
}
test "setClipboardString" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
glfw.setClipboardString("hello mach");
}
test "getClipboardString" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.getClipboardString();
}

338
pkg/glfw/errors.zig Normal file
View File

@ -0,0 +1,338 @@
//! Errors
const testing = @import("std").testing;
const mem = @import("std").mem;
const c = @import("c.zig").c;
/// Errors that GLFW can produce.
pub const ErrorCode = error{
/// GLFW has not been initialized.
///
/// This occurs if a GLFW function was called that must not be called unless the library is
/// initialized.
NotInitialized,
/// No context is current for this thread.
///
/// This occurs if a GLFW function was called that needs and operates on the current OpenGL or
/// OpenGL ES context but no context is current on the calling thread. One such function is
/// glfw.SwapInterval.
NoCurrentContext,
/// One of the arguments to the function was an invalid enum value.
///
/// One of the arguments to the function was an invalid enum value, for example requesting
/// glfw.red_bits with glfw.getWindowAttrib.
InvalidEnum,
/// One of the arguments to the function was an invalid value.
///
/// One of the arguments to the function was an invalid value, for example requesting a
/// non-existent OpenGL or OpenGL ES version like 2.7.
///
/// Requesting a valid but unavailable OpenGL or OpenGL ES version will instead result in a
/// glfw.ErrorCode.VersionUnavailable error.
InvalidValue,
/// A memory allocation failed.
OutOfMemory,
/// GLFW could not find support for the requested API on the system.
///
/// The installed graphics driver does not support the requested API, or does not support it
/// via the chosen context creation API. Below are a few examples.
///
/// Some pre-installed Windows graphics drivers do not support OpenGL. AMD only supports
/// OpenGL ES via EGL, while Nvidia and Intel only support it via a WGL or GLX extension. macOS
/// does not provide OpenGL ES at all. The Mesa EGL, OpenGL and OpenGL ES libraries do not
/// interface with the Nvidia binary driver. Older graphics drivers do not support Vulkan.
APIUnavailable,
/// The requested OpenGL or OpenGL ES version (including any requested context or framebuffer
/// hints) is not available on this machine.
///
/// The machine does not support your requirements. If your application is sufficiently
/// flexible, downgrade your requirements and try again. Otherwise, inform the user that their
/// machine does not match your requirements.
///
/// Future invalid OpenGL and OpenGL ES versions, for example OpenGL 4.8 if 5.0 comes out
/// before the 4.x series gets that far, also fail with this error and not glfw.ErrorCode.InvalidValue,
/// because GLFW cannot know what future versions will exist.
VersionUnavailable,
/// A platform-specific error occurred that does not match any of the more specific categories.
///
/// A bug or configuration error in GLFW, the underlying operating system or its drivers, or a
/// lack of required resources. Report the issue to our [issue tracker](https://github.com/glfw/glfw/issues).
PlatformError,
/// The requested format is not supported or available.
///
/// If emitted during window creation, the requested pixel format is not supported.
///
/// If emitted when querying the clipboard, the contents of the clipboard could not be
/// converted to the requested format.
///
/// If emitted during window creation, one or more hard constraints did not match any of the
/// available pixel formats. If your application is sufficiently flexible, downgrade your
/// requirements and try again. Otherwise, inform the user that their machine does not match
/// your requirements.
///
/// If emitted when querying the clipboard, ignore the error or report it to the user, as
/// appropriate.
FormatUnavailable,
/// The specified window does not have an OpenGL or OpenGL ES context.
///
/// A window that does not have an OpenGL or OpenGL ES context was passed to a function that
/// requires it to have one.
NoWindowContext,
/// The specified cursor shape is not available.
///
/// The specified standard cursor shape is not available, either because the
/// current platform cursor theme does not provide it or because it is not
/// available on the platform.
///
/// analysis: Platform or system settings limitation. Pick another standard cursor shape or
/// create a custom cursor.
CursorUnavailable,
/// The requested feature is not provided by the platform.
///
/// The requested feature is not provided by the platform, so GLFW is unable to
/// implement it. The documentation for each function notes if it could emit
/// this error.
///
/// analysis: Platform or platform version limitation. The error can be ignored
/// unless the feature is critical to the application.
///
/// A function call that emits this error has no effect other than the error and
/// updating any existing out parameters.
///
FeatureUnavailable,
/// The requested feature is not implemented for the platform.
///
/// The requested feature has not yet been implemented in GLFW for this platform.
///
/// analysis: An incomplete implementation of GLFW for this platform, hopefully
/// fixed in a future release. The error can be ignored unless the feature is
/// critical to the application.
///
/// A function call that emits this error has no effect other than the error and
/// updating any existing out parameters.
///
FeatureUnimplemented,
/// Platform unavailable or no matching platform was found.
///
/// If emitted during initialization, no matching platform was found. If glfw.InitHint.platform
/// is set to `.any_platform`, GLFW could not detect any of the platforms supported by this
/// library binary, except for the Null platform. If set to a specific platform, it is either
/// not supported by this library binary or GLFW was not able to detect it.
///
/// If emitted by a native access function, GLFW was initialized for a different platform
/// than the function is for.
///
/// analysis: Failure to detect any platform usually only happens on non-macOS Unix
/// systems, either when no window system is running or the program was run from
/// a terminal that does not have the necessary environment variables. Fall back to
/// a different platform if possible or notify the user that no usable platform was
/// detected.
///
/// Failure to detect a specific platform may have the same cause as above or be because
/// support for that platform was not compiled in. Call glfw.platformSupported to
/// check whether a specific platform is supported by a library binary.
///
PlatformUnavailable,
};
/// An error produced by GLFW and the description associated with it.
pub const Error = struct {
error_code: ErrorCode,
description: [:0]const u8,
};
fn convertError(e: c_int) ErrorCode!void {
return switch (e) {
c.GLFW_NO_ERROR => {},
c.GLFW_NOT_INITIALIZED => ErrorCode.NotInitialized,
c.GLFW_NO_CURRENT_CONTEXT => ErrorCode.NoCurrentContext,
c.GLFW_INVALID_ENUM => ErrorCode.InvalidEnum,
c.GLFW_INVALID_VALUE => ErrorCode.InvalidValue,
c.GLFW_OUT_OF_MEMORY => ErrorCode.OutOfMemory,
c.GLFW_API_UNAVAILABLE => ErrorCode.APIUnavailable,
c.GLFW_VERSION_UNAVAILABLE => ErrorCode.VersionUnavailable,
c.GLFW_PLATFORM_ERROR => ErrorCode.PlatformError,
c.GLFW_FORMAT_UNAVAILABLE => ErrorCode.FormatUnavailable,
c.GLFW_NO_WINDOW_CONTEXT => ErrorCode.NoWindowContext,
c.GLFW_CURSOR_UNAVAILABLE => ErrorCode.CursorUnavailable,
c.GLFW_FEATURE_UNAVAILABLE => ErrorCode.FeatureUnavailable,
c.GLFW_FEATURE_UNIMPLEMENTED => ErrorCode.FeatureUnimplemented,
c.GLFW_PLATFORM_UNAVAILABLE => ErrorCode.PlatformUnavailable,
else => unreachable,
};
}
/// Clears the last error and the error description pointer for the calling thread. Does nothing if
/// no error has occurred since the last call.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn clearError() void {
_ = c.glfwGetError(null);
}
/// Returns and clears the last error for the calling thread.
///
/// This function returns and clears the error code of the last error that occurred on the calling
/// thread, along with a UTF-8 encoded human-readable description of it. If no error has occurred
/// since the last call, it returns GLFW_NO_ERROR (zero) and the description pointer is set to
/// `NULL`.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is guaranteed to be valid only until the next error occurs or the library is
/// terminated.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getError() ?Error {
var desc: [*c]const u8 = null;
convertError(c.glfwGetError(&desc)) catch |error_code| {
return .{
.error_code = error_code,
.description = mem.sliceTo(desc, 0),
};
};
return null;
}
pub inline fn mustGetError() Error {
return getError() orelse {
@panic("glfw: mustGetError called but no error is present");
};
}
/// Returns and clears the last error for the calling thread.
///
/// This function returns and clears the error code of the last error that occurred on the calling
/// thread. If no error has occurred since the last call, it returns GLFW_NO_ERROR (zero).
///
/// @return The last error code for the calling thread, or @ref GLFW_NO_ERROR (zero).
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getErrorCode() ErrorCode!void {
return convertError(c.glfwGetError(null));
}
/// Returns and clears the last error code for the calling thread. If no error is present, this
/// function panics.
pub inline fn mustGetErrorCode() ErrorCode {
try getErrorCode();
@panic("glfw: mustGetErrorCode called but no error is present");
}
/// Returns and clears the last error description for the calling thread.
///
/// This function returns a UTF-8 encoded human-readable description of the last error that occured
/// on the calling thread. If no error has occurred since the last call, it returns null.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is guaranteed to be valid only until the next error occurs or the library is
/// terminated.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getErrorString() ?[:0]const u8 {
var desc: [*c]const u8 = null;
const error_code = c.glfwGetError(&desc);
if (error_code != c.GLFW_NO_ERROR) {
return mem.sliceTo(desc, 0);
}
return null;
}
/// Returns and clears the last error description for the calling thread. If no error is present,
/// this function panics.
pub inline fn mustGetErrorString() [:0]const u8 {
return getErrorString() orelse {
@panic("glfw: mustGetErrorString called but no error is present");
};
}
/// Sets the error callback.
///
/// This function sets the error callback, which is called with an error code
/// and a human-readable description each time a GLFW error occurs.
///
/// The error code is set before the callback is called. Calling @ref
/// glfwGetError from the error callback will return the same value as the error
/// code argument.
///
/// The error callback is called on the thread where the error occurred. If you
/// are using GLFW from multiple threads, your error callback needs to be
/// written accordingly.
///
/// Because the description string may have been generated specifically for that
/// error, it is not guaranteed to be valid after the callback has returned. If
/// you wish to use it after the callback returns, you need to make a copy.
///
/// Once set, the error callback remains set even after the library has been
/// terminated.
///
/// @param[in] callback The new callback, or `NULL` to remove the currently set
/// callback.
///
/// @callback_param `error_code` An error code. Future releases may add more error codes.
/// @callback_param `description` A UTF-8 encoded string describing the error.
///
/// @errors None.
///
/// @remark This function may be called before @ref glfwInit.
///
/// @thread_safety This function must only be called from the main thread.
pub fn setErrorCallback(comptime callback: ?fn (error_code: ErrorCode, description: [:0]const u8) void) void {
if (callback) |user_callback| {
const CWrapper = struct {
pub fn errorCallbackWrapper(err_int: c_int, c_description: [*c]const u8) callconv(.C) void {
convertError(err_int) catch |error_code| {
user_callback(error_code, mem.sliceTo(c_description, 0));
};
}
};
_ = c.glfwSetErrorCallback(CWrapper.errorCallbackWrapper);
return;
}
_ = c.glfwSetErrorCallback(null);
}
test "set error callback" {
const TestStruct = struct {
pub fn callback(_: ErrorCode, _: [:0]const u8) void {}
};
setErrorCallback(TestStruct.callback);
}
test "error string" {
try testing.expect(getErrorString() == null);
}
test "error code" {
try getErrorCode();
}
test "error code and string" {
try testing.expect(getError() == null);
}
test "clear error" {
clearError();
}

16
pkg/glfw/gamepad_axis.zig Normal file
View File

@ -0,0 +1,16 @@
const c = @import("c.zig").c;
/// Gamepad axes.
///
/// See glfw.getGamepadState for how these are used.
pub const GamepadAxis = enum(c_int) {
left_x = c.GLFW_GAMEPAD_AXIS_LEFT_X,
left_y = c.GLFW_GAMEPAD_AXIS_LEFT_Y,
right_x = c.GLFW_GAMEPAD_AXIS_RIGHT_X,
right_y = c.GLFW_GAMEPAD_AXIS_RIGHT_Y,
left_trigger = c.GLFW_GAMEPAD_AXIS_LEFT_TRIGGER,
right_trigger = c.GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER,
};
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const last = GamepadAxis.right_trigger;

View File

@ -0,0 +1,37 @@
const c = @import("c.zig").c;
/// Gamepad buttons.
///
/// See glfw.getGamepadState for how these are used.
pub const GamepadButton = enum(c_int) {
a = c.GLFW_GAMEPAD_BUTTON_A,
b = c.GLFW_GAMEPAD_BUTTON_B,
x = c.GLFW_GAMEPAD_BUTTON_X,
y = c.GLFW_GAMEPAD_BUTTON_Y,
left_bumper = c.GLFW_GAMEPAD_BUTTON_LEFT_BUMPER,
right_bumper = c.GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER,
back = c.GLFW_GAMEPAD_BUTTON_BACK,
start = c.GLFW_GAMEPAD_BUTTON_START,
guide = c.GLFW_GAMEPAD_BUTTON_GUIDE,
left_thumb = c.GLFW_GAMEPAD_BUTTON_LEFT_THUMB,
right_thumb = c.GLFW_GAMEPAD_BUTTON_RIGHT_THUMB,
dpad_up = c.GLFW_GAMEPAD_BUTTON_DPAD_UP,
dpad_right = c.GLFW_GAMEPAD_BUTTON_DPAD_RIGHT,
dpad_down = c.GLFW_GAMEPAD_BUTTON_DPAD_DOWN,
dpad_left = c.GLFW_GAMEPAD_BUTTON_DPAD_LEFT,
};
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const last = GamepadButton.dpad_left;
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const cross = GamepadButton.a;
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const circle = GamepadButton.b;
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const square = GamepadButton.x;
/// Not in the GamepadAxis enumeration as it is a duplicate value which is forbidden.
pub const triangle = GamepadButton.y;

100
pkg/glfw/hat.zig Normal file
View File

@ -0,0 +1,100 @@
const c = @import("c.zig").c;
// must be in sync with GLFW C constants in hat state group, search for "@defgroup hat_state Joystick hat states"
/// A bitmask of all Joystick hat states
///
/// See glfw.Joystick.getHats for how these are used.
pub const Hat = packed struct(u8) {
up: bool = false,
right: bool = false,
down: bool = false,
left: bool = false,
_padding: u4 = 0,
pub inline fn centered(self: Hat) bool {
return self.up == false and self.right == false and self.down == false and self.left == false;
}
inline fn verifyIntType(comptime IntType: type) void {
comptime {
switch (@import("shims.zig").typeInfo(IntType)) {
.int => {},
else => @compileError("Int was not of int type"),
}
}
}
pub inline fn toInt(self: Hat, comptime IntType: type) IntType {
verifyIntType(IntType);
return @as(IntType, @intCast(@as(u8, @bitCast(self))));
}
pub inline fn fromInt(flags: anytype) Hat {
verifyIntType(@TypeOf(flags));
return @as(Hat, @bitCast(@as(u8, @intCast(flags))));
}
};
/// Holds all GLFW hat values in their raw form.
pub const RawHat = struct {
pub const centered = c.GLFW_HAT_CENTERED;
pub const up = c.GLFW_HAT_UP;
pub const right = c.GLFW_HAT_RIGHT;
pub const down = c.GLFW_HAT_DOWN;
pub const left = c.GLFW_HAT_LEFT;
pub const right_up = right | up;
pub const right_down = right | down;
pub const left_up = left | up;
pub const left_down = left | down;
};
test "from int, single" {
const std = @import("std");
try std.testing.expectEqual(Hat{
.up = true,
.right = false,
.down = false,
.left = false,
._padding = 0,
}, Hat.fromInt(RawHat.up));
}
test "from int, multi" {
const std = @import("std");
try std.testing.expectEqual(Hat{
.up = true,
.right = false,
.down = true,
.left = true,
._padding = 0,
}, Hat.fromInt(RawHat.up | RawHat.down | RawHat.left));
}
test "to int, single" {
const std = @import("std");
var v = Hat{
.up = true,
.right = false,
.down = false,
.left = false,
._padding = 0,
};
try std.testing.expectEqual(v.toInt(c_int), RawHat.up);
}
test "to int, multi" {
const std = @import("std");
var v = Hat{
.up = true,
.right = false,
.down = true,
.left = true,
._padding = 0,
};
try std.testing.expectEqual(v.toInt(c_int), RawHat.up | RawHat.down | RawHat.left);
}

View File

@ -0,0 +1,14 @@
const std = @import("std");
const builtin = @import("builtin");
const is_debug = builtin.mode == .Debug;
var glfw_initialized = if (is_debug) false else @as(void, {});
pub inline fn toggleInitialized() void {
if (is_debug) glfw_initialized = !glfw_initialized;
}
pub inline fn assertInitialized() void {
if (is_debug) std.debug.assert(glfw_initialized);
}
pub inline fn assumeInitialized() void {
if (is_debug) glfw_initialized = true;
}

266
pkg/glfw/key.zig Normal file
View File

@ -0,0 +1,266 @@
//! Keyboard key IDs.
//!
//! See glfw.setKeyCallback for how these are used.
//!
//! These key codes are inspired by the _USB HID Usage Tables v1.12_ (p. 53-60), but re-arranged to
//! map to 7-bit ASCII for printable keys (function keys are put in the 256+ range).
//!
//! The naming of the key codes follow these rules:
//!
//! - The US keyboard layout is used
//! - Names of printable alphanumeric characters are used (e.g. "a", "r", "three", etc.)
//! - For non-alphanumeric characters, Unicode:ish names are used (e.g. "comma", "left_bracket",
//! etc.). Note that some names do not correspond to the Unicode standard (usually for brevity)
//! - Keys that lack a clear US mapping are named "world_x"
//! - For non-printable keys, custom names are used (e.g. "F4", "backspace", etc.)
const std = @import("std");
const cc = @import("c.zig").c;
const internal_debug = @import("internal_debug.zig");
/// enum containing all glfw keys
pub const Key = enum(c_int) {
/// The unknown key
unknown = cc.GLFW_KEY_UNKNOWN,
/// Printable keys
space = cc.GLFW_KEY_SPACE,
apostrophe = cc.GLFW_KEY_APOSTROPHE,
comma = cc.GLFW_KEY_COMMA,
minus = cc.GLFW_KEY_MINUS,
period = cc.GLFW_KEY_PERIOD,
slash = cc.GLFW_KEY_SLASH,
zero = cc.GLFW_KEY_0,
one = cc.GLFW_KEY_1,
two = cc.GLFW_KEY_2,
three = cc.GLFW_KEY_3,
four = cc.GLFW_KEY_4,
five = cc.GLFW_KEY_5,
six = cc.GLFW_KEY_6,
seven = cc.GLFW_KEY_7,
eight = cc.GLFW_KEY_8,
nine = cc.GLFW_KEY_9,
semicolon = cc.GLFW_KEY_SEMICOLON,
equal = cc.GLFW_KEY_EQUAL,
a = cc.GLFW_KEY_A,
b = cc.GLFW_KEY_B,
c = cc.GLFW_KEY_C,
d = cc.GLFW_KEY_D,
e = cc.GLFW_KEY_E,
f = cc.GLFW_KEY_F,
g = cc.GLFW_KEY_G,
h = cc.GLFW_KEY_H,
i = cc.GLFW_KEY_I,
j = cc.GLFW_KEY_J,
k = cc.GLFW_KEY_K,
l = cc.GLFW_KEY_L,
m = cc.GLFW_KEY_M,
n = cc.GLFW_KEY_N,
o = cc.GLFW_KEY_O,
p = cc.GLFW_KEY_P,
q = cc.GLFW_KEY_Q,
r = cc.GLFW_KEY_R,
s = cc.GLFW_KEY_S,
t = cc.GLFW_KEY_T,
u = cc.GLFW_KEY_U,
v = cc.GLFW_KEY_V,
w = cc.GLFW_KEY_W,
x = cc.GLFW_KEY_X,
y = cc.GLFW_KEY_Y,
z = cc.GLFW_KEY_Z,
left_bracket = cc.GLFW_KEY_LEFT_BRACKET,
backslash = cc.GLFW_KEY_BACKSLASH,
right_bracket = cc.GLFW_KEY_RIGHT_BRACKET,
grave_accent = cc.GLFW_KEY_GRAVE_ACCENT,
world_1 = cc.GLFW_KEY_WORLD_1, // non-US #1
world_2 = cc.GLFW_KEY_WORLD_2, // non-US #2
// Function keys
escape = cc.GLFW_KEY_ESCAPE,
enter = cc.GLFW_KEY_ENTER,
tab = cc.GLFW_KEY_TAB,
backspace = cc.GLFW_KEY_BACKSPACE,
insert = cc.GLFW_KEY_INSERT,
delete = cc.GLFW_KEY_DELETE,
right = cc.GLFW_KEY_RIGHT,
left = cc.GLFW_KEY_LEFT,
down = cc.GLFW_KEY_DOWN,
up = cc.GLFW_KEY_UP,
page_up = cc.GLFW_KEY_PAGE_UP,
page_down = cc.GLFW_KEY_PAGE_DOWN,
home = cc.GLFW_KEY_HOME,
end = cc.GLFW_KEY_END,
caps_lock = cc.GLFW_KEY_CAPS_LOCK,
scroll_lock = cc.GLFW_KEY_SCROLL_LOCK,
num_lock = cc.GLFW_KEY_NUM_LOCK,
print_screen = cc.GLFW_KEY_PRINT_SCREEN,
pause = cc.GLFW_KEY_PAUSE,
F1 = cc.GLFW_KEY_F1,
F2 = cc.GLFW_KEY_F2,
F3 = cc.GLFW_KEY_F3,
F4 = cc.GLFW_KEY_F4,
F5 = cc.GLFW_KEY_F5,
F6 = cc.GLFW_KEY_F6,
F7 = cc.GLFW_KEY_F7,
F8 = cc.GLFW_KEY_F8,
F9 = cc.GLFW_KEY_F9,
F10 = cc.GLFW_KEY_F10,
F11 = cc.GLFW_KEY_F11,
F12 = cc.GLFW_KEY_F12,
F13 = cc.GLFW_KEY_F13,
F14 = cc.GLFW_KEY_F14,
F15 = cc.GLFW_KEY_F15,
F16 = cc.GLFW_KEY_F16,
F17 = cc.GLFW_KEY_F17,
F18 = cc.GLFW_KEY_F18,
F19 = cc.GLFW_KEY_F19,
F20 = cc.GLFW_KEY_F20,
F21 = cc.GLFW_KEY_F21,
F22 = cc.GLFW_KEY_F22,
F23 = cc.GLFW_KEY_F23,
F24 = cc.GLFW_KEY_F24,
F25 = cc.GLFW_KEY_F25,
kp_0 = cc.GLFW_KEY_KP_0,
kp_1 = cc.GLFW_KEY_KP_1,
kp_2 = cc.GLFW_KEY_KP_2,
kp_3 = cc.GLFW_KEY_KP_3,
kp_4 = cc.GLFW_KEY_KP_4,
kp_5 = cc.GLFW_KEY_KP_5,
kp_6 = cc.GLFW_KEY_KP_6,
kp_7 = cc.GLFW_KEY_KP_7,
kp_8 = cc.GLFW_KEY_KP_8,
kp_9 = cc.GLFW_KEY_KP_9,
kp_decimal = cc.GLFW_KEY_KP_DECIMAL,
kp_divide = cc.GLFW_KEY_KP_DIVIDE,
kp_multiply = cc.GLFW_KEY_KP_MULTIPLY,
kp_subtract = cc.GLFW_KEY_KP_SUBTRACT,
kp_add = cc.GLFW_KEY_KP_ADD,
kp_enter = cc.GLFW_KEY_KP_ENTER,
kp_equal = cc.GLFW_KEY_KP_EQUAL,
left_shift = cc.GLFW_KEY_LEFT_SHIFT,
left_control = cc.GLFW_KEY_LEFT_CONTROL,
left_alt = cc.GLFW_KEY_LEFT_ALT,
left_super = cc.GLFW_KEY_LEFT_SUPER,
right_shift = cc.GLFW_KEY_RIGHT_SHIFT,
right_control = cc.GLFW_KEY_RIGHT_CONTROL,
right_alt = cc.GLFW_KEY_RIGHT_ALT,
right_super = cc.GLFW_KEY_RIGHT_SUPER,
menu = cc.GLFW_KEY_MENU,
pub inline fn last() Key {
return @as(Key, @enumFromInt(cc.GLFW_KEY_LAST));
}
/// Returns the layout-specific name of the specified printable key.
///
/// This function returns the name of the specified printable key, encoded as UTF-8. This is
/// typically the character that key would produce without any modifier keys, intended for
/// displaying key bindings to the user. For dead keys, it is typically the diacritic it would add
/// to a character.
///
/// __Do not use this function__ for text input (see input_char). You will break text input for many
/// languages even if it happens to work for yours.
///
/// If the key is `glfw.key.unknown`, the scancode is used to identify the key, otherwise the
/// scancode is ignored. If you specify a non-printable key, or `glfw.key.unknown` and a scancode
/// that maps to a non-printable key, this function returns null but does not emit an error.
///
/// This behavior allows you to always pass in the arguments in the key callback (see input_key)
/// without modification.
///
/// The printable keys are:
///
/// - `glfw.Key.apostrophe`
/// - `glfw.Key.comma`
/// - `glfw.Key.minus`
/// - `glfw.Key.period`
/// - `glfw.Key.slash`
/// - `glfw.Key.semicolon`
/// - `glfw.Key.equal`
/// - `glfw.Key.left_bracket`
/// - `glfw.Key.right_bracket`
/// - `glfw.Key.backslash`
/// - `glfw.Key.world_1`
/// - `glfw.Key.world_2`
/// - `glfw.Key.0` to `glfw.key.9`
/// - `glfw.Key.a` to `glfw.key.z`
/// - `glfw.Key.kp_0` to `glfw.key.kp_9`
/// - `glfw.Key.kp_decimal`
/// - `glfw.Key.kp_divide`
/// - `glfw.Key.kp_multiply`
/// - `glfw.Key.kp_subtract`
/// - `glfw.Key.kp_add`
/// - `glfw.Key.kp_equal`
///
/// Names for printable keys depend on keyboard layout, while names for non-printable keys are the
/// same across layouts but depend on the application language and should be localized along with
/// other user interface text.
///
/// @param[in] key The key to query, or `glfw.key.unknown`.
/// @param[in] scancode The scancode of the key to query.
/// @return The UTF-8 encoded, layout-specific name of the key, or null.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Also returns null in the event of an error.
///
/// The contents of the returned string may change when a keyboard layout change event is received.
///
/// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the library is terminated.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: input_key_name
pub inline fn getName(self: Key, scancode: i32) ?[:0]const u8 {
internal_debug.assertInitialized();
const name_opt = cc.glfwGetKeyName(@intFromEnum(self), @as(c_int, @intCast(scancode)));
return if (name_opt) |name|
std.mem.span(@as([*:0]const u8, @ptrCast(name)))
else
null;
}
/// Returns the platform-specific scancode of the specified key.
///
/// This function returns the platform-specific scancode of the specified key.
///
/// If the key is `glfw.key.UNKNOWN` or does not exist on the keyboard this method will return `-1`.
///
/// @param[in] key Any named key (see keys).
/// @return The platform-specific scancode for the key.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.PlatformError.
/// Additionally returns -1 in the event of an error.
///
/// @thread_safety This function may be called from any thread.
pub inline fn getScancode(self: Key) i32 {
internal_debug.assertInitialized();
return cc.glfwGetKeyScancode(@intFromEnum(self));
}
};
test "getName" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.Key.a.getName(0);
}
test "getScancode" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.Key.a.getScancode();
}

586
pkg/glfw/main.zig Normal file
View File

@ -0,0 +1,586 @@
const std = @import("std");
const testing = std.testing;
const c = @import("c.zig").c;
const key = @import("key.zig");
const errors = @import("errors.zig");
/// Possible value for various window hints, etc.
pub const dont_care = c.GLFW_DONT_CARE;
pub const getError = errors.getError;
pub const mustGetError = errors.mustGetError;
pub const getErrorCode = errors.getErrorCode;
pub const mustGetErrorCode = errors.mustGetErrorCode;
pub const getErrorString = errors.getErrorString;
pub const mustGetErrorString = errors.mustGetErrorString;
pub const setErrorCallback = errors.setErrorCallback;
pub const clearError = errors.clearError;
pub const ErrorCode = errors.ErrorCode;
pub const Error = errors.Error;
pub const Action = @import("action.zig").Action;
pub const GamepadAxis = @import("gamepad_axis.zig").GamepadAxis;
pub const GamepadButton = @import("gamepad_button.zig").GamepadButton;
pub const gamepad_axis = @import("gamepad_axis.zig");
pub const gamepad_button = @import("gamepad_button.zig");
pub const GammaRamp = @import("GammaRamp.zig");
pub const Image = @import("Image.zig");
pub const Joystick = @import("Joystick.zig");
pub const Monitor = @import("Monitor.zig");
pub const mouse_button = @import("mouse_button.zig");
pub const MouseButton = mouse_button.MouseButton;
pub const version = @import("version.zig");
pub const VideoMode = @import("VideoMode.zig");
pub const Window = @import("Window.zig");
pub const Cursor = @import("Cursor.zig");
pub const Native = @import("native.zig").Native;
pub const BackendOptions = @import("native.zig").BackendOptions;
pub const Key = key.Key;
pub const setClipboardString = @import("clipboard.zig").setClipboardString;
pub const getClipboardString = @import("clipboard.zig").getClipboardString;
pub const makeContextCurrent = @import("opengl.zig").makeContextCurrent;
pub const getCurrentContext = @import("opengl.zig").getCurrentContext;
pub const swapInterval = @import("opengl.zig").swapInterval;
pub const extensionSupported = @import("opengl.zig").extensionSupported;
pub const GLProc = @import("opengl.zig").GLProc;
pub const getProcAddress = @import("opengl.zig").getProcAddress;
pub const getTime = @import("time.zig").getTime;
pub const setTime = @import("time.zig").setTime;
pub const getTimerValue = @import("time.zig").getTimerValue;
pub const getTimerFrequency = @import("time.zig").getTimerFrequency;
pub const Hat = @import("hat.zig").Hat;
pub const RawHat = @import("hat.zig").RawHat;
pub const Mods = @import("mod.zig").Mods;
pub const RawMods = @import("mod.zig").RawMods;
const internal_debug = @import("internal_debug.zig");
/// If GLFW was already initialized in your program, e.g. you are embedding Zig code into an existing
/// program that has already called glfwInit via the C API for you - then you need to tell mach/glfw
/// that it has in fact been initialized already, otherwise when you call other methods mach/glfw
/// would panic thinking glfw.init has not been called yet.
pub fn assumeInitialized() void {
internal_debug.assumeInitialized();
}
/// Initializes the GLFW library.
///
/// This function initializes the GLFW library. Before most GLFW functions can be used, GLFW must
/// be initialized, and before an application terminates GLFW should be terminated in order to free
/// any resources allocated during or after initialization.
///
/// If this function fails, it calls glfw.Terminate before returning. If it succeeds, you should
/// call glfw.Terminate before the application exits.
///
/// Additional calls to this function after successful initialization but before termination will
/// return immediately with no error.
///
/// The glfw.InitHint.platform init hint controls which platforms are considered during
/// initialization. This also depends on which platforms the library was compiled to support.
///
/// macos: This function will change the current directory of the application to the
/// `Contents/Resources` subdirectory of the application's bundle, if present. This can be disabled
/// with `glfw.InitHint.cocoa_chdir_resources`.
///
/// macos: This function will create the main menu and dock icon for the application. If GLFW finds
/// a `MainMenu.nib` it is loaded and assumed to contain a menu bar. Otherwise a minimal menu bar is
/// created manually with common commands like Hide, Quit and About. The About entry opens a minimal
/// about dialog with information from the application's bundle. The menu bar and dock icon can be
/// disabled entirely with `glfw.InitHint.cocoa_menubar`.
///
/// x11: This function will set the `LC_CTYPE` category of the application locale according to the
/// current environment if that category is still "C". This is because the "C" locale breaks
/// Unicode text input.
///
/// Possible errors include glfw.ErrorCode.PlatformUnavailable, glfw.ErrorCode.PlatformError.
/// Returns a bool indicating success.
///
/// @thread_safety This function must only be called from the main thread.
pub inline fn init(hints: InitHints) bool {
internal_debug.toggleInitialized();
internal_debug.assertInitialized();
errdefer {
internal_debug.assertInitialized();
internal_debug.toggleInitialized();
}
inline for (comptime std.meta.fieldNames(InitHints)) |field_name| {
const init_hint = @field(InitHint, field_name);
const init_value = @field(hints, field_name);
if (@TypeOf(init_value) == PlatformType) {
initHint(init_hint, @intFromEnum(init_value));
} else {
initHint(init_hint, init_value);
}
}
return c.glfwInit() == c.GLFW_TRUE;
}
// TODO: implement custom allocator support
//
// /*! @brief Sets the init allocator to the desired value.
// *
// * To use the default allocator, call this function with a `NULL` argument.
// *
// * If you specify an allocator struct, every member must be a valid function
// * pointer. If any member is `NULL`, this function emits @ref
// * GLFW_INVALID_VALUE and the init allocator is unchanged.
// *
// * @param[in] allocator The allocator to use at the next initialization, or
// * `NULL` to use the default one.
// *
// * @errors Possible errors include @ref GLFW_INVALID_VALUE.
// *
// * @pointer_lifetime The specified allocator is copied before this function
// * returns.
// *
// * @thread_safety This function must only be called from the main thread.
// *
// * @sa @ref init_allocator
// * @sa @ref glfwInit
// *
// * @since Added in version 3.4.
// *
// * @ingroup init
// */
// GLFWAPI void glfwInitAllocator(const GLFWallocator* allocator);
/// Terminates the GLFW library.
///
/// This function destroys all remaining windows and cursors, restores any modified gamma ramps
/// and frees any other allocated resources. Once this function is called, you must again call
/// glfw.init successfully before you will be able to use most GLFW functions.
///
/// If GLFW has been successfully initialized, this function should be called before the
/// application exits. If initialization fails, there is no need to call this function, as it is
/// called by glfw.init before it returns failure.
///
/// This function has no effect if GLFW is not initialized.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// warning: The contexts of any remaining windows must not be current on any other thread when
/// this function is called.
///
/// reentrancy: This function must not be called from a callback.
///
/// thread_safety: This function must only be called from the main thread.
pub inline fn terminate() void {
internal_debug.assertInitialized();
internal_debug.toggleInitialized();
c.glfwTerminate();
}
/// Initialization hints for passing into glfw.init
pub const InitHints = struct {
/// Specifies whether to also expose joystick hats as buttons, for compatibility with earlier
/// versions of GLFW that did not have glfwGetJoystickHats.
joystick_hat_buttons: bool = true,
/// macOS specific init hint. Ignored on other platforms.
///
/// Specifies whether to set the current directory to the application to the Contents/Resources
/// subdirectory of the application's bundle, if present.
cocoa_chdir_resources: bool = true,
/// macOS specific init hint. Ignored on other platforms.
///
/// specifies whether to create a basic menu bar, either from a nib or manually, when the first
/// window is created, which is when AppKit is initialized.
cocoa_menubar: bool = true,
/// Platform selection init hint.
///
/// Possible values are `PlatformType` enums.
platform: PlatformType = .any,
};
/// Initialization hints for passing into glfw.initHint
const InitHint = enum(c_int) {
/// Specifies whether to also expose joystick hats as buttons, for compatibility with earlier
/// versions of GLFW that did not have glfwGetJoystickHats.
///
/// Possible values are `true` and `false`.
joystick_hat_buttons = c.GLFW_JOYSTICK_HAT_BUTTONS,
/// ANGLE rendering backend init hint.
///
/// Possible values are `AnglePlatformType` enums.
angle_platform_type = c.GLFW_ANGLE_PLATFORM_TYPE,
/// Platform selection init hint.
///
/// Possible values are `PlatformType` enums.
platform = c.GLFW_PLATFORM,
/// macOS specific init hint. Ignored on other platforms.
///
/// Specifies whether to set the current directory to the application to the Contents/Resources
/// subdirectory of the application's bundle, if present.
///
/// Possible values are `true` and `false`.
cocoa_chdir_resources = c.GLFW_COCOA_CHDIR_RESOURCES,
/// macOS specific init hint. Ignored on other platforms.
///
/// specifies whether to create a basic menu bar, either from a nib or manually, when the first
/// window is created, which is when AppKit is initialized.
///
/// Possible values are `true` and `false`.
cocoa_menubar = c.GLFW_COCOA_MENUBAR,
/// X11 specific init hint.
x11_xcb_vulkan_surface = c.GLFW_X11_XCB_VULKAN_SURFACE,
/// Wayland specific init hint.
///
/// Possible values are `WaylandLibdecorInitHint` enums.
wayland_libdecor = c.GLFW_WAYLAND_LIBDECOR,
};
/// Angle platform type hints for glfw.InitHint.angle_platform_type
pub const AnglePlatformType = enum(c_int) {
none = c.GLFW_ANGLE_PLATFORM_TYPE_NONE,
opengl = c.GLFW_ANGLE_PLATFORM_TYPE_OPENGL,
opengles = c.GLFW_ANGLE_PLATFORM_TYPE_OPENGLES,
d3d9 = c.GLFW_ANGLE_PLATFORM_TYPE_D3D9,
d3d11 = c.GLFW_ANGLE_PLATFORM_TYPE_D3D11,
vulkan = c.GLFW_ANGLE_PLATFORM_TYPE_VULKAN,
metal = c.GLFW_ANGLE_PLATFORM_TYPE_METAL,
};
/// Wayland libdecor hints for glfw.InitHint.wayland_libdecor
///
/// libdecor is important for GNOME, since GNOME does not implement server side decorations on
/// wayland. libdecor is loaded dynamically at runtime, so in general enabling it is always
/// safe to do. It is enabled by default.
pub const WaylandLibdecorInitHint = enum(c_int) {
wayland_prefer_libdecor = c.GLFW_WAYLAND_PREFER_LIBDECOR,
wayland_disable_libdecor = c.GLFW_WAYLAND_DISABLE_LIBDECOR,
};
/// Platform type hints for glfw.InitHint.platform
pub const PlatformType = enum(c_int) {
/// Enables automatic platform detection.
/// Will default to X11 on wayland.
any = c.GLFW_ANY_PLATFORM,
win32 = c.GLFW_PLATFORM_WIN32,
cocoa = c.GLFW_PLATFORM_COCOA,
wayland = c.GLFW_PLATFORM_WAYLAND,
x11 = c.GLFW_PLATFORM_X11,
null = c.GLFW_PLATFORM_NULL,
};
/// Sets the specified init hint to the desired value.
///
/// This function sets hints for the next initialization of GLFW.
///
/// The values you set hints to are never reset by GLFW, but they only take effect during
/// initialization. Once GLFW has been initialized, any values you set will be ignored until the
/// library is terminated and initialized again.
///
/// Some hints are platform specific. These may be set on any platform but they will only affect
/// their specific platform. Other platforms will ignore them. Setting these hints requires no
/// platform specific headers or functions.
///
/// @param hint: The init hint to set.
/// @param value: The new value of the init hint.
///
/// Possible errors include glfw.ErrorCode.InvalidEnum and glfw.ErrorCode.InvalidValue.
///
/// @remarks This function may be called before glfw.init.
///
/// @thread_safety This function must only be called from the main thread.
fn initHint(hint: InitHint, value: anytype) void {
switch (@import("shims.zig").typeInfo(@TypeOf(value))) {
.int, .comptime_int => {
c.glfwInitHint(@intFromEnum(hint), @as(c_int, @intCast(value)));
},
.bool => c.glfwInitHint(@intFromEnum(hint), @as(c_int, @intCast(@intFromBool(value)))),
else => @compileError("expected a int or bool, got " ++ @typeName(@TypeOf(value))),
}
}
/// Returns a string describing the compile-time configuration.
///
/// This function returns the compile-time generated version string of the GLFW library binary. It
/// describes the version, platform, compiler and any platform or operating system specific
/// compile-time options. It should not be confused with the OpenGL or OpenGL ES version string,
/// queried with `glGetString`.
///
/// __Do not use the version string__ to parse the GLFW library version. Use the glfw.version
/// constants instead.
///
/// __Do not use the version string__ to parse what platforms are supported. The
/// `glfw.platformSupported` function lets you query platform support.
///
/// returns: The ASCII encoded GLFW version string.
///
/// remark: This function may be called before @ref glfw.Init.
///
/// pointer_lifetime: The returned string is static and compile-time generated.
///
/// thread_safety: This function may be called from any thread.
pub inline fn getVersionString() [:0]const u8 {
return std.mem.span(@as([*:0]const u8, @ptrCast(c.glfwGetVersionString())));
}
/// Returns the currently selected platform.
///
/// This function returns the platform that was selected during initialization. The returned value
/// will be one of `glfw.PlatformType.win32`, `glfw.PlatformType.cocoa`,
/// `glfw.PlatformType.wayland`, `glfw.PlatformType.x11` or `glfw.PlatformType.null`.
///
/// thread_safety: This function may be called from any thread.
pub fn getPlatform() PlatformType {
internal_debug.assertInitialized();
return @as(PlatformType, @enumFromInt(c.glfwGetPlatform()));
}
/// Returns whether the library includes support for the specified platform.
///
/// This function returns whether the library was compiled with support for the specified platform.
/// The platform must be one of `glfw.PlatformType.win32`, `glfw.PlatformType.cocoa`,
/// `glfw.PlatformType.wayland`, `glfw.PlatformType.x11` or `glfw.PlatformType.null`.
///
/// remark: This function may be called before glfw.Init.
///
/// thread_safety: This function may be called from any thread.
pub fn platformSupported(platform: PlatformType) bool {
internal_debug.assertInitialized();
return c.glfwPlatformSupported(@intFromEnum(platform)) == c.GLFW_TRUE;
}
/// Processes all pending events.
///
/// This function processes only those events that are already in the event queue and then returns
/// immediately. Processing events will cause the window and input callbacks associated with those
/// events to be called.
///
/// On some platforms, a window move, resize or menu operation will cause event processing to
/// block. This is due to how event processing is designed on those platforms. You can use the
/// window refresh callback (see window_refresh) to redraw the contents of your window when
/// necessary during such operations.
///
/// Do not assume that callbacks you set will _only_ be called in response to event processing
/// functions like this one. While it is necessary to poll for events, window systems that require
/// GLFW to register callbacks of its own can pass events to GLFW in response to many window system
/// function calls. GLFW will pass those events on to the application callbacks before returning.
///
/// Event processing is not required for joystick input to work.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: events, glfw.waitEvents, glfw.waitEventsTimeout
pub inline fn pollEvents() void {
internal_debug.assertInitialized();
c.glfwPollEvents();
}
/// Waits until events are queued and processes them.
///
/// This function puts the calling thread to sleep until at least one event is available in the
/// event queue. Once one or more events are available, it behaves exactly like glfw.pollEvents,
/// i.e. the events in the queue are processed and the function then returns immediately.
/// Processing events will cause the window and input callbacks associated with those events to be
/// called.
///
/// Since not all events are associated with callbacks, this function may return without a callback
/// having been called even if you are monitoring all callbacks.
///
/// On some platforms, a window move, resize or menu operation will cause event processing to
/// block. This is due to how event processing is designed on those platforms. You can use the
/// window refresh callback (see window_refresh) to redraw the contents of your window when
/// necessary during such operations.
///
/// Do not assume that callbacks you set will _only_ be called in response to event processing
/// functions like this one. While it is necessary to poll for events, window systems that require
/// GLFW to register callbacks of its own can pass events to GLFW in response to many window system
/// function calls. GLFW will pass those events on to the application callbacks before returning.
///
/// Event processing is not required for joystick input to work.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: events, glfw.pollEvents, glfw.waitEventsTimeout
pub inline fn waitEvents() void {
internal_debug.assertInitialized();
c.glfwWaitEvents();
}
/// Waits with timeout until events are queued and processes them.
///
/// This function puts the calling thread to sleep until at least one event is available in the
/// event queue, or until the specified timeout is reached. If one or more events are available, it
/// behaves exactly like glfw.pollEvents, i.e. the events in the queue are processed and the
/// function then returns immediately. Processing events will cause the window and input callbacks
/// associated with those events to be called.
///
/// The timeout value must be a positive finite number.
///
/// Since not all events are associated with callbacks, this function may return without a callback
/// having been called even if you are monitoring all callbacks.
///
/// On some platforms, a window move, resize or menu operation will cause event processing to
/// block. This is due to how event processing is designed on those platforms. You can use the
/// window refresh callback (see window_refresh) to redraw the contents of your window when
/// necessary during such operations.
///
/// Do not assume that callbacks you set will _only_ be called in response to event processing
/// functions like this one. While it is necessary to poll for events, window systems that require
/// GLFW to register callbacks of its own can pass events to GLFW in response to many window system
/// function calls. GLFW will pass those events on to the application callbacks before returning.
///
/// Event processing is not required for joystick input to work.
///
/// @param[in] timeout The maximum amount of time, in seconds, to wait.
///
/// Possible errors include glfw.ErrorCode.InvalidValue and glfw.ErrorCode.PlatformError.
///
/// @reentrancy This function must not be called from a callback.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: events, glfw.pollEvents, glfw.waitEvents
pub inline fn waitEventsTimeout(timeout: f64) void {
internal_debug.assertInitialized();
std.debug.assert(!std.math.isNan(timeout));
std.debug.assert(timeout >= 0);
std.debug.assert(timeout <= std.math.floatMax(f64));
c.glfwWaitEventsTimeout(timeout);
}
/// Posts an empty event to the event queue.
///
/// This function posts an empty event from the current thread to the event queue, causing
/// glfw.waitEvents or glfw.waitEventsTimeout to return.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: events, glfw.waitEvents, glfw.waitEventsTimeout
pub inline fn postEmptyEvent() void {
internal_debug.assertInitialized();
c.glfwPostEmptyEvent();
}
/// Returns whether raw mouse motion is supported.
///
/// This function returns whether raw mouse motion is supported on the current system. This status
/// does not change after GLFW has been initialized so you only need to check this once. If you
/// attempt to enable raw motion on a system that does not support it, glfw.ErrorCode.PlatformError
/// will be emitted.
///
/// Raw mouse motion is closer to the actual motion of the mouse across a surface. It is not
/// affected by the scaling and acceleration applied to the motion of the desktop cursor. That
/// processing is suitable for a cursor while raw motion is better for controlling for example a 3D
/// camera. Because of this, raw mouse motion is only provided when the cursor is disabled.
///
/// @return `true` if raw mouse motion is supported on the current machine, or `false` otherwise.
///
/// @thread_safety This function must only be called from the main thread.
///
/// see also: raw_mouse_motion, glfw.setInputMode
pub inline fn rawMouseMotionSupported() bool {
internal_debug.assertInitialized();
return c.glfwRawMouseMotionSupported() == c.GLFW_TRUE;
}
pub fn basicTest() !void {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
const window = Window.create(640, 480, "GLFW example", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
const start = std.time.milliTimestamp();
while (std.time.milliTimestamp() < start + 1000 and !window.shouldClose()) {
c.glfwPollEvents();
}
}
test {
std.testing.refAllDeclsRecursive(@This());
}
test "getVersionString" {
std.debug.print("\nGLFW version v{}.{}.{}\n", .{ version.major, version.minor, version.revision });
std.debug.print("\nstring: {s}\n", .{getVersionString()});
}
test "init" {
_ = init(.{ .cocoa_chdir_resources = true });
if (getErrorString()) |err| {
std.log.err("failed to initialize GLFW: {?s}", .{err});
std.process.exit(1);
}
defer terminate();
}
test "pollEvents" {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
pollEvents();
}
test "waitEventsTimeout" {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
waitEventsTimeout(0.25);
}
test "postEmptyEvent_and_waitEvents" {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
postEmptyEvent();
waitEvents();
}
test "rawMouseMotionSupported" {
defer clearError(); // clear any error we generate
if (!init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{getErrorString()});
std.process.exit(1);
}
defer terminate();
_ = rawMouseMotionSupported();
}
test "basic" {
try basicTest();
}

167
pkg/glfw/mod.zig Normal file
View File

@ -0,0 +1,167 @@
//! Modifier key flags
//!
//! See glfw.setKeyCallback for how these are used.
const c = @import("c.zig").c;
// must be in sync with GLFW C constants in modifier group, search for "@defgroup mods Modifier key flags"
/// A bitmask of all key modifiers
pub const Mods = packed struct(u8) {
shift: bool = false,
control: bool = false,
alt: bool = false,
super: bool = false,
caps_lock: bool = false,
num_lock: bool = false,
_padding: u2 = 0,
inline fn verifyIntType(comptime IntType: type) void {
comptime {
switch (@import("shims.zig").typeInfo(IntType)) {
.int => {},
else => @compileError("Int was not of int type"),
}
}
}
pub inline fn toInt(self: Mods, comptime IntType: type) IntType {
verifyIntType(IntType);
return @as(IntType, @intCast(@as(u8, @bitCast(self))));
}
pub inline fn fromInt(flags: anytype) Mods {
verifyIntType(@TypeOf(flags));
return @as(Mods, @bitCast(@as(u8, @intCast(flags))));
}
};
/// Holds all GLFW mod values in their raw form.
pub const RawMods = struct {
/// If this bit is set one or more Shift keys were held down.
pub const shift = c.GLFW_MOD_SHIFT;
/// If this bit is set one or more Control keys were held down.
pub const control = c.GLFW_MOD_CONTROL;
/// If this bit is set one or more Alt keys were held down.
pub const alt = c.GLFW_MOD_ALT;
/// If this bit is set one or more Super keys were held down.
pub const super = c.GLFW_MOD_SUPER;
/// If this bit is set the Caps Lock key is enabled and the glfw.lock_key_mods input mode is set.
pub const caps_lock = c.GLFW_MOD_CAPS_LOCK;
/// If this bit is set the Num Lock key is enabled and the glfw.lock_key_mods input mode is set.
pub const num_lock = c.GLFW_MOD_NUM_LOCK;
};
test "shift int to bitmask" {
const std = @import("std");
const int_mod = RawMods.shift;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == true);
try std.testing.expect(mod.control == false);
try std.testing.expect(mod.alt == false);
try std.testing.expect(mod.super == false);
try std.testing.expect(mod.caps_lock == false);
try std.testing.expect(mod.num_lock == false);
}
test "shift int and alt to bitmask" {
const std = @import("std");
const int_mod = RawMods.shift | RawMods.alt;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == true);
try std.testing.expect(mod.control == false);
try std.testing.expect(mod.alt == true);
try std.testing.expect(mod.super == false);
try std.testing.expect(mod.caps_lock == false);
try std.testing.expect(mod.num_lock == false);
}
test "super int to bitmask" {
const std = @import("std");
const int_mod = RawMods.super;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == false);
try std.testing.expect(mod.control == false);
try std.testing.expect(mod.alt == false);
try std.testing.expect(mod.super == true);
try std.testing.expect(mod.caps_lock == false);
try std.testing.expect(mod.num_lock == false);
}
test "num lock int to bitmask" {
const std = @import("std");
const int_mod = RawMods.num_lock;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == false);
try std.testing.expect(mod.control == false);
try std.testing.expect(mod.alt == false);
try std.testing.expect(mod.super == false);
try std.testing.expect(mod.caps_lock == false);
try std.testing.expect(mod.num_lock == true);
}
test "all int to bitmask" {
const std = @import("std");
const int_mod = RawMods.shift | RawMods.control |
RawMods.alt | RawMods.super |
RawMods.caps_lock | RawMods.num_lock;
const mod = Mods.fromInt(int_mod);
try std.testing.expect(mod.shift == true);
try std.testing.expect(mod.control == true);
try std.testing.expect(mod.alt == true);
try std.testing.expect(mod.super == true);
try std.testing.expect(mod.caps_lock == true);
try std.testing.expect(mod.num_lock == true);
}
test "shift bitmask to int" {
const std = @import("std");
const mod = Mods{ .shift = true };
const int_mod = mod.toInt(c_int);
try std.testing.expectEqual(int_mod, RawMods.shift);
}
test "shift and alt bitmask to int" {
const std = @import("std");
const mod = Mods{ .shift = true, .alt = true };
const int_mod = mod.toInt(c_int);
try std.testing.expectEqual(int_mod, RawMods.shift | RawMods.alt);
}
test "all bitmask to int" {
const std = @import("std");
const mod = Mods{
.shift = true,
.control = true,
.alt = true,
.super = true,
.caps_lock = true,
.num_lock = true,
};
const int_mod = mod.toInt(c_int);
const expected = RawMods.shift | RawMods.control |
RawMods.alt | RawMods.super |
RawMods.caps_lock | RawMods.num_lock;
try std.testing.expectEqual(int_mod, expected);
}

23
pkg/glfw/mouse_button.zig Normal file
View File

@ -0,0 +1,23 @@
const c = @import("c.zig").c;
/// Mouse button IDs.
///
/// See glfw.setMouseButtonCallback for how these are used.
pub const MouseButton = enum(c_int) {
// We use left/right/middle aliases here because those are more common and we cannot have
// duplicate values in a Zig enum.
left = c.GLFW_MOUSE_BUTTON_1,
right = c.GLFW_MOUSE_BUTTON_2,
middle = c.GLFW_MOUSE_BUTTON_3,
four = c.GLFW_MOUSE_BUTTON_4,
five = c.GLFW_MOUSE_BUTTON_5,
six = c.GLFW_MOUSE_BUTTON_6,
seven = c.GLFW_MOUSE_BUTTON_7,
eight = c.GLFW_MOUSE_BUTTON_8,
};
/// Not in the MouseButton enumeration as it is a duplicate value which is forbidden.
pub const last = MouseButton.eight;
pub const one = MouseButton.left;
pub const two = MouseButton.right;
pub const three = MouseButton.middle;

393
pkg/glfw/native.zig Normal file
View File

@ -0,0 +1,393 @@
//! Native access functions
const std = @import("std");
const Window = @import("Window.zig");
const Monitor = @import("Monitor.zig");
const internal_debug = @import("internal_debug.zig");
pub const BackendOptions = struct {
win32: bool = false,
wgl: bool = false,
cocoa: bool = false,
nsgl: bool = false,
x11: bool = false,
glx: bool = false,
wayland: bool = false,
egl: bool = false,
osmesa: bool = false,
};
/// This function returns a type which allows provides an interface to access
/// the native handles based on backends selected.
///
/// The available window API options are:
/// * win32
/// * cocoa
/// * x11
/// * wayland
///
/// The available context API options are:
///
/// * wgl
/// * nsgl
/// * glx
/// * egl
/// * osmesa
///
/// The chosen backends must match those the library was compiled for. Failure to do so
/// will cause a link-time error.
pub fn Native(comptime options: BackendOptions) type {
const native = @cImport({
// @cDefine("GLFW_INCLUDE_VULKAN", "1");
@cDefine("GLFW_INCLUDE_NONE", "1");
if (options.win32) @cDefine("GLFW_EXPOSE_NATIVE_WIN32", "1");
if (options.wgl) @cDefine("GLFW_EXPOSE_NATIVE_WGL", "1");
if (options.cocoa) @cDefine("GLFW_EXPOSE_NATIVE_COCOA", "1");
if (options.nsgl) @cDefine("GLFW_EXPOSE_NATIVE_NGSL", "1");
if (options.x11) @cDefine("GLFW_EXPOSE_NATIVE_X11", "1");
if (options.glx) @cDefine("GLFW_EXPOSE_NATIVE_GLX", "1");
if (options.wayland) @cDefine("GLFW_EXPOSE_NATIVE_WAYLAND", "1");
if (options.egl) @cDefine("GLFW_EXPOSE_NATIVE_EGL", "1");
if (options.osmesa) @cDefine("GLFW_EXPOSE_NATIVE_OSMESA", "1");
@cDefine("__kernel_ptr_semantics", "");
@cInclude("GLFW/glfw3.h");
@cInclude("GLFW/glfw3native.h");
});
return struct {
/// Returns the adapter device name of the specified monitor.
///
/// return: The UTF-8 encoded adapter device name (for example `\\.\DISPLAY1`) of the
/// specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWin32Adapter(monitor: Monitor) [*:0]const u8 {
internal_debug.assertInitialized();
if (native.glfwGetWin32Adapter(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)))) |adapter| return adapter;
// `glfwGetWin32Adapter` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the display device name of the specified monitor.
///
/// return: The UTF-8 encoded display device name (for example `\\.\DISPLAY1\Monitor0`)
/// of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWin32Monitor(monitor: Monitor) [*:0]const u8 {
internal_debug.assertInitialized();
if (native.glfwGetWin32Monitor(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)))) |mon| return mon;
// `glfwGetWin32Monitor` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `HWND` of the specified window.
///
/// The `HDC` associated with the window can be queried with the
/// [GetDC](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc)
/// function.
/// ```
/// const dc = std.os.windows.user32.GetDC(native.getWin32Window(window));
/// ```
/// This DC is private and does not need to be released.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWin32Window(window: Window) std.os.windows.HWND {
internal_debug.assertInitialized();
if (native.glfwGetWin32Window(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |win|
return @as(std.os.windows.HWND, @ptrCast(win));
// `glfwGetWin32Window` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `HGLRC` of the specified window.
///
/// The `HDC` associated with the window can be queried with the
/// [GetDC](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc)
/// function.
/// ```
/// const dc = std.os.windows.user32.GetDC(native.getWin32Window(window));
/// ```
/// This DC is private and does not need to be released.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext
/// null is returned in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWGLContext(window: Window) ?std.os.windows.HGLRC {
internal_debug.assertInitialized();
if (native.glfwGetWGLContext(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |context| return context;
return null;
}
/// Returns the `CGDirectDisplayID` of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getCocoaMonitor(monitor: Monitor) u32 {
internal_debug.assertInitialized();
const mon = native.glfwGetCocoaMonitor(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)));
if (mon != native.kCGNullDirectDisplay) return mon;
// `glfwGetCocoaMonitor` returns `kCGNullDirectDisplay` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `NSWindow` of the specified window.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getCocoaWindow(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
return native.glfwGetCocoaWindow(@as(*native.GLFWwindow, @ptrCast(window.handle)));
}
/// Returns the `NSWindow` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getNSGLContext(window: Window) u32 {
internal_debug.assertInitialized();
return native.glfwGetNSGLContext(@as(*native.GLFWwindow, @ptrCast(window.handle)));
}
/// Returns the `Display` used by GLFW.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getX11Display() *anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetX11Display()) |display| return @as(*anyopaque, @ptrCast(display));
// `glfwGetX11Display` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `RRCrtc` of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getX11Adapter(monitor: Monitor) u32 {
internal_debug.assertInitialized();
const adapter = native.glfwGetX11Adapter(@as(*native.GLFWMonitor, @ptrCast(monitor.handle)));
if (adapter != 0) return adapter;
// `glfwGetX11Adapter` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `RROutput` of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getX11Monitor(monitor: Monitor) u32 {
internal_debug.assertInitialized();
const mon = native.glfwGetX11Monitor(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)));
if (mon != 0) return mon;
// `glfwGetX11Monitor` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `Window` of the specified window.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getX11Window(window: Window) u32 {
internal_debug.assertInitialized();
const win = native.glfwGetX11Window(@as(*native.GLFWwindow, @ptrCast(window.handle)));
if (win != 0) return @as(u32, @intCast(win));
// `glfwGetX11Window` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Sets the current primary selection to the specified string.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
///
/// The specified string is copied before this function returns.
///
/// thread_safety: This function must only be called from the main thread.
pub fn setX11SelectionString(string: [*:0]const u8) void {
internal_debug.assertInitialized();
native.glfwSetX11SelectionString(string);
}
/// Returns the contents of the current primary selection as a string.
///
/// Possible errors include glfw.ErrorCode.PlatformError.
/// Returns null in the event of an error.
///
/// The returned string is allocated and freed by GLFW. You should not free it
/// yourself. It is valid until the next call to getX11SelectionString or
/// setX11SelectionString, or until the library is terminated.
///
/// thread_safety: This function must only be called from the main thread.
pub fn getX11SelectionString() ?[*:0]const u8 {
internal_debug.assertInitialized();
if (native.glfwGetX11SelectionString()) |str| return str;
return null;
}
/// Returns the `GLXContext` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
/// Returns null in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getGLXContext(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetGLXContext(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |context| return @as(*anyopaque, @ptrCast(context));
return null;
}
/// Returns the `GLXWindow` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
/// Returns null in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getGLXWindow(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
const win = native.glfwGetGLXWindow(@as(*native.GLFWwindow, @ptrCast(window.handle)));
if (win != 0) return @as(*anyopaque, @ptrCast(win));
return null;
}
/// Returns the `*wl_display` used by GLFW.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWaylandDisplay() *anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetWaylandDisplay()) |display| return @as(*anyopaque, @ptrCast(display));
// `glfwGetWaylandDisplay` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `*wl_output` of the specified monitor.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWaylandMonitor(monitor: Monitor) *anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetWaylandMonitor(@as(*native.GLFWmonitor, @ptrCast(monitor.handle)))) |mon| return @as(*anyopaque, @ptrCast(mon));
// `glfwGetWaylandMonitor` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `*wl_surface` of the specified window.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getWaylandWindow(window: Window) *anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetWaylandWindow(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |win| return @as(*anyopaque, @ptrCast(win));
// `glfwGetWaylandWindow` returns `null` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `EGLDisplay` used by GLFW.
///
/// remark: Because EGL is initialized on demand, this function will return `EGL_NO_DISPLAY`
/// until the first context has been created via EGL.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getEGLDisplay() *anyopaque {
internal_debug.assertInitialized();
const display = native.glfwGetEGLDisplay();
if (display != native.EGL_NO_DISPLAY) return @as(*anyopaque, @ptrCast(display));
// `glfwGetEGLDisplay` returns `EGL_NO_DISPLAY` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the `EGLContext` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
/// Returns null in the event of an error.
///
/// thread_safety This function may be called from any thread. Access is not synchronized.
pub fn getEGLContext(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
const context = native.glfwGetEGLContext(@as(*native.GLFWwindow, @ptrCast(window.handle)));
if (context != native.EGL_NO_CONTEXT) return @as(*anyopaque, @ptrCast(context));
return null;
}
/// Returns the `EGLSurface` of the specified window.
///
/// Possible errors include glfw.ErrorCode.NotInitalized and glfw.ErrorCode.NoWindowContext.
///
/// thread_safety This function may be called from any thread. Access is not synchronized.
pub fn getEGLSurface(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
const surface = native.glfwGetEGLSurface(@as(*native.GLFWwindow, @ptrCast(window.handle)));
if (surface != native.EGL_NO_SURFACE) return @as(*anyopaque, @ptrCast(surface));
return null;
}
pub const OSMesaColorBuffer = struct {
width: c_int,
height: c_int,
format: c_int,
buffer: *anyopaque,
};
/// Retrieves the color buffer associated with the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext and glfw.ErrorCode.PlatformError.
/// Returns null in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getOSMesaColorBuffer(window: Window) ?OSMesaColorBuffer {
internal_debug.assertInitialized();
var buf: OSMesaColorBuffer = undefined;
if (native.glfwGetOSMesaColorBuffer(
@as(*native.GLFWwindow, @ptrCast(window.handle)),
&buf.width,
&buf.height,
&buf.format,
&buf.buffer,
) == native.GLFW_TRUE) return buf;
return null;
}
pub const OSMesaDepthBuffer = struct {
width: c_int,
height: c_int,
bytes_per_value: c_int,
buffer: *anyopaque,
};
/// Retrieves the depth buffer associated with the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext and glfw.ErrorCode.PlatformError.
/// Returns null in the event of an error.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getOSMesaDepthBuffer(window: Window) ?OSMesaDepthBuffer {
internal_debug.assertInitialized();
var buf: OSMesaDepthBuffer = undefined;
if (native.glfwGetOSMesaDepthBuffer(
@as(*native.GLFWwindow, @ptrCast(window.handle)),
&buf.width,
&buf.height,
&buf.bytes_per_value,
&buf.buffer,
) == native.GLFW_TRUE) return buf;
return null;
}
/// Returns the 'OSMesaContext' of the specified window.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext.
///
/// thread_safety: This function may be called from any thread. Access is not synchronized.
pub fn getOSMesaContext(window: Window) ?*anyopaque {
internal_debug.assertInitialized();
if (native.glfwGetOSMesaContext(@as(*native.GLFWwindow, @ptrCast(window.handle)))) |context| return @as(*anyopaque, @ptrCast(context));
return null;
}
};
}

256
pkg/glfw/opengl.zig Normal file
View File

@ -0,0 +1,256 @@
const std = @import("std");
const builtin = @import("builtin");
const c = @import("c.zig").c;
const Window = @import("Window.zig");
const internal_debug = @import("internal_debug.zig");
/// Makes the context of the specified window current for the calling thread.
///
/// This function makes the OpenGL or OpenGL ES context of the specified window current on the
/// calling thread. A context must only be made current on a single thread at a time and each
/// thread can have only a single current context at a time.
///
/// When moving a context between threads, you must make it non-current on the old thread before
/// making it current on the new one.
///
/// By default, making a context non-current implicitly forces a pipeline flush. On machines that
/// support `GL_KHR_context_flush_control`, you can control whether a context performs this flush
/// by setting the glfw.context_release_behavior hint.
///
/// The specified window must have an OpenGL or OpenGL ES context. Specifying a window without a
/// context will generate glfw.ErrorCode.NoWindowContext.
///
/// @param[in] window The window whose context to make current, or null to
/// detach the current context.
///
/// Possible errors include glfw.ErrorCode.NoWindowContext and glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: context_current, glfwGetCurrentContext
pub inline fn makeContextCurrent(window: ?Window) void {
internal_debug.assertInitialized();
if (window) |w| c.glfwMakeContextCurrent(w.handle) else c.glfwMakeContextCurrent(null);
}
/// Returns the window whose context is current on the calling thread.
///
/// This function returns the window whose OpenGL or OpenGL ES context is current on the calling
/// thread.
///
/// Returns he window whose context is current, or null if no window's context is current.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: context_current, glfwMakeContextCurrent
pub inline fn getCurrentContext() ?Window {
internal_debug.assertInitialized();
if (c.glfwGetCurrentContext()) |handle| return Window.from(handle);
return null;
}
/// Sets the swap interval for the current context.
///
/// This function sets the swap interval for the current OpenGL or OpenGL ES context, i.e. the
/// number of screen updates to wait from the time glfw.SwapBuffers was called before swapping the
/// buffers and returning. This is sometimes called _vertical synchronization_, _vertical retrace
/// synchronization_ or just _vsync_.
///
/// A context that supports either of the `WGL_EXT_swap_control_tear` and `GLX_EXT_swap_control_tear`
/// extensions also accepts _negative_ swap intervals, which allows the driver to swap immediately
/// even if a frame arrives a little bit late. You can check for these extensions with glfw.extensionSupported.
///
/// A context must be current on the calling thread. Calling this function without a current context
/// will cause glfw.ErrorCode.NoCurrentContext.
///
/// This function does not apply to Vulkan. If you are rendering with Vulkan, see the present mode
/// of your swapchain instead.
///
/// @param[in] interval The minimum number of screen updates to wait for until the buffers are
/// swapped by glfw.swapBuffers.
///
/// Possible errors include glfw.ErrorCode.NoCurrentContext and glfw.ErrorCode.PlatformError.
///
/// This function is not called during context creation, leaving the swap interval set to whatever
/// is the default for that API. This is done because some swap interval extensions used by
/// GLFW do not allow the swap interval to be reset to zero once it has been set to a non-zero
/// value.
///
/// Some GPU drivers do not honor the requested swap interval, either because of a user setting
/// that overrides the application's request or due to bugs in the driver.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: buffer_swap, glfwSwapBuffers
pub inline fn swapInterval(interval: i32) void {
internal_debug.assertInitialized();
c.glfwSwapInterval(@as(c_int, @intCast(interval)));
}
/// Returns whether the specified extension is available.
///
/// This function returns whether the specified API extension (see context_glext) is supported by
/// the current OpenGL or OpenGL ES context. It searches both for client API extension and context
/// creation API extensions.
///
/// A context must be current on the calling thread. Calling this function without a current
/// context will cause glfw.ErrorCode.NoCurrentContext.
///
/// As this functions retrieves and searches one or more extension strings each call, it is
/// recommended that you cache its results if it is going to be used frequently. The extension
/// strings will not change during the lifetime of a context, so there is no danger in doing this.
///
/// This function does not apply to Vulkan. If you are using Vulkan, see glfw.getRequiredInstanceExtensions,
/// `vkEnumerateInstanceExtensionProperties` and `vkEnumerateDeviceExtensionProperties` instead.
///
/// @param[in] extension The ASCII encoded name of the extension.
/// @return `true` if the extension is available, or `false` otherwise.
///
/// Possible errors include glfw.ErrorCode.NoCurrentContext, glfw.ErrorCode.InvalidValue
/// and glfw.ErrorCode.PlatformError.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: context_glext, glfw.getProcAddress
pub inline fn extensionSupported(extension: [:0]const u8) bool {
internal_debug.assertInitialized();
std.debug.assert(extension.len != 0);
std.debug.assert(extension[0] != 0);
return c.glfwExtensionSupported(extension.ptr) == c.GLFW_TRUE;
}
/// Client API function pointer type.
///
/// Generic function pointer used for returning client API function pointers.
///
/// see also: context_glext, glfwGetProcAddress
pub const GLProc = *const fn () callconv(if (builtin.os.tag == .windows and builtin.cpu.arch == .x86) .Stdcall else .C) void;
/// Returns the address of the specified function for the current context.
///
/// This function returns the address of the specified OpenGL or OpenGL ES core or extension
/// function (see context_glext), if it is supported by the current context.
///
/// A context must be current on the calling thread. Calling this function without a current
/// context will cause glfw.ErrorCode.NoCurrentContext.
///
/// This function does not apply to Vulkan. If you are rendering with Vulkan, see glfw.getInstanceProcAddress,
/// `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` instead.
///
/// @param[in] procname The ASCII encoded name of the function.
/// @return The address of the function, or null if an error occurred.
///
/// To maintain ABI compatability with the C glfwGetProcAddress, as it is commonly passed into
/// libraries expecting that exact ABI, this function does not return an error. Instead, if
/// glfw.ErrorCode.NotInitialized, glfw.ErrorCode.NoCurrentContext, or glfw.ErrorCode.PlatformError
/// would occur this function will panic. You should ensure a valid OpenGL context exists and the
/// GLFW is initialized before calling this function.
///
/// The address of a given function is not guaranteed to be the same between contexts.
///
/// This function may return a non-null address despite the associated version or extension
/// not being available. Always check the context version or extension string first.
///
/// @pointer_lifetime The returned function pointer is valid until the context is destroyed or the
/// library is terminated.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: context_glext, glfwExtensionSupported
pub fn getProcAddress(proc_name: [*:0]const u8) callconv(.C) ?GLProc {
internal_debug.assertInitialized();
if (c.glfwGetProcAddress(proc_name)) |proc_address| return @ptrCast(proc_address);
return null;
}
test "makeContextCurrent" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "Hello, Zig!", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
glfw.makeContextCurrent(window);
}
test "getCurrentContext" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const current_context = glfw.getCurrentContext();
std.debug.assert(current_context == null);
}
test "swapInterval" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "Hello, Zig!", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
glfw.makeContextCurrent(window);
glfw.swapInterval(1);
}
test "getProcAddress" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "Hello, Zig!", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
glfw.makeContextCurrent(window);
_ = glfw.getProcAddress("foobar");
}
test "extensionSupported" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
const window = Window.create(640, 480, "Hello, Zig!", null, null, .{}) orelse {
std.log.warn("failed to create window: {?s}", .{glfw.getErrorString()});
return error.SkipZigTest; // note: we don't exit(1) here because our CI can't open windows
};
defer window.destroy();
glfw.makeContextCurrent(window);
_ = glfw.extensionSupported("foobar");
}

84
pkg/glfw/shims.zig Normal file
View File

@ -0,0 +1,84 @@
// Zig 0.14.0-dev changed the names of all 'std.builtin.Type' fields.
const old_std_builtin_type_field_names = @hasField(@import("std").builtin.Type, "Type");
pub const std = struct {
pub const builtin = struct {
pub const Type = if (old_std_builtin_type_field_names) union(enum) {
type: void,
void: void,
bool: void,
noreturn: void,
int: Int,
float: Float,
pointer: Pointer,
array: Array,
@"struct": Struct,
comptime_float: void,
comptime_int: void,
undefined: void,
null: void,
optional: Optional,
error_union: ErrorUnion,
error_set: ErrorSet,
@"enum": Enum,
@"union": Union,
@"fn": Fn,
@"opaque": Opaque,
frame: Frame,
@"anyframe": AnyFrame,
vector: Vector,
enum_literal: void,
pub const Int = @import("std").builtin.Type.Int;
pub const Float = @import("std").builtin.Type.Float;
pub const Pointer = @import("std").builtin.Type.Pointer;
pub const Array = @import("std").builtin.Type.Array;
pub const ContainerLayout = @import("std").builtin.Type.ContainerLayout;
pub const StructField = @import("std").builtin.Type.StructField;
pub const Struct = @import("std").builtin.Type.Struct;
pub const Optional = @import("std").builtin.Type.Optional;
pub const ErrorUnion = @import("std").builtin.Type.ErrorUnion;
pub const Error = @import("std").builtin.Type.Error;
pub const ErrorSet = @import("std").builtin.Type.ErrorSet;
pub const EnumField = @import("std").builtin.Type.EnumField;
pub const Enum = @import("std").builtin.Type.Enum;
pub const UnionField = @import("std").builtin.Type.UnionField;
pub const Union = @import("std").builtin.Type.Union;
pub const Fn = @import("std").builtin.Type.Fn;
pub const Opaque = @import("std").builtin.Type.Opaque;
pub const Frame = @import("std").builtin.Type.Frame;
pub const AnyFrame = @import("std").builtin.Type.AnyFrame;
pub const Vector = @import("std").builtin.Type.Vector;
pub const Declaration = @import("std").builtin.Type.Declaration;
} else @import("std").builtin.Type;
};
};
pub fn typeInfo(comptime T: type) std.builtin.Type {
return if (old_std_builtin_type_field_names) switch (@typeInfo(T)) {
.Type => .type,
.Void => .void,
.Bool => .bool,
.NoReturn => .noreturn,
.Int => |x| .{ .int = x },
.Float => |x| .{ .float = x },
.Pointer => |x| .{ .pointer = x },
.Array => |x| .{ .array = x },
.Struct => |x| .{ .@"struct" = x },
.ComptimeFloat => .comptime_float,
.ComptimeInt => .comptime_int,
.Undefined => .undefined,
.Null => .null,
.Optional => |x| .{ .optional = x },
.ErrorUnion => |x| .{ .error_union = x },
.ErrorSet => |x| .{ .error_set = x },
.Enum => |x| .{ .@"enum" = x },
.Union => |x| .{ .@"union" = x },
.Fn => |x| .{ .@"fn" = x },
.Opaque => |x| .{ .@"opaque" = x },
.Frame => |x| .{ .frame = x },
.AnyFrame => .@"anyframe",
.Vector => |x| .{ .vector = x },
.EnumLiteral => .enum_literal,
} else @typeInfo(T);
}

153
pkg/glfw/time.zig Normal file
View File

@ -0,0 +1,153 @@
const std = @import("std");
const c = @import("c.zig").c;
const internal_debug = @import("internal_debug.zig");
/// Returns the GLFW time.
///
/// This function returns the current GLFW time, in seconds. Unless the time
/// has been set using @ref glfwSetTime it measures time elapsed since GLFW was
/// initialized.
///
/// This function and @ref glfwSetTime are helper functions on top of glfw.getTimerFrequency
/// and glfw.getTimerValue.
///
/// The resolution of the timer is system dependent, but is usually on the order
/// of a few micro- or nanoseconds. It uses the highest-resolution monotonic
/// time source on each supported operating system.
///
/// @return The current time, in seconds, or zero if an
/// error occurred.
///
/// @thread_safety This function may be called from any thread. Reading and
/// writing of the internal base time is not atomic, so it needs to be
/// externally synchronized with calls to @ref glfwSetTime.
///
/// see also: time
pub inline fn getTime() f64 {
internal_debug.assertInitialized();
const time = c.glfwGetTime();
if (time != 0) return time;
// `glfwGetTime` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Sets the GLFW time.
///
/// This function sets the current GLFW time, in seconds. The value must be a positive finite
/// number less than or equal to 18446744073.0, which is approximately 584.5 years.
///
/// This function and @ref glfwGetTime are helper functions on top of glfw.getTimerFrequency and
/// glfw.getTimerValue.
///
/// @param[in] time The new value, in seconds.
///
/// Possible errors include glfw.ErrorCode.InvalidValue.
///
/// The upper limit of GLFW time is calculated as `floor((2^64 - 1) / 10^9)` and is due to
/// implementations storing nanoseconds in 64 bits. The limit may be increased in the future.
///
/// @thread_safety This function may be called from any thread. Reading and writing of the internal
/// base time is not atomic, so it needs to be externally synchronized with calls to glfw.getTime.
///
/// see also: time
pub inline fn setTime(time: f64) void {
internal_debug.assertInitialized();
std.debug.assert(!std.math.isNan(time));
std.debug.assert(time >= 0);
// assert time is lteq to largest number of seconds representable by u64 with nanosecond precision
std.debug.assert(time <= max_time: {
const @"2^64" = std.math.maxInt(u64);
break :max_time @divTrunc(@"2^64", std.time.ns_per_s);
});
c.glfwSetTime(time);
}
/// Returns the current value of the raw timer.
///
/// This function returns the current value of the raw timer, measured in `1/frequency` seconds. To
/// get the frequency, call glfw.getTimerFrequency.
///
/// @return The value of the timer, or zero if an error occurred.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: time, glfw.getTimerFrequency
pub inline fn getTimerValue() u64 {
internal_debug.assertInitialized();
const value = c.glfwGetTimerValue();
if (value != 0) return value;
// `glfwGetTimerValue` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
/// Returns the frequency, in Hz, of the raw timer.
///
/// This function returns the frequency, in Hz, of the raw timer.
///
/// @return The frequency of the timer, in Hz, or zero if an error occurred.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: time, glfw.getTimerValue
pub inline fn getTimerFrequency() u64 {
internal_debug.assertInitialized();
const frequency = c.glfwGetTimerFrequency();
if (frequency != 0) return frequency;
// `glfwGetTimerFrequency` returns `0` only for errors
// but the only potential error is unreachable (NotInitialized)
unreachable;
}
test "getTime" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = getTime();
}
test "setTime" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.setTime(1234);
}
test "getTimerValue" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.getTimerValue();
}
test "getTimerFrequency" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.getTimerFrequency();
}

18
pkg/glfw/version.zig Normal file
View File

@ -0,0 +1,18 @@
//! GLFW version info
const c = @import("c.zig").c;
/// The major version number of the GLFW library.
///
/// This is incremented when the API is changed in non-compatible ways.
pub const major = c.GLFW_VERSION_MAJOR;
/// The minor version number of the GLFW library.
///
/// This is incremented when features are added to the API but it remains backward-compatible.
pub const minor = c.GLFW_VERSION_MINOR;
/// The revision number of the GLFW library.
///
/// This is incremented when a bug fix release is made that does not contain any API changes.
pub const revision = c.GLFW_VERSION_REVISION;

290
pkg/glfw/vulkan.zig Normal file
View File

@ -0,0 +1,290 @@
const std = @import("std");
const builtin = @import("builtin");
const c = @import("c.zig").c;
const Window = @import("Window.zig");
const internal_debug = @import("internal_debug.zig");
/// Sets the desired Vulkan `vkGetInstanceProcAddr` function.
///
/// This function sets the `vkGetInstanceProcAddr` function that GLFW will use for all
/// Vulkan related entry point queries.
///
/// This feature is mostly useful on macOS, if your copy of the Vulkan loader is in
/// a location where GLFW cannot find it through dynamic loading, or if you are still
/// using the static library version of the loader.
///
/// If set to `NULL`, GLFW will try to load the Vulkan loader dynamically by its standard
/// name and get this function from there. This is the default behavior.
///
/// The standard name of the loader is `vulkan-1.dll` on Windows, `libvulkan.so.1` on
/// Linux and other Unix-like systems and `libvulkan.1.dylib` on macOS. If your code is
/// also loading it via these names then you probably don't need to use this function.
///
/// The function address you set is never reset by GLFW, but it only takes effect during
/// initialization. Once GLFW has been initialized, any updates will be ignored until the
/// library is terminated and initialized again.
///
/// remark: This function may be called before glfw.Init.
///
/// thread_safety: This function must only be called from the main thread.
pub fn initVulkanLoader(loader_function: ?VKGetInstanceProcAddr) void {
c.glfwInitVulkanLoader(loader_function orelse null);
}
pub const VKGetInstanceProcAddr = *const fn (vk_instance: c.VkInstance, name: [*c]const u8) callconv(.C) ?VKProc;
/// Returns whether the Vulkan loader and an ICD have been found.
///
/// This function returns whether the Vulkan loader and any minimally functional ICD have been
/// found.
///
/// The availability of a Vulkan loader and even an ICD does not by itself guarantee that surface
/// creation or even instance creation is possible. Call glfw.getRequiredInstanceExtensions
/// to check whether the extensions necessary for Vulkan surface creation are available and
/// glfw.getPhysicalDevicePresentationSupport to check whether a queue family of a physical device
/// supports image presentation.
///
/// @return `true` if Vulkan is minimally available, or `false` otherwise.
///
/// @thread_safety This function may be called from any thread.
pub inline fn vulkanSupported() bool {
internal_debug.assertInitialized();
const supported = c.glfwVulkanSupported();
return supported == c.GLFW_TRUE;
}
/// Returns the Vulkan instance extensions required by GLFW.
///
/// This function returns an array of names of Vulkan instance extensions required by GLFW for
/// creating Vulkan surfaces for GLFW windows. If successful, the list will always contain
/// `VK_KHR_surface`, so if you don't require any additional extensions you can pass this list
/// directly to the `VkInstanceCreateInfo` struct.
///
/// If Vulkan is not available on the machine, this function returns null and generates a
/// glfw.ErrorCode.APIUnavailable error. Call glfw.vulkanSupported to check whether Vulkan is at
/// least minimally available.
///
/// If Vulkan is available but no set of extensions allowing window surface creation was found,
/// this function returns null. You may still use Vulkan for off-screen rendering and compute work.
///
/// Possible errors include glfw.ErrorCode.APIUnavailable.
/// Returns null in the event of an error.
///
/// Additional extensions may be required by future versions of GLFW. You should check if any
/// extensions you wish to enable are already in the returned array, as it is an error to specify
/// an extension more than once in the `VkInstanceCreateInfo` struct.
///
/// @pointer_lifetime The returned array is allocated and freed by GLFW. You should not free it
/// yourself. It is guaranteed to be valid only until the library is terminated.
///
/// @thread_safety This function may be called from any thread.
///
/// see also: vulkan_ext, glfwCreateWindowSurface
pub inline fn getRequiredInstanceExtensions() ?[][*:0]const u8 {
internal_debug.assertInitialized();
var count: u32 = 0;
if (c.glfwGetRequiredInstanceExtensions(&count)) |extensions| return @as([*][*:0]const u8, @ptrCast(extensions))[0..count];
return null;
}
/// Vulkan API function pointer type.
///
/// Generic function pointer used for returning Vulkan API function pointers.
///
/// see also: vulkan_proc, glfw.getInstanceProcAddress
pub const VKProc = *const fn () callconv(if (builtin.os.tag == .windows and builtin.cpu.arch == .x86) .Stdcall else .C) void;
/// Returns the address of the specified Vulkan instance function.
///
/// This function returns the address of the specified Vulkan core or extension function for the
/// specified instance. If instance is set to null it can return any function exported from the
/// Vulkan loader, including at least the following functions:
///
/// - `vkEnumerateInstanceExtensionProperties`
/// - `vkEnumerateInstanceLayerProperties`
/// - `vkCreateInstance`
/// - `vkGetInstanceProcAddr`
///
/// If Vulkan is not available on the machine, this function returns null and generates a
/// glfw.ErrorCode.APIUnavailable error. Call glfw.vulkanSupported to check whether Vulkan is at
/// least minimally available.
///
/// This function is equivalent to calling `vkGetInstanceProcAddr` with a platform-specific query
/// of the Vulkan loader as a fallback.
///
/// @param[in] instance The Vulkan instance to query, or null to retrieve functions related to
/// instance creation.
/// @param[in] procname The ASCII encoded name of the function.
/// @return The address of the function, or null if an error occurred.
///
/// To maintain ABI compatability with the C glfwGetInstanceProcAddress, as it is commonly passed
/// into libraries expecting that exact ABI, this function does not return an error. Instead, if
/// glfw.ErrorCode.NotInitialized or glfw.ErrorCode.APIUnavailable would occur this function will panic.
/// You may check glfw.vulkanSupported prior to invoking this function.
///
/// @pointer_lifetime The returned function pointer is valid until the library is terminated.
///
/// @thread_safety This function may be called from any thread.
pub fn getInstanceProcAddress(vk_instance: ?*anyopaque, proc_name: [*:0]const u8) callconv(.C) ?VKProc {
internal_debug.assertInitialized();
if (c.glfwGetInstanceProcAddress(if (vk_instance) |v| @as(c.VkInstance, @ptrCast(v)) else null, proc_name)) |proc_address| return proc_address;
return null;
}
/// Returns whether the specified queue family can present images.
///
/// This function returns whether the specified queue family of the specified physical device
/// supports presentation to the platform GLFW was built for.
///
/// If Vulkan or the required window surface creation instance extensions are not available on the
/// machine, or if the specified instance was not created with the required extensions, this
/// function returns `GLFW_FALSE` and generates a glfw.ErrorCode.APIUnavailable error. Call
/// glfw.vulkanSupported to check whether Vulkan is at least minimally available and
/// glfw.getRequiredInstanceExtensions to check what instance extensions are required.
///
/// @param[in] instance The instance that the physical device belongs to.
/// @param[in] device The physical device that the queue family belongs to.
/// @param[in] queuefamily The index of the queue family to query.
/// @return `true` if the queue family supports presentation, or `false` otherwise.
///
/// Possible errors include glfw.ErrorCode.APIUnavailable and glfw.ErrorCode.PlatformError.
/// Returns false in the event of an error.
///
/// macos: This function currently always returns `true`, as the `VK_MVK_macos_surface` and
/// 'VK_EXT_metal_surface' extension does not provide a `vkGetPhysicalDevice*PresentationSupport` type function.
///
/// @thread_safety This function may be called from any thread. For synchronization details of
/// Vulkan objects, see the Vulkan specification.
///
/// see also: vulkan_present
pub inline fn getPhysicalDevicePresentationSupport(
vk_instance: *anyopaque,
vk_physical_device: *anyopaque,
queue_family: u32,
) bool {
internal_debug.assertInitialized();
return c.glfwGetPhysicalDevicePresentationSupport(
@as(c.VkInstance, @ptrCast(vk_instance)),
@as(c.VkPhysicalDevice, @ptrCast(vk_physical_device)),
queue_family,
) == c.GLFW_TRUE;
}
/// Creates a Vulkan surface for the specified window.
///
/// This function creates a Vulkan surface for the specified window.
///
/// If the Vulkan loader or at least one minimally functional ICD were not found, this function
/// returns `VK_ERROR_INITIALIZATION_FAILED` and generates a glfw.ErrorCode.APIUnavailable error. Call
/// glfw.vulkanSupported to check whether Vulkan is at least minimally available.
///
/// If the required window surface creation instance extensions are not available or if the
/// specified instance was not created with these extensions enabled, this function returns `VK_ERROR_EXTENSION_NOT_PRESENT`
/// and generates a glfw.ErrorCode.APIUnavailable error. Call glfw.getRequiredInstanceExtensions to
/// check what instance extensions are required.
///
/// The window surface cannot be shared with another API so the window must have been created with
/// the client api hint set to `GLFW_NO_API` otherwise it generates a glfw.ErrorCode.InvalidValue error
/// and returns `VK_ERROR_NATIVE_WINDOW_IN_USE_KHR`.
///
/// The window surface must be destroyed before the specified Vulkan instance. It is the
/// responsibility of the caller to destroy the window surface. GLFW does not destroy it for you.
/// Call `vkDestroySurfaceKHR` to destroy the surface.
///
/// @param[in] vk_instance The Vulkan instance to create the surface in.
/// @param[in] window The window to create the surface for.
/// @param[in] vk_allocation_callbacks The allocator to use, or null to use the default
/// allocator.
/// @param[out] surface Where to store the handle of the surface. This is set
/// to `VK_NULL_HANDLE` if an error occurred.
/// @return `VkResult` type, `VK_SUCCESS` if successful, or a Vulkan error code if an
/// error occurred.
///
/// Possible errors include glfw.ErrorCode.APIUnavailable, glfw.ErrorCode.PlatformError and glfw.ErrorCode.InvalidValue
/// Returns a bool indicating success.
///
/// If an error occurs before the creation call is made, GLFW returns the Vulkan error code most
/// appropriate for the error. Appropriate use of glfw.vulkanSupported and glfw.getRequiredInstanceExtensions
/// should eliminate almost all occurrences of these errors.
///
/// macos: GLFW prefers the `VK_EXT_metal_surface` extension, with the `VK_MVK_macos_surface`
/// extension as a fallback. The name of the selected extension, if any, is included in the array
/// returned by glfw.getRequiredInstanceExtensions.
///
/// macos: This function currently only supports the `VK_MVK_macos_surface` extension from MoltenVK.
///
/// macos: This function creates and sets a `CAMetalLayer` instance for the window content view,
/// which is required for MoltenVK to function.
///
/// x11: By default GLFW prefers the `VK_KHR_xcb_surface` extension, with the `VK_KHR_xlib_surface`
/// extension as a fallback. You can make `VK_KHR_xlib_surface` the preferred extension by setting
/// glfw.InitHints.x11_xcb_vulkan_surface. The name of the selected extension, if any, is included
/// in the array returned by glfw.getRequiredInstanceExtensions.
///
/// @thread_safety This function may be called from any thread. For synchronization details of
/// Vulkan objects, see the Vulkan specification.
///
/// see also: vulkan_surface, glfw.getRequiredInstanceExtensions
pub inline fn createWindowSurface(vk_instance: anytype, window: Window, vk_allocation_callbacks: anytype, vk_surface_khr: anytype) i32 {
internal_debug.assertInitialized();
// zig-vulkan uses enums to represent opaque pointers:
// pub const Instance = enum(usize) { null_handle = 0, _ };
const instance: c.VkInstance = switch (@import("shims.zig").typeInfo(@TypeOf(vk_instance))) {
.@"enum" => @as(c.VkInstance, @ptrFromInt(@intFromEnum(vk_instance))),
else => @as(c.VkInstance, @ptrCast(vk_instance)),
};
return c.glfwCreateWindowSurface(
instance,
window.handle,
if (vk_allocation_callbacks == null) null else @as(*const c.VkAllocationCallbacks, @ptrCast(@alignCast(vk_allocation_callbacks))),
@as(*c.VkSurfaceKHR, @ptrCast(@alignCast(vk_surface_khr))),
);
}
test "vulkanSupported" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.vulkanSupported();
}
test "getRequiredInstanceExtensions" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
_ = glfw.getRequiredInstanceExtensions();
}
test "getInstanceProcAddress" {
const glfw = @import("main.zig");
defer glfw.clearError(); // clear any error we generate
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
std.process.exit(1);
}
defer glfw.terminate();
// syntax check only, we don't have a real vulkan instance and so this function would panic.
_ = glfw.getInstanceProcAddress;
}
test "syntax" {
// Best we can do for these two functions in terms of testing in lieu of an actual Vulkan
// context.
_ = getPhysicalDevicePresentationSupport;
_ = createWindowSurface;
_ = initVulkanLoader;
}

View File

@ -0,0 +1,74 @@
/* Generated by wayland-scanner 1.23.1 */
/*
* Copyright © 2022 Kenny Levinsen
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
extern const struct wl_interface wl_surface_interface;
extern const struct wl_interface wp_fractional_scale_v1_interface;
static const struct wl_interface *fractional_scale_v1_types[] = {
NULL,
&wp_fractional_scale_v1_interface,
&wl_surface_interface,
};
static const struct wl_message wp_fractional_scale_manager_v1_requests[] = {
{ "destroy", "", fractional_scale_v1_types + 0 },
{ "get_fractional_scale", "no", fractional_scale_v1_types + 1 },
};
WL_PRIVATE const struct wl_interface wp_fractional_scale_manager_v1_interface = {
"wp_fractional_scale_manager_v1", 1,
2, wp_fractional_scale_manager_v1_requests,
0, NULL,
};
static const struct wl_message wp_fractional_scale_v1_requests[] = {
{ "destroy", "", fractional_scale_v1_types + 0 },
};
static const struct wl_message wp_fractional_scale_v1_events[] = {
{ "preferred_scale", "u", fractional_scale_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface wp_fractional_scale_v1_interface = {
"wp_fractional_scale_v1", 1,
1, wp_fractional_scale_v1_requests,
1, wp_fractional_scale_v1_events,
};

View File

@ -0,0 +1,264 @@
/* Generated by wayland-scanner 1.23.1 */
#ifndef FRACTIONAL_SCALE_V1_CLIENT_PROTOCOL_H
#define FRACTIONAL_SCALE_V1_CLIENT_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-client.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @page page_fractional_scale_v1 The fractional_scale_v1 protocol
* Protocol for requesting fractional surface scales
*
* @section page_desc_fractional_scale_v1 Description
*
* This protocol allows a compositor to suggest for surfaces to render at
* fractional scales.
*
* A client can submit scaled content by utilizing wp_viewport. This is done by
* creating a wp_viewport object for the surface and setting the destination
* rectangle to the surface size before the scale factor is applied.
*
* The buffer size is calculated by multiplying the surface size by the
* intended scale.
*
* The wl_surface buffer scale should remain set to 1.
*
* If a surface has a surface-local size of 100 px by 50 px and wishes to
* submit buffers with a scale of 1.5, then a buffer of 150px by 75 px should
* be used and the wp_viewport destination rectangle should be 100 px by 50 px.
*
* For toplevel surfaces, the size is rounded halfway away from zero. The
* rounding algorithm for subsurface position and size is not defined.
*
* @section page_ifaces_fractional_scale_v1 Interfaces
* - @subpage page_iface_wp_fractional_scale_manager_v1 - fractional surface scale information
* - @subpage page_iface_wp_fractional_scale_v1 - fractional scale interface to a wl_surface
* @section page_copyright_fractional_scale_v1 Copyright
* <pre>
*
* Copyright © 2022 Kenny Levinsen
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* </pre>
*/
struct wl_surface;
struct wp_fractional_scale_manager_v1;
struct wp_fractional_scale_v1;
#ifndef WP_FRACTIONAL_SCALE_MANAGER_V1_INTERFACE
#define WP_FRACTIONAL_SCALE_MANAGER_V1_INTERFACE
/**
* @page page_iface_wp_fractional_scale_manager_v1 wp_fractional_scale_manager_v1
* @section page_iface_wp_fractional_scale_manager_v1_desc Description
*
* A global interface for requesting surfaces to use fractional scales.
* @section page_iface_wp_fractional_scale_manager_v1_api API
* See @ref iface_wp_fractional_scale_manager_v1.
*/
/**
* @defgroup iface_wp_fractional_scale_manager_v1 The wp_fractional_scale_manager_v1 interface
*
* A global interface for requesting surfaces to use fractional scales.
*/
extern const struct wl_interface wp_fractional_scale_manager_v1_interface;
#endif
#ifndef WP_FRACTIONAL_SCALE_V1_INTERFACE
#define WP_FRACTIONAL_SCALE_V1_INTERFACE
/**
* @page page_iface_wp_fractional_scale_v1 wp_fractional_scale_v1
* @section page_iface_wp_fractional_scale_v1_desc Description
*
* An additional interface to a wl_surface object which allows the compositor
* to inform the client of the preferred scale.
* @section page_iface_wp_fractional_scale_v1_api API
* See @ref iface_wp_fractional_scale_v1.
*/
/**
* @defgroup iface_wp_fractional_scale_v1 The wp_fractional_scale_v1 interface
*
* An additional interface to a wl_surface object which allows the compositor
* to inform the client of the preferred scale.
*/
extern const struct wl_interface wp_fractional_scale_v1_interface;
#endif
#ifndef WP_FRACTIONAL_SCALE_MANAGER_V1_ERROR_ENUM
#define WP_FRACTIONAL_SCALE_MANAGER_V1_ERROR_ENUM
enum wp_fractional_scale_manager_v1_error {
/**
* the surface already has a fractional_scale object associated
*/
WP_FRACTIONAL_SCALE_MANAGER_V1_ERROR_FRACTIONAL_SCALE_EXISTS = 0,
};
#endif /* WP_FRACTIONAL_SCALE_MANAGER_V1_ERROR_ENUM */
#define WP_FRACTIONAL_SCALE_MANAGER_V1_DESTROY 0
#define WP_FRACTIONAL_SCALE_MANAGER_V1_GET_FRACTIONAL_SCALE 1
/**
* @ingroup iface_wp_fractional_scale_manager_v1
*/
#define WP_FRACTIONAL_SCALE_MANAGER_V1_DESTROY_SINCE_VERSION 1
/**
* @ingroup iface_wp_fractional_scale_manager_v1
*/
#define WP_FRACTIONAL_SCALE_MANAGER_V1_GET_FRACTIONAL_SCALE_SINCE_VERSION 1
/** @ingroup iface_wp_fractional_scale_manager_v1 */
static inline void
wp_fractional_scale_manager_v1_set_user_data(struct wp_fractional_scale_manager_v1 *wp_fractional_scale_manager_v1, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) wp_fractional_scale_manager_v1, user_data);
}
/** @ingroup iface_wp_fractional_scale_manager_v1 */
static inline void *
wp_fractional_scale_manager_v1_get_user_data(struct wp_fractional_scale_manager_v1 *wp_fractional_scale_manager_v1)
{
return wl_proxy_get_user_data((struct wl_proxy *) wp_fractional_scale_manager_v1);
}
static inline uint32_t
wp_fractional_scale_manager_v1_get_version(struct wp_fractional_scale_manager_v1 *wp_fractional_scale_manager_v1)
{
return wl_proxy_get_version((struct wl_proxy *) wp_fractional_scale_manager_v1);
}
/**
* @ingroup iface_wp_fractional_scale_manager_v1
*
* Informs the server that the client will not be using this protocol
* object anymore. This does not affect any other objects,
* wp_fractional_scale_v1 objects included.
*/
static inline void
wp_fractional_scale_manager_v1_destroy(struct wp_fractional_scale_manager_v1 *wp_fractional_scale_manager_v1)
{
wl_proxy_marshal_flags((struct wl_proxy *) wp_fractional_scale_manager_v1,
WP_FRACTIONAL_SCALE_MANAGER_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) wp_fractional_scale_manager_v1), WL_MARSHAL_FLAG_DESTROY);
}
/**
* @ingroup iface_wp_fractional_scale_manager_v1
*
* Create an add-on object for the the wl_surface to let the compositor
* request fractional scales. If the given wl_surface already has a
* wp_fractional_scale_v1 object associated, the fractional_scale_exists
* protocol error is raised.
*/
static inline struct wp_fractional_scale_v1 *
wp_fractional_scale_manager_v1_get_fractional_scale(struct wp_fractional_scale_manager_v1 *wp_fractional_scale_manager_v1, struct wl_surface *surface)
{
struct wl_proxy *id;
id = wl_proxy_marshal_flags((struct wl_proxy *) wp_fractional_scale_manager_v1,
WP_FRACTIONAL_SCALE_MANAGER_V1_GET_FRACTIONAL_SCALE, &wp_fractional_scale_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_fractional_scale_manager_v1), 0, NULL, surface);
return (struct wp_fractional_scale_v1 *) id;
}
/**
* @ingroup iface_wp_fractional_scale_v1
* @struct wp_fractional_scale_v1_listener
*/
struct wp_fractional_scale_v1_listener {
/**
* notify of new preferred scale
*
* Notification of a new preferred scale for this surface that
* the compositor suggests that the client should use.
*
* The sent scale is the numerator of a fraction with a denominator
* of 120.
* @param scale the new preferred scale
*/
void (*preferred_scale)(void *data,
struct wp_fractional_scale_v1 *wp_fractional_scale_v1,
uint32_t scale);
};
/**
* @ingroup iface_wp_fractional_scale_v1
*/
static inline int
wp_fractional_scale_v1_add_listener(struct wp_fractional_scale_v1 *wp_fractional_scale_v1,
const struct wp_fractional_scale_v1_listener *listener, void *data)
{
return wl_proxy_add_listener((struct wl_proxy *) wp_fractional_scale_v1,
(void (**)(void)) listener, data);
}
#define WP_FRACTIONAL_SCALE_V1_DESTROY 0
/**
* @ingroup iface_wp_fractional_scale_v1
*/
#define WP_FRACTIONAL_SCALE_V1_PREFERRED_SCALE_SINCE_VERSION 1
/**
* @ingroup iface_wp_fractional_scale_v1
*/
#define WP_FRACTIONAL_SCALE_V1_DESTROY_SINCE_VERSION 1
/** @ingroup iface_wp_fractional_scale_v1 */
static inline void
wp_fractional_scale_v1_set_user_data(struct wp_fractional_scale_v1 *wp_fractional_scale_v1, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) wp_fractional_scale_v1, user_data);
}
/** @ingroup iface_wp_fractional_scale_v1 */
static inline void *
wp_fractional_scale_v1_get_user_data(struct wp_fractional_scale_v1 *wp_fractional_scale_v1)
{
return wl_proxy_get_user_data((struct wl_proxy *) wp_fractional_scale_v1);
}
static inline uint32_t
wp_fractional_scale_v1_get_version(struct wp_fractional_scale_v1 *wp_fractional_scale_v1)
{
return wl_proxy_get_version((struct wl_proxy *) wp_fractional_scale_v1);
}
/**
* @ingroup iface_wp_fractional_scale_v1
*
* Destroy the fractional scale object. When this object is destroyed,
* preferred_scale events will no longer be sent.
*/
static inline void
wp_fractional_scale_v1_destroy(struct wp_fractional_scale_v1 *wp_fractional_scale_v1)
{
wl_proxy_marshal_flags((struct wl_proxy *) wp_fractional_scale_v1,
WP_FRACTIONAL_SCALE_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) wp_fractional_scale_v1), WL_MARSHAL_FLAG_DESTROY);
}
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,69 @@
/* Generated by wayland-scanner 1.23.1 */
/*
* Copyright © 2015 Samsung Electronics Co., Ltd
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
extern const struct wl_interface wl_surface_interface;
extern const struct wl_interface zwp_idle_inhibitor_v1_interface;
static const struct wl_interface *idle_inhibit_unstable_v1_types[] = {
&zwp_idle_inhibitor_v1_interface,
&wl_surface_interface,
};
static const struct wl_message zwp_idle_inhibit_manager_v1_requests[] = {
{ "destroy", "", idle_inhibit_unstable_v1_types + 0 },
{ "create_inhibitor", "no", idle_inhibit_unstable_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface zwp_idle_inhibit_manager_v1_interface = {
"zwp_idle_inhibit_manager_v1", 1,
2, zwp_idle_inhibit_manager_v1_requests,
0, NULL,
};
static const struct wl_message zwp_idle_inhibitor_v1_requests[] = {
{ "destroy", "", idle_inhibit_unstable_v1_types + 0 },
};
WL_PRIVATE const struct wl_interface zwp_idle_inhibitor_v1_interface = {
"zwp_idle_inhibitor_v1", 1,
1, zwp_idle_inhibitor_v1_requests,
0, NULL,
};

View File

@ -0,0 +1,232 @@
/* Generated by wayland-scanner 1.23.1 */
#ifndef IDLE_INHIBIT_UNSTABLE_V1_CLIENT_PROTOCOL_H
#define IDLE_INHIBIT_UNSTABLE_V1_CLIENT_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-client.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @page page_idle_inhibit_unstable_v1 The idle_inhibit_unstable_v1 protocol
* @section page_ifaces_idle_inhibit_unstable_v1 Interfaces
* - @subpage page_iface_zwp_idle_inhibit_manager_v1 - control behavior when display idles
* - @subpage page_iface_zwp_idle_inhibitor_v1 - context object for inhibiting idle behavior
* @section page_copyright_idle_inhibit_unstable_v1 Copyright
* <pre>
*
* Copyright © 2015 Samsung Electronics Co., Ltd
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
* </pre>
*/
struct wl_surface;
struct zwp_idle_inhibit_manager_v1;
struct zwp_idle_inhibitor_v1;
#ifndef ZWP_IDLE_INHIBIT_MANAGER_V1_INTERFACE
#define ZWP_IDLE_INHIBIT_MANAGER_V1_INTERFACE
/**
* @page page_iface_zwp_idle_inhibit_manager_v1 zwp_idle_inhibit_manager_v1
* @section page_iface_zwp_idle_inhibit_manager_v1_desc Description
*
* This interface permits inhibiting the idle behavior such as screen
* blanking, locking, and screensaving. The client binds the idle manager
* globally, then creates idle-inhibitor objects for each surface.
*
* Warning! The protocol described in this file is experimental and
* backward incompatible changes may be made. Backward compatible changes
* may be added together with the corresponding interface version bump.
* Backward incompatible changes are done by bumping the version number in
* the protocol and interface names and resetting the interface version.
* Once the protocol is to be declared stable, the 'z' prefix and the
* version number in the protocol and interface names are removed and the
* interface version number is reset.
* @section page_iface_zwp_idle_inhibit_manager_v1_api API
* See @ref iface_zwp_idle_inhibit_manager_v1.
*/
/**
* @defgroup iface_zwp_idle_inhibit_manager_v1 The zwp_idle_inhibit_manager_v1 interface
*
* This interface permits inhibiting the idle behavior such as screen
* blanking, locking, and screensaving. The client binds the idle manager
* globally, then creates idle-inhibitor objects for each surface.
*
* Warning! The protocol described in this file is experimental and
* backward incompatible changes may be made. Backward compatible changes
* may be added together with the corresponding interface version bump.
* Backward incompatible changes are done by bumping the version number in
* the protocol and interface names and resetting the interface version.
* Once the protocol is to be declared stable, the 'z' prefix and the
* version number in the protocol and interface names are removed and the
* interface version number is reset.
*/
extern const struct wl_interface zwp_idle_inhibit_manager_v1_interface;
#endif
#ifndef ZWP_IDLE_INHIBITOR_V1_INTERFACE
#define ZWP_IDLE_INHIBITOR_V1_INTERFACE
/**
* @page page_iface_zwp_idle_inhibitor_v1 zwp_idle_inhibitor_v1
* @section page_iface_zwp_idle_inhibitor_v1_desc Description
*
* An idle inhibitor prevents the output that the associated surface is
* visible on from being set to a state where it is not visually usable due
* to lack of user interaction (e.g. blanked, dimmed, locked, set to power
* save, etc.) Any screensaver processes are also blocked from displaying.
*
* If the surface is destroyed, unmapped, becomes occluded, loses
* visibility, or otherwise becomes not visually relevant for the user, the
* idle inhibitor will not be honored by the compositor; if the surface
* subsequently regains visibility the inhibitor takes effect once again.
* Likewise, the inhibitor isn't honored if the system was already idled at
* the time the inhibitor was established, although if the system later
* de-idles and re-idles the inhibitor will take effect.
* @section page_iface_zwp_idle_inhibitor_v1_api API
* See @ref iface_zwp_idle_inhibitor_v1.
*/
/**
* @defgroup iface_zwp_idle_inhibitor_v1 The zwp_idle_inhibitor_v1 interface
*
* An idle inhibitor prevents the output that the associated surface is
* visible on from being set to a state where it is not visually usable due
* to lack of user interaction (e.g. blanked, dimmed, locked, set to power
* save, etc.) Any screensaver processes are also blocked from displaying.
*
* If the surface is destroyed, unmapped, becomes occluded, loses
* visibility, or otherwise becomes not visually relevant for the user, the
* idle inhibitor will not be honored by the compositor; if the surface
* subsequently regains visibility the inhibitor takes effect once again.
* Likewise, the inhibitor isn't honored if the system was already idled at
* the time the inhibitor was established, although if the system later
* de-idles and re-idles the inhibitor will take effect.
*/
extern const struct wl_interface zwp_idle_inhibitor_v1_interface;
#endif
#define ZWP_IDLE_INHIBIT_MANAGER_V1_DESTROY 0
#define ZWP_IDLE_INHIBIT_MANAGER_V1_CREATE_INHIBITOR 1
/**
* @ingroup iface_zwp_idle_inhibit_manager_v1
*/
#define ZWP_IDLE_INHIBIT_MANAGER_V1_DESTROY_SINCE_VERSION 1
/**
* @ingroup iface_zwp_idle_inhibit_manager_v1
*/
#define ZWP_IDLE_INHIBIT_MANAGER_V1_CREATE_INHIBITOR_SINCE_VERSION 1
/** @ingroup iface_zwp_idle_inhibit_manager_v1 */
static inline void
zwp_idle_inhibit_manager_v1_set_user_data(struct zwp_idle_inhibit_manager_v1 *zwp_idle_inhibit_manager_v1, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) zwp_idle_inhibit_manager_v1, user_data);
}
/** @ingroup iface_zwp_idle_inhibit_manager_v1 */
static inline void *
zwp_idle_inhibit_manager_v1_get_user_data(struct zwp_idle_inhibit_manager_v1 *zwp_idle_inhibit_manager_v1)
{
return wl_proxy_get_user_data((struct wl_proxy *) zwp_idle_inhibit_manager_v1);
}
static inline uint32_t
zwp_idle_inhibit_manager_v1_get_version(struct zwp_idle_inhibit_manager_v1 *zwp_idle_inhibit_manager_v1)
{
return wl_proxy_get_version((struct wl_proxy *) zwp_idle_inhibit_manager_v1);
}
/**
* @ingroup iface_zwp_idle_inhibit_manager_v1
*
* Destroy the inhibit manager.
*/
static inline void
zwp_idle_inhibit_manager_v1_destroy(struct zwp_idle_inhibit_manager_v1 *zwp_idle_inhibit_manager_v1)
{
wl_proxy_marshal_flags((struct wl_proxy *) zwp_idle_inhibit_manager_v1,
ZWP_IDLE_INHIBIT_MANAGER_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) zwp_idle_inhibit_manager_v1), WL_MARSHAL_FLAG_DESTROY);
}
/**
* @ingroup iface_zwp_idle_inhibit_manager_v1
*
* Create a new inhibitor object associated with the given surface.
*/
static inline struct zwp_idle_inhibitor_v1 *
zwp_idle_inhibit_manager_v1_create_inhibitor(struct zwp_idle_inhibit_manager_v1 *zwp_idle_inhibit_manager_v1, struct wl_surface *surface)
{
struct wl_proxy *id;
id = wl_proxy_marshal_flags((struct wl_proxy *) zwp_idle_inhibit_manager_v1,
ZWP_IDLE_INHIBIT_MANAGER_V1_CREATE_INHIBITOR, &zwp_idle_inhibitor_v1_interface, wl_proxy_get_version((struct wl_proxy *) zwp_idle_inhibit_manager_v1), 0, NULL, surface);
return (struct zwp_idle_inhibitor_v1 *) id;
}
#define ZWP_IDLE_INHIBITOR_V1_DESTROY 0
/**
* @ingroup iface_zwp_idle_inhibitor_v1
*/
#define ZWP_IDLE_INHIBITOR_V1_DESTROY_SINCE_VERSION 1
/** @ingroup iface_zwp_idle_inhibitor_v1 */
static inline void
zwp_idle_inhibitor_v1_set_user_data(struct zwp_idle_inhibitor_v1 *zwp_idle_inhibitor_v1, void *user_data)
{
wl_proxy_set_user_data((struct wl_proxy *) zwp_idle_inhibitor_v1, user_data);
}
/** @ingroup iface_zwp_idle_inhibitor_v1 */
static inline void *
zwp_idle_inhibitor_v1_get_user_data(struct zwp_idle_inhibitor_v1 *zwp_idle_inhibitor_v1)
{
return wl_proxy_get_user_data((struct wl_proxy *) zwp_idle_inhibitor_v1);
}
static inline uint32_t
zwp_idle_inhibitor_v1_get_version(struct zwp_idle_inhibitor_v1 *zwp_idle_inhibitor_v1)
{
return wl_proxy_get_version((struct wl_proxy *) zwp_idle_inhibitor_v1);
}
/**
* @ingroup iface_zwp_idle_inhibitor_v1
*
* Remove the inhibitor effect from the associated wl_surface.
*/
static inline void
zwp_idle_inhibitor_v1_destroy(struct zwp_idle_inhibitor_v1 *zwp_idle_inhibitor_v1)
{
wl_proxy_marshal_flags((struct wl_proxy *) zwp_idle_inhibitor_v1,
ZWP_IDLE_INHIBITOR_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) zwp_idle_inhibitor_v1), WL_MARSHAL_FLAG_DESTROY);
}
#ifdef __cplusplus
}
#endif
#endif

Some files were not shown because too many files have changed in this diff Show More