This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: **/.git/**, **/.github/**, **/node_modules/**, **/vendor/**, **/third_party/**, **/external/**, **/libs/**, **/lib/**, **/bin/**, **/obj/**, **/build/**, **/dist/**, **/target/**, **/out/**, **/release/**, **/debug/**, **/wwwroot/**, **/public/**, **/assets/**, **/static/**, **/[tT]est/**, **/[tT]ests/**, **/__tests__/**, **/[lL]ogs/**, **/[mM]igrations/**, **/.vs/**, **/.vscode/**, **/.idea/**, **/.pnpm-store/**, **/.yarn/**, **/.npm/**, **/__pycache__/**, **/.pytest_cache/**, **/.mypy_cache/**, **/.gradle/**, **/.mvn/**, **/coverage/**, **/.coverage/**, **/reports/**, **/report/**, **/TestResults/**, **/tmp/**, **/temp/**, **/.tmp/**, **/.cache/**, **/.history/**, **/.DS_Store, **/Thumbs.db, **/*.log, **/*.out, **/*.err, **/*.trace, **/*.trc, **/*.tmp, **/*.cache, **/*.dmp, **/*.dump, **/*.core, **/*.binlog, **/*.ndjson, **/*.jsonl, **/*.csv, **/*.evtx, **/*.etl, **/*.access, **/*.error, **/*.exe, **/*.dll, **/*.so, **/*.dylib, **/*.bin, **/*.app, **/*.msi, **/*.apk, **/*.ipa, **/*.lib, **/*.a, **/*.o, **/*.obj, **/*.lo, **/*.lai, **/*.class, **/*.jar, **/*.war, **/*.ear, **/*.pdb, **/*.idb, **/*.ilk, **/*.nupkg, **/*.snupkg, **/*.gem, **/*.whl, **/*.egg, **/*.deb, **/*.rpm, **/*.zip, **/*.tar, **/*.gz, **/*.tgz, **/*.rar, **/*.bz2, **/*.xz, **/*.7z, **/*.lz, **/*.lzma, **/*.min.js, **/*.min.css, **/*.map, **/*.css, **/*.scss, **/*.sass, **/*.less, **/*.jpg, **/*.jpeg, **/*.png, **/*.gif, **/*.bmp, **/*.tif, **/*.tiff, **/*.webp, **/*.heif, **/*.heic, **/*.svg, **/*.eps, **/*.ai, **/*.raw, **/*.cr2, **/*.cr3, **/*.nef, **/*.arw, **/*.dng, **/*.orf, **/*.rw2, **/*.avif, **/*.apng, **/*.ico, **/*.psd, **/*.psb, **/*.xcf, **/*.hdr, **/*.exr, **/*.dcm, **/*.dicom, **/*.fits, **/*.ppm, **/*.pgm, **/*.pbm, **/*.j2k, **/*.jp2, **/*.pcx, **/*.tga, **/*.iff, **/*.sgi, **/*.ras, **/*.coverage, **/*.lcov, **/*.gcov, **/*.gcda, **/*.gcno, **/*.generated, **/*.g.cs, **/*.designer.cs, **/*.lock, **/*.lock.json, **/*.eot, **/*.ttf, **/*.woff, **/*.woff2, **/*.pfx, **/*.p12, **/*.cer, **/*.crt, **/*.key, **/*.editorconfig, **/*.tool-versions, **/*.onnx, **/*.pt, **/*.pth, **/*.h5, **/*.ckpt, **/*.sln, **/*.csproj, **/*.config, **/*.user, **/*.vsidx, **/*.v2, **/*.db*, **/.*ignore, **/.git*, **/*.config.*, dist/**, pkg/**, example/**, **/CMakeLists.txt, **/*.cmake, **/*.bzl, **/BUILD, **/BUILD.bazel, **/*.gradle, **/pom.xml, **/*.pbxproj, **/*.xcodeproj/**, **/*.xcworkspace/**, **/*.xcshareddata/**, **/*.xcscheme/**, **/*.xcworkspacedata, **/*.xcassets/**, **/*.plist, **/*.png, **/*.jpg, **/*.ico, **/*.pdf, **/*.ttf, **/*.otf, **/*.xib, **/*.lock, **/.gitignore, **/.gitattributes, **/.gitmodules, **/.editorconfig, **/.clang-format, **/.prettierignore, **/.envrc, **/*.rc, **/*.zshenv, **/*.bash, **/*.sh, **/gen/**, **/generated/**, **/auto/**, **/out/**, **/*.pdl, **/*.cddl, **/*.thrift, **/*.proto, **/*.avsc, **/*.smithy, **/*.nix, **/*.toml, **/*.yaml, **/*.yml
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Code comments have been removed from supported file types
- Empty lines have been removed from all files
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<directory_structure>
.agents/
  commands/
    review-branch
  skills/
    writing-commit-messages/
      SKILL.md
flatpak/
  exceptions.json
  zig-packages.json
images/
  Ghostty.icon/
    icon.json
include/
  ghostty/
    vt/
      key/
        encoder.h
        event.h
      mouse/
        encoder.h
        event.h
      allocator.h
      build_info.h
      color_scheme.h
      color.h
      device.h
      focus.h
      formatter.h
      grid_ref_tracked.h
      grid_ref.h
      io.h
      key.h
      kitty_graphics.h
      modes.h
      mouse.h
      osc.h
      paste.h
      point.h
      render.h
      screen.h
      search.h
      selection.h
      sgr.h
      size_report.h
      snapshot.h
      style.h
      sys.h
      terminal.h
      types.h
      unicode.h
      wasm.h
    vt.h
  ghostty.h
  module.modulemap
macos/
  GhosttyUITests/
    AppKitExtensions.swift
    GhosttyCommandPaletteTests.swift
    GhosttyCustomConfigCase.swift
    GhosttyMouseStateTests.swift
    GhosttyThemeTests.swift
    GhosttyTitlebarTabsUITests.swift
    GhosttyTitleUITests.swift
    GhosttyWindowPositionUITests.swift
  Sources/
    App/
      AppDelegate.swift
      AppDelegate+Ghostty.swift
      CommandLineOpenFileFilter.swift
      ghostty-bridging-header.h
      main.swift
    Features/
      About/
        AboutController.swift
        AboutView.swift
        AboutViewModel.swift
        CyclingIconView.swift
      App Intents/
        Entities/
          CommandEntity.swift
          TerminalEntity.swift
        CloseTerminalIntent.swift
        CommandPaletteIntent.swift
        FocusTerminalIntent.swift
        GetTerminalDetailsIntent.swift
        GhosttyIntentError.swift
        InputIntent.swift
        IntentPermission.swift
        KeybindIntent.swift
        NewTerminalIntent.swift
        QuickTerminalIntent.swift
      AppleScript/
        AppDelegate+AppleScript.swift
        Ghostty.Input.Mods+AppleScript.swift
        ScriptInputTextCommand.swift
        ScriptKeyEventCommand.swift
        ScriptMouseButtonCommand.swift
        ScriptMousePosCommand.swift
        ScriptMouseScrollCommand.swift
        ScriptRecord.swift
        ScriptSurfaceConfiguration.swift
        ScriptTab.swift
        ScriptTerminal.swift
        ScriptWindow.swift
      ClipboardConfirmation/
        ClipboardConfirmationController.swift
        ClipboardConfirmationView.swift
      Command Palette/
        CommandPalette.swift
        TerminalCommandPalette.swift
      Custom App Icon/
        Extensions/
          Notification+AppIcon.swift
          UserDefaults+AppIcon.swift
        AppIcon.swift
        ColorizedGhosttyIcon.swift
        ColorizedGhosttyIconImage.swift
        ColorizedGhosttyIconView.swift
        DockTilePlugin.swift
      Global Keybinds/
        GlobalEventTap.swift
      QuickTerminal/
        QuickTerminalController.swift
        QuickTerminalPosition.swift
        QuickTerminalRestorableState.swift
        QuickTerminalScreen.swift
        QuickTerminalScreenStateCache.swift
        QuickTerminalSize.swift
        QuickTerminalSpaceBehavior.swift
        QuickTerminalWindow.swift
      Secure Input/
        SecureInput.swift
        SecureInputOverlay.swift
      Services/
        ServiceProvider.swift
      Settings/
        ConfigurationErrorsController.swift
        ConfigurationErrorsView.swift
        SettingsView.swift
      Splits/
        SplitTree.swift
        SplitView.Divider.swift
        SplitView.swift
        TerminalSplitTreeView.swift
      Terminal/
        Window Styles/
          HiddenTitlebarTerminalWindow.swift
          TerminalWindow.swift
          TitlebarTabsTahoeTerminalWindow.swift
          TitlebarTabsVenturaTerminalWindow.swift
          TransparentTitlebarTerminalWindow.swift
        BaseTerminalController.swift
        ErrorView.swift
        TerminalController.swift
        TerminalRestorable.swift
        TerminalRestorableState+InteralState.swift
        TerminalTabColor.swift
        TerminalView.swift
        TerminalViewContainer.swift
      Update/
        UpdateBadge.swift
        UpdateController.swift
        UpdateDelegate.swift
        UpdateDriver.swift
        UpdatePill.swift
        UpdatePopoverView.swift
        UpdateSimulator.swift
        UpdateViewModel.swift
    Ghostty/
      Surface View/
        ChildExitedMessageBar.swift
        InspectorView.swift
        OSSurfaceView.swift
        SurfaceDragSource.swift
        SurfaceGrabHandle.swift
        SurfaceProgressBar.swift
        SurfaceScrollView.swift
        SurfaceView_AppKit.swift
        SurfaceView.swift
        SurfaceView+Image.swift
        SurfaceView+Transferable.swift
      FullscreenMode+Extension.swift
      Ghostty.Action.swift
      Ghostty.App.swift
      Ghostty.ChildExitedMessage.swift
      Ghostty.ClipboardConfirmationRequest.swift
      Ghostty.Command.swift
      Ghostty.Config.swift
      Ghostty.ConfigTypes.swift
      Ghostty.Error.swift
      Ghostty.Event.swift
      Ghostty.Input.swift
      Ghostty.Inspector.swift
      Ghostty.MenuShortcutManager.swift
      Ghostty.Shell.swift
      Ghostty.Surface.swift
      GhosttyDelegate.swift
      GhosttyPackage.swift
      GhosttyPackageMeta.swift
      NSEvent+Extension.swift
    Helpers/
      Extensions/
        Array+Extension.swift
        Double+Extension.swift
        Duration+Extension.swift
        EventModifiers+Extension.swift
        FileHandle+Extension.swift
        KeyboardShortcut+Extension.swift
        NSAlert+Extension.swift
        NSAppearance+Extension.swift
        NSAppleEventDescriptor+Extension.swift
        NSApplication+Extension.swift
        NSColor+Extension.swift
        NSImage+Extension.swift
        NSMenu+Extension.swift
        NSMenuItem+Extension.swift
        NSPasteboard+Extension.swift
        NSScreen+Extension.swift
        NSView+Extension.swift
        NSWindow+Extension.swift
        NSWorkspace+Extension.swift
        ObjectIdentifier+Extension.swift
        Optional+Extension.swift
        OSColor+Extension.swift
        OSPasteboard+Extension.swift
        String+Extension.swift
        Transferable+Extension.swift
        UndoManager+Extension.swift
        URL+Extension.swift
        UserDefaults+Extension.swift
        UUID+Extension.swift
        View+Extension.swift
      Private/
        CGS.swift
        Dock.swift
      AppInfo.swift
      Backport.swift
      CodableBridge.swift
      Cursor.swift
      ExpiringUndoManager.swift
      Fullscreen.swift
      KeyboardLayout.swift
      LastWindowPosition.swift
      MetalView.swift
      NonDraggableHostingView.swift
      ObjCExceptionCatcher.h
      ObjCExceptionCatcher.m
      PermissionRequest.swift
      TabGroupCloseCoordinator.swift
      TabTitleEditor.swift
      UntrustedURL.swift
      UntrustedURLAlert.swift
      URLHoverBanner.swift
      VibrantLayer.h
      VibrantLayer.m
      Weak.swift
  AGENTS.md
  build.nu
  Ghostty.entitlements
  Ghostty.sdef
  Ghostty.xctestplan
  GhosttyDebug.entitlements
  GhosttyReleaseLocal.entitlements
nix/
  build-support/
    update-mirror.nu
  test-src/
    test_libghostty_vt.c
po/
  be.po
  bg.po
  ca.po
  com.mitchellh.ghostty.pot
  da.po
  de.po
  es_AR.po
  es_BO.po
  es_ES.po
  eu.po
  fr.po
  ga.po
  he.po
  hr.po
  hu.po
  id.po
  it.po
  ja.po
  kk.po
  ko_KR.po
  lt.po
  lv.po
  mk.po
  nb.po
  nl.po
  pl.po
  pt_BR.po
  README_CONTRIBUTORS.md
  README_TRANSLATORS.md
  ru.po
  sr.po
  sr@latin.po
  tr.po
  uk.po
  vi.po
  zh_CN.po
  zh_TW.po
snap/
  local/
    launcher
src/
  apprt/
    gtk/
      class/
        application.zig
        clipboard_confirmation_dialog.zig
        close_confirmation_dialog.zig
        command_palette.zig
        config_errors_dialog.zig
        config.zig
        debug_warning.zig
        dialog.zig
        global_shortcuts.zig
        imgui_widget.zig
        inspector_widget.zig
        inspector_window.zig
        key_state_overlay.zig
        Overrides.zig
        render_surface.zig
        resize_overlay.zig
        search_overlay.zig
        split_tree.zig
        surface_child_exited.zig
        surface_scrolled_window.zig
        surface.zig
        tab.zig
        title_dialog.zig
        window.zig
      ext/
        actions.zig
        slice.zig
      ipc/
        DBus.zig
        new_tab.zig
        new_window.zig
        toggle_quick_terminal.zig
      portal/
        OpenURI.zig
      ui/
        1.0/
          clipboard-confirmation-dialog.blp
        1.2/
          close-confirmation-dialog.blp
          config-errors-dialog.blp
          debug-warning.blp
          key-state-overlay.blp
          resize-overlay.blp
          search-overlay.blp
          surface.blp
        1.3/
          debug-warning.blp
          surface-child-exited.blp
        1.4/
          clipboard-confirmation-dialog.blp
        1.5/
          command-palette.blp
          imgui-widget.blp
          inspector-widget.blp
          inspector-window.blp
          split-tree-split.blp
          split-tree.blp
          surface-scrolled-window.blp
          tab.blp
          title-dialog.blp
          window.blp
      winproto/
        wayland/
          protocols/
            vicinae-hotkey-v1.xml
          Globals.zig
          Hotkeys.zig
        BlurRegion.zig
        noop.zig
        wayland.zig
        x11.zig
      adw_version.zig
      App.zig
      cgroup.zig
      class.zig
      ext.zig
      flatpak.zig
      gsettings.zig
      gtk_version.zig
      key.zig
      media.zig
      portal.zig
      post_fork.zig
      pre_exec.zig
      scale.zig
      Surface.zig
      weak_ref.zig
      winproto.zig
    action.zig
    browser.zig
    embedded.zig
    gtk.zig
    ipc.zig
    none.zig
    runtime.zig
    structs.zig
    surface.zig
  benchmark/
    AGENTS.md
    ApcParser.zig
    Benchmark.zig
    CApi.zig
    cli.zig
    CodepointWidth.zig
    GraphemeBreak.zig
    HyperlinkMap.zig
    IsSymbol.zig
    main.zig
    options.zig
    OscParser.zig
    PageCompression.zig
    ScreenClone.zig
    ScrollbackCompression.zig
    TerminalFormatter.zig
    TerminalParser.zig
    TerminalResize.zig
    TerminalSnapshot.zig
    TerminalStream.zig
  cli/
    ssh-cache/
      DiskCache.zig
      Entry.zig
    action.zig
    args.zig
    boo.zig
    CommaSplitter.zig
    crash_report.zig
    diagnostics.zig
    edit_config.zig
    explain_config.zig
    ghostty.zig
    help.zig
    list_actions.zig
    list_colors.zig
    list_fonts.zig
    list_keybinds.zig
    list_themes.zig
    lorem_ipsum.txt
    new_tab.zig
    new_window.zig
    Pager.zig
    README.md
    show_config.zig
    show_face.zig
    ssh_cache.zig
    ssh.zig
    toggle_quick_terminal.zig
    tui.zig
    validate_config.zig
    version.zig
  config/
    testdata/
      theme_dark
      theme_light
      theme_simple
    c_get.zig
    CApi.zig
    ClipboardCodepointMap.zig
    command.zig
    conditional.zig
    config-template
    Config.zig
    edit.zig
    ErrorList.zig
    file_load.zig
    formatter_file.zig
    formatter.zig
    io.zig
    key.zig
    limit.zig
    path.zig
    RepeatableStringMap.zig
    string.zig
    theme.zig
    url.zig
    Wasm.zig
  crash/
    dir.zig
    main.zig
    sentry_envelope.zig
    sentry.zig
  datastruct/
    blocking_queue.zig
    cache_table.zig
    circ_buf.zig
    comparison.zig
    comptime_int_set.zig
    intrusive_linked_list.zig
    limited_allocator.zig
    main.zig
    message_data.zig
    segmented_list.zig
    split_tree.zig
    untouched_pool.zig
    wasm_page_pool.zig
  extra/
    bash.zig
    fish.zig
    sublime.zig
    vim.zig
    zsh.zig
  font/
    face/
      coretext.zig
      freetype.zig
      web_canvas.zig
    opentype/
      glyf.zig
      head.zig
      hhea.zig
      os2.zig
      post.zig
      sfnt.zig
      svg.zig
    res/
      BSD-2-Clause.txt
      MIT.txt
      OFL.txt
      README.md
      spleen-8x16.bdf
      spleen-8x16.otb
      spleen-8x16.pcf
    shaper/
      testdata/
        arabic.txt
      Cache.zig
      coretext.zig
      feature.zig
      harfbuzz.zig
      noop.zig
      run.zig
      web_canvas.zig
    sprite/
      draw/
        block.zig
        box.zig
        braille.zig
        branch.zig
        common.zig
        geometric_shapes.zig
        octants.txt
        powerline.zig
        README.md
        special.zig
        symbols_for_legacy_computing_supplement.zig
        symbols_for_legacy_computing.zig
      canvas.zig
      Face.zig
    Atlas.zig
    backend.zig
    CodepointMap.zig
    CodepointResolver.zig
    Collection.zig
    DeferredFace.zig
    discovery.zig
    embedded.zig
    face.zig
    glyf_rasterize_png_test.zig
    glyf_rasterize.zig
    Glyph.zig
    library.zig
    main.zig
    Metrics.zig
    nerd_font_attributes.zig
    nerd_font_codegen.py
    nerd_font_codepoint_tables.py
    nerd_font_tables.zig
    opentype.zig
    shape.zig
    SharedGrid.zig
    SharedGridSet.zig
    sprite.zig
  input/
    Binding.zig
    command.zig
    config.zig
    function_keys.zig
    helpgen_actions.zig
    key_encode.zig
    key_mods.zig
    key.zig
    keyboard.zig
    keycodes.zig
    KeymapDarwin.zig
    KeymapNoop.zig
    kitty.zig
    Link.zig
    mouse_encode.zig
    mouse.zig
    paste.zig
  inspector/
    widgets/
      key.zig
      page.zig
      pagelist.zig
      renderer.zig
      screen.zig
      style.zig
      surface.zig
      terminal.zig
      termio.zig
    AGENTS.md
    Inspector.zig
    main.zig
    units.zig
    widgets.zig
  os/
    wasm/
      log.zig
      target.zig
    cf_release_thread.zig
    cgroup.zig
    dbus.zig
    desktop.zig
    edit.zig
    file.zig
    flatpak.zig
    homedir.zig
    hostname.zig
    i18n_locales.zig
    i18n.zig
    kernel_info.zig
    locale.c
    locale.zig
    mach.zig
    macos.zig
    main.zig
    mouse.zig
    open.zig
    passwd.zig
    path.zig
    pipe.zig
    resourcesdir.zig
    shell.zig
    stderr.zig
    string_encoding.zig
    systemd.zig
    TempDir.zig
    uri.zig
    wasm.zig
    windows.zig
    xdg.zig
  renderer/
    metal/
      api.zig
      buffer.zig
      Device.zig
      Frame.zig
      IOSurfaceLayer.zig
      Pipeline.zig
      RenderPass.zig
      Sampler.zig
      shaders.zig
      Target.zig
      Texture.zig
    opengl/
      buffer.zig
      Device.zig
      Frame.zig
      Pipeline.zig
      RenderPass.zig
      Sampler.zig
      shaders.zig
      Target.zig
      Texture.zig
    shaders/
      glsl/
        bg_color.f.glsl
        bg_image.f.glsl
        bg_image.v.glsl
        cell_bg.f.glsl
        cell_text.f.glsl
        cell_text.v.glsl
        common.glsl
        full_screen.v.glsl
        image.f.glsl
        image.v.glsl
      shaders.metal
      shadertoy_prefix.glsl
      test_shadertoy_crt.glsl
      test_shadertoy_focus.glsl
      test_shadertoy_invalid.glsl
    backend.zig
    cell.zig
    cursor.zig
    Dmabuf.zig
    generic.zig
    image.zig
    link.zig
    message.zig
    Metal.zig
    OpenGL.zig
    Options.zig
    Overlay.zig
    row.zig
    shadertoy.zig
    size.zig
    State.zig
    Thread.zig
  shell-integration/
    fish/
      vendor_conf.d/
        ghostty-shell-integration.fish
    zsh/
      ghostty-integration
    README.md
  simd/
    base64_scalar.zig
    base64.cpp
    base64.zig
    codepoint_width.cpp
    codepoint_width.zig
    index_of.cpp
    index_of.h
    index_of.zig
    main.zig
    vt.cpp
    vt.h
    vt.zig
  stb/
    main.zig
    stb_image_resize.h
    stb_image.h
    stb.c
  synthetic/
    cli/
      Ascii.zig
      Kitty.zig
      Osc.zig
      Styled.zig
      Utf8.zig
    Bytes.zig
    cli.zig
    Generator.zig
    Kitty.zig
    main.zig
    Osc.zig
    Utf8.zig
  terminal/
    apc/
      glyph/
        AGENTS.md
        execute.zig
        Glossary.zig
        request.zig
        response.zig
      glyph.zig
    c/
      AGENTS.md
      allocator.zig
      build_info.zig
      cell.zig
      color_scheme.zig
      color.zig
      focus.zig
      formatter.zig
      grid_ref_tracked.zig
      grid_ref.zig
      io.zig
      key_encode.zig
      key_event.zig
      kitty_graphics.zig
      main.zig
      modes.zig
      mouse_encode.zig
      mouse_event.zig
      osc.zig
      paste.zig
      render.zig
      result.zig
      row.zig
      search.zig
      selection_gesture.zig
      selection.zig
      sgr.zig
      size_report.zig
      snapshot.zig
      style.zig
      sys.zig
      terminal.zig
      types-schema-verify.py
      types.schema.json
      types.zig
      unicode.zig
    compress/
      AGENTS.md
      lz4_differential.zig
      lz4.zig
      Page.zig
    kitty/
      testdata/
        image-png-none-50x76-2147483647-raw.data
        image-png-zlib_deflate-50x76-2147483647-raw.data
        image-rgb-none-20x15-2147483647-raw.data
        image-rgb-zlib_deflate-128x96-2147483647-raw.data
      clipboard_command.zig
      clipboard_grants.zig
      clipboard_response.zig
      clipboard_write.zig
      clipboard.zig
      color.zig
      dnd_command.zig
      dnd_drop.zig
      dnd_response.zig
      dnd_test.zig
      dnd.zig
      graphics_animation.zig
      graphics_command.zig
      graphics_exec.zig
      graphics_image.zig
      graphics_pixel.zig
      graphics_render.zig
      graphics_storage.zig
      graphics_unicode.zig
      graphics.zig
      key.zig
      windows.zig
    osc/
      parsers/
        change_window_icon.zig
        change_window_title.zig
        clipboard_operation.zig
        color.zig
        context_signal.zig
        hyperlink.zig
        iterm2.zig
        kitty_clipboard_protocol.zig
        kitty_color.zig
        kitty_desktop_notification.zig
        kitty_dnd_protocol.zig
        kitty_text_sizing.zig
        mouse_shape.zig
        osc9.zig
        report_pwd.zig
        rxvt_extension.zig
        semantic_prompt.zig
        unknown.zig
      encoding.zig
      kitty_metadata.zig
      parsers.zig
    res/
      glitch.txt
      rgb.txt
    search/
      active.zig
      pagelist.zig
      screen.zig
      sliding_window.zig
      terminal.zig
      Thread.zig
      viewport.zig
    snapshot/
      testdata/
        checkpoint-ready-v1.hex
        complete-v1.hex
        continuation-apc-v1.hex
        continuation-csi-v1.hex
        continuation-dcs-v1.hex
        continuation-esc-v1.hex
        continuation-ground-v1.hex
        continuation-osc-v1.hex
        continuation-utf8-v1.hex
        envelope-v1.hex
        grid-v1.hex
        history-header-v1.hex
        hyperlink-explicit-v1.hex
        hyperlink-implicit-v1.hex
        page-empty-record-v1.hex
        page-header-v1.hex
        page-v1.hex
        record-page-header-v1.hex
        screen-header-v1.hex
        screen-saved-cursor-v1.hex
        style-v1.hex
        terminal-header-v1.hex
      AGENTS.md
      checkpoint.zig
      continuation.zig
      envelope.zig
      fixture.zig
      grid.zig
      history.zig
      hyperlink.zig
      io.zig
      main.zig
      page.zig
      record.zig
      screen.zig
      snapshot.ksy
      snapshot.zig
      style.zig
      terminal.zig
      verify-kaitai.py
    tmux/
      control.zig
      layout.zig
      output.zig
      viewer.zig
    ansi.zig
    apc.zig
    bitmap_allocator.zig
    build_options.zig
    charsets.zig
    clipboard.zig
    color.zig
    compress.zig
    csi.zig
    cursor.zig
    dcs.zig
    device_attributes.zig
    device_status.zig
    focus.zig
    formatter.zig
    fraction.zig
    hash_map.zig
    highlight.zig
    hyperlink.zig
    kitty.zig
    lib.zig
    main.zig
    mem.zig
    modes.zig
    mouse.zig
    osc.zig
    page.zig
    PageList.zig
    parse_table.zig
    Parser.zig
    paste.zig
    point.zig
    ref_counted_set.zig
    render.zig
    Screen.zig
    ScreenSet.zig
    search.zig
    selection_codepoints.zig
    Selection.zig
    SelectionGesture.zig
    sgr.zig
    size_report.zig
    size.zig
    stream_continuation.zig
    stream_terminal.zig
    stream.zig
    StringMap.zig
    style.zig
    sys.zig
    Tabstops.zig
    Terminal.zig
    tmux.zig
    UTF8Decoder.zig
    x11_color.zig
    xt_checksum.zig
  terminfo/
    ghostty.zig
    main.zig
    Source.zig
  termio/
    backend.zig
    Exec.zig
    mailbox.zig
    message.zig
    Options.zig
    shell_integration.zig
    stream_handler.zig
    Termio.zig
    Thread.zig
  unicode/
    grapheme.zig
    lut.zig
    main.zig
    props_table.zig
    props_uucode.zig
    props.zig
    symbols_table.zig
    symbols_uucode.zig
  App.zig
  apprt.zig
  build_config.zig
  cli.zig
  Command.zig
  config.zig
  crc32c.zig
  fastmem.zig
  fastprint.zig
  file_type.zig
  global.zig
  helpgen.zig
  input.zig
  lib_vt.zig
  main_bench.zig
  main_build_data.zig
  main_c.zig
  main_gen.zig
  main_ghostty.zig
  main_wasm.zig
  main.zig
  math.zig
  pty.c
  pty.zig
  quirks_memset.zig
  quirks.zig
  renderer.zig
  surface_mouse.zig
  Surface.zig
  termio.zig
  tripwire.zig
.mailmap
.shellcheckrc
AGENTS.md
AI_POLICY.md
build.zig
build.zig.zon
build.zig.zon.json
build.zig.zon.txt
CODEOWNERS
CONTRIBUTING.md
Doxyfile
DoxygenLayout.xml
HACKING.md
LICENSE
Makefile
PACKAGING.md
passthrough.glsl
README.md
valgrind.supp
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path=".agents/commands/review-branch">
#!/usr/bin/env nu

# A command to review the changes made in the current Git branch.
#
# IMPORTANT: This command is prompted to NOT write any code and to ONLY
# produce a review summary. You should still be vigilant when running this
# but that is the expected behavior.
#
# The optional `<issue>` parameter can be an issue number, PR number,
# or a full GitHub URL to provide additional context.
def main [
  issue?: any, # Optional GitHub issue/PR number or URL for context
] {
  let issueContext = if $issue != null {
    let data = gh issue view $issue --json author,title,number,body,comments | from json
    let comments = if ($data.comments? != null) {
      $data.comments | each { |comment|
        let author = if ($comment.author?.login? != null) { $comment.author.login } else { "unknown" }
        $"
### Comment by ($author)
($comment.body)
" | str trim
      } | str join "\n\n"
    } else {
      ""
    }

    $"
## Source Issue: ($data.title) \(#($data.number)\)

... (46 lines truncated)
</file>

<file path=".agents/skills/writing-commit-messages/SKILL.md">
---
name: writing-commit-messages
description: >-
  Writes Git commit messages. Activates when the user asks to write
  a commit message, draft a commit message, or similar.
---

# Writing Commit Messages

Write commit messages that follow commit style guidelines for the project.

## Format

```
<subsystem>: <summary>

<reference issues/PRs/etc.>

<long form description>
```

## Rules

### Subject line

- **Subsystem prefix**: Use a short, lowercase identifier for the
  area of code changed (e.g., `terminal`, `vt`, `lib`, `config`,
  `font`). Determine this from the file paths in the diff. If
  changes span the macOS app, use `macos`. For GTK, use `gtk`. For
  build system, use `build`. Use nested subsystems with `/` when
... (33 lines truncated)
</file>

<file path="flatpak/exceptions.json">
{
  "com.mitchellh.ghostty": ["finish-args-flatpak-spawn-access"]
}
</file>

<file path="flatpak/zig-packages.json">
[
  {
    "type": "archive",
    "url": "https://github.com/vancluever/arocc/archive/f97cdfc3779aec4b242299e2fc9a1c828c3547c6.tar.gz",
    "dest": "vendor/p/aro-0.0.0-JSD1Qk6lNgDdcDV4Vh7Sfy-34m2TluIVOdPzMmj_0BjX",
    "sha256": "42c8cab9135b12518e6af7dc5e461f055c78b863adca8ed7774f2fb7fe9a7784"
  },
  {
    "type": "archive",
    "url": "https://deps.files.ghostty.org/DearBindings_v0.17_ImGui_v1.92.5-docking.tar.gz",
    "dest": "vendor/p/N-V-__8AANT61wB--nJ95Gj_ctmzAtcjloZ__hRqNw5lC1Kr",
    "sha256": "8bfec500e00926f679853ee23d67cc392d3c3181733ca4704738651d3f70baa3"
  },
  {
    "type": "archive",
    "url": "https://deps.files.ghostty.org/breakpad-b99f444ba5f6b98cac261cbb391d8766b34a5918.tar.gz",
    "dest": "vendor/p/N-V-__8AALw2uwF_03u4JRkZwRLc3Y9hakkYV7NKRR9-RIZJ",
    "sha256": "6cca98943d1a990766cef61077c09aff5938063fe17a1efe1228e5412b6d6ad9"
  },
  {
    "type": "archive",
    "url": "https://gitlab.freedesktop.org/api/v4/projects/890/packages/generic/fontconfig/2.18.3/fontconfig-2.18.3.tar.xz",
    "dest": "vendor/p/N-V-__8AAOgqbADacob-q2_DMQlmgaG4xKHRuW-6PJ4oJzMZ",
    "sha256": "4f7b554a38cdf78c033f666c8871f3749e14a094f65a07f630c91ed0b43d35e3"
  },
  {
    "type": "archive",
    "url": "https://deps.files.ghostty.org/freetype-1220b81f6ecfb3fd222f76cf9106fecfa6554ab07ec7fdc4124b9bb063ae2adf969d.tar.gz",
    "dest": "vendor/p/N-V-__8AAKLKpwC4H27Ps_0iL3bPkQb-z6ZVSrB-x_3EEkub",
    "sha256": "427201f5d5151670d05c1f5b45bef5dda1f2e7dd971ef54f0feaaa7ffd2ab90c"
... (207 lines truncated)
</file>

<file path="images/Ghostty.icon/icon.json">
{
  "color-space-for-untagged-svg-colors" : "display-p3",
  "fill" : {
    "linear-gradient" : [
      "display-p3:0.87945,0.87945,0.87945,1.00000",
      "display-p3:0.40000,0.40000,0.40392,1.00000"
    ]
  },
  "groups" : [
    {
      "blend-mode" : "normal",
      "layers" : [
        {
          "blend-mode" : "overlay",
          "fill" : {
            "linear-gradient" : [
              "srgb:1.00000,1.00000,1.00000,1.00000",
              "srgb:0.00000,0.00000,0.00000,1.00000"
            ]
          },
          "glass" : false,
          "hidden" : false,
          "image-name" : "gloss.png",
          "name" : "GlossTop",
          "opacity" : 0.25,
          "position" : {
            "scale" : 0.98,
            "translation-in-points" : [
              0.90625,
              -236.4609375
... (146 lines truncated)
</file>

<file path="include/ghostty/vt/key/encoder.h">
typedef uint8_t GhosttyKittyKeyFlags;
⋮----
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyOptionAsAlt;
⋮----
} GhosttyKeyEncoderOption;
⋮----
GHOSTTY_API GhosttyResult ghostty_key_encoder_new(const GhosttyAllocator *allocator, GhosttyKeyEncoder *encoder);
⋮----
GHOSTTY_API void ghostty_key_encoder_free(GhosttyKeyEncoder encoder);
⋮----
GHOSTTY_API void ghostty_key_encoder_setopt(GhosttyKeyEncoder encoder, GhosttyKeyEncoderOption option, const void *value);
⋮----
GHOSTTY_API void ghostty_key_encoder_setopt_from_terminal(GhosttyKeyEncoder encoder, GhosttyTerminal terminal);
⋮----
GHOSTTY_API GhosttyResult ghostty_key_encoder_encode(GhosttyKeyEncoder encoder, GhosttyKeyEvent event, char *out_buf, size_t out_buf_size, size_t *out_len);
</file>

<file path="include/ghostty/vt/key/event.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyKeyAction;
⋮----
typedef uint16_t GhosttyMods;
⋮----
} GhosttyKey;
⋮----
GHOSTTY_API GhosttyResult ghostty_key_event_new(const GhosttyAllocator *allocator, GhosttyKeyEvent *event);
⋮----
GHOSTTY_API void ghostty_key_event_free(GhosttyKeyEvent event);
⋮----
GHOSTTY_API void ghostty_key_event_set_action(GhosttyKeyEvent event, GhosttyKeyAction action);
⋮----
GHOSTTY_API GhosttyKeyAction ghostty_key_event_get_action(GhosttyKeyEvent event);
⋮----
GHOSTTY_API void ghostty_key_event_set_key(GhosttyKeyEvent event, GhosttyKey key);
⋮----
GHOSTTY_API GhosttyKey ghostty_key_event_get_key(GhosttyKeyEvent event);
⋮----
GHOSTTY_API void ghostty_key_event_set_mods(GhosttyKeyEvent event, GhosttyMods mods);
⋮----
GHOSTTY_API GhosttyMods ghostty_key_event_get_mods(GhosttyKeyEvent event);
⋮----
GHOSTTY_API void ghostty_key_event_set_consumed_mods(GhosttyKeyEvent event, GhosttyMods consumed_mods);
⋮----
GHOSTTY_API GhosttyMods ghostty_key_event_get_consumed_mods(GhosttyKeyEvent event);
⋮----
GHOSTTY_API void ghostty_key_event_set_composing(GhosttyKeyEvent event, bool composing);
⋮----
... (10 lines truncated)
</file>

<file path="include/ghostty/vt/mouse/encoder.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyMouseTrackingMode;
⋮----
} GhosttyMouseFormat;
⋮----
} GhosttyMouseEncoderSize;
⋮----
} GhosttyMouseEncoderOption;
⋮----
GHOSTTY_API GhosttyResult ghostty_mouse_encoder_new(const GhosttyAllocator *allocator,
⋮----
GHOSTTY_API void ghostty_mouse_encoder_free(GhosttyMouseEncoder encoder);
⋮----
GHOSTTY_API void ghostty_mouse_encoder_setopt(GhosttyMouseEncoder encoder,
⋮----
GHOSTTY_API void ghostty_mouse_encoder_setopt_from_terminal(GhosttyMouseEncoder encoder,
⋮----
GHOSTTY_API void ghostty_mouse_encoder_reset(GhosttyMouseEncoder encoder);
⋮----
GHOSTTY_API GhosttyResult ghostty_mouse_encoder_encode(GhosttyMouseEncoder encoder,
</file>

<file path="include/ghostty/vt/mouse/event.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyMouseAction;
⋮----
} GhosttyMouseButton;
⋮----
} GhosttyMousePosition;
⋮----
GHOSTTY_API GhosttyResult ghostty_mouse_event_new(const GhosttyAllocator *allocator,
⋮----
GHOSTTY_API void ghostty_mouse_event_free(GhosttyMouseEvent event);
⋮----
GHOSTTY_API void ghostty_mouse_event_set_action(GhosttyMouseEvent event,
⋮----
GHOSTTY_API GhosttyMouseAction ghostty_mouse_event_get_action(GhosttyMouseEvent event);
⋮----
GHOSTTY_API void ghostty_mouse_event_set_button(GhosttyMouseEvent event,
⋮----
GHOSTTY_API void ghostty_mouse_event_clear_button(GhosttyMouseEvent event);
⋮----
GHOSTTY_API bool ghostty_mouse_event_get_button(GhosttyMouseEvent event,
⋮----
GHOSTTY_API void ghostty_mouse_event_set_mods(GhosttyMouseEvent event,
⋮----
GHOSTTY_API GhosttyMods ghostty_mouse_event_get_mods(GhosttyMouseEvent event);
⋮----
GHOSTTY_API void ghostty_mouse_event_set_position(GhosttyMouseEvent event,
⋮----
GHOSTTY_API GhosttyMousePosition ghostty_mouse_event_get_position(GhosttyMouseEvent event);
</file>

<file path="include/ghostty/vt/allocator.h">
} GhosttyAllocatorVtable;
⋮----
typedef struct GhosttyAllocator {
⋮----
} GhosttyAllocator;
⋮----
GHOSTTY_API uint8_t* ghostty_alloc(const GhosttyAllocator* allocator, size_t len);
⋮----
GHOSTTY_API void ghostty_free(const GhosttyAllocator* allocator, uint8_t* ptr, size_t len);
</file>

<file path="include/ghostty/vt/build_info.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyOptimizeMode;
⋮----
} GhosttyBuildInfo;
⋮----
GHOSTTY_API GhosttyResult ghostty_build_info(GhosttyBuildInfo data, void *out);
</file>

<file path="include/ghostty/vt/color_scheme.h">
GHOSTTY_API GhosttyResult ghostty_color_scheme_report_encode(
</file>

<file path="include/ghostty/vt/color.h">
} GhosttyColorRgb;
⋮----
typedef uint8_t GhosttyColorPaletteIndex;
⋮----
} GhosttyColorPaletteMask;
⋮----
} GhosttyColorX11Entry;
⋮----
GHOSTTY_API void ghostty_color_rgb_get(const GhosttyColorRgb* color,
⋮----
GHOSTTY_API GhosttyResult ghostty_color_parse_x11(
⋮----
GHOSTTY_API GhosttyResult ghostty_color_parse(
⋮----
GHOSTTY_API GhosttyResult ghostty_color_parse_palette_entry(
⋮----
GHOSTTY_API void ghostty_color_palette_default(GhosttyColorRgb* out);
⋮----
GHOSTTY_API void ghostty_color_palette_generate(
⋮----
GHOSTTY_API double ghostty_color_luminance(const GhosttyColorRgb* color);
⋮----
GHOSTTY_API double ghostty_color_perceived_luminance(const GhosttyColorRgb* color);
⋮----
GHOSTTY_API double ghostty_color_contrast(const GhosttyColorRgb* a,
</file>

<file path="include/ghostty/vt/device.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyColorScheme;
⋮----
} GhosttyDeviceAttributesPrimary;
⋮----
} GhosttyDeviceAttributesSecondary;
⋮----
} GhosttyDeviceAttributesTertiary;
⋮----
} GhosttyDeviceAttributes;
</file>

<file path="include/ghostty/vt/focus.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyFocusEvent;
⋮----
GHOSTTY_API GhosttyResult ghostty_focus_encode(
</file>

<file path="include/ghostty/vt/formatter.h">
} GhosttyFormatterScreenExtra;
⋮----
} GhosttyFormatterTerminalExtra;
⋮----
} GhosttyFormatterTerminalOptions;
⋮----
GHOSTTY_API GhosttyResult ghostty_formatter_terminal_new(
⋮----
GHOSTTY_API GhosttyResult ghostty_formatter_format(
⋮----
GHOSTTY_API GhosttyResult ghostty_formatter_format_buf(GhosttyFormatter formatter,
⋮----
GHOSTTY_API GhosttyResult ghostty_formatter_format_alloc(GhosttyFormatter formatter,
⋮----
GHOSTTY_API void ghostty_formatter_free(GhosttyFormatter formatter);
</file>

<file path="include/ghostty/vt/grid_ref_tracked.h">
GHOSTTY_API void ghostty_tracked_grid_ref_free(GhosttyTrackedGridRef ref);
⋮----
GHOSTTY_API bool ghostty_tracked_grid_ref_has_value(
⋮----
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_point(
⋮----
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_set(
⋮----
GHOSTTY_API GhosttyResult ghostty_tracked_grid_ref_snapshot(
</file>

<file path="include/ghostty/vt/grid_ref.h">
} GhosttyGridRef;
⋮----
GHOSTTY_API GhosttyResult ghostty_grid_ref_cell(const GhosttyGridRef *ref,
⋮----
GHOSTTY_API GhosttyResult ghostty_grid_ref_row(const GhosttyGridRef *ref,
⋮----
GHOSTTY_API GhosttyResult ghostty_grid_ref_graphemes(const GhosttyGridRef *ref,
⋮----
GHOSTTY_API GhosttyResult ghostty_grid_ref_hyperlink_uri(
⋮----
GHOSTTY_API GhosttyResult ghostty_grid_ref_style(const GhosttyGridRef *ref,
</file>

<file path="include/ghostty/vt/io.h">
} GhosttyReader;
⋮----
} GhosttyWriter;
⋮----
} GhosttyMimeReader;
</file>

<file path="include/ghostty/vt/key.h">

</file>

<file path="include/ghostty/vt/kitty_graphics.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyKittyGraphicsData;
⋮----
} GhosttyKittyGraphicsPlacementData;
⋮----
} GhosttyKittyPlacementLayer;
⋮----
} GhosttyKittyGraphicsPlacementIteratorOption;
⋮----
} GhosttyKittyImageFormat;
⋮----
} GhosttyKittyImageCompression;
⋮----
} GhosttyKittyGraphicsImageData;
⋮----
} GhosttyKittyGraphicsPlacementRenderInfo;
⋮----
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_get(
⋮----
GHOSTTY_API GhosttyKittyGraphicsImage ghostty_kitty_graphics_image(
⋮----
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get(
⋮----
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_image_get_multi(
⋮----
GHOSTTY_API GhosttyResult ghostty_kitty_graphics_placement_iterator_new(
⋮----
GHOSTTY_API void ghostty_kitty_graphics_placement_iterator_free(
⋮----
... (20 lines truncated)
</file>

<file path="include/ghostty/vt/modes.h">
typedef uint16_t GhosttyMode;
⋮----
static inline GhosttyMode ghostty_mode_new(uint16_t value, bool ansi) {
⋮----
static inline uint16_t ghostty_mode_value(GhosttyMode mode) {
⋮----
static inline bool ghostty_mode_ansi(GhosttyMode mode) {
⋮----
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyModeReportState;
⋮----
GHOSTTY_API GhosttyResult ghostty_mode_report_encode(
</file>

<file path="include/ghostty/vt/mouse.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyMouseShape;
</file>

<file path="include/ghostty/vt/osc.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyOscCommandType;
⋮----
} GhosttyOscTerminator;
⋮----
} GhosttyOscOption;
⋮----
} GhosttyOscCommandData;
⋮----
GHOSTTY_API GhosttyResult ghostty_osc_new(const GhosttyAllocator *allocator, GhosttyOscParser *parser);
⋮----
GHOSTTY_API void ghostty_osc_free(GhosttyOscParser parser);
⋮----
GHOSTTY_API void ghostty_osc_reset(GhosttyOscParser parser);
⋮----
GHOSTTY_API GhosttyResult ghostty_osc_set(GhosttyOscParser parser,
⋮----
GHOSTTY_API void ghostty_osc_next(GhosttyOscParser parser, uint8_t byte);
⋮----
GHOSTTY_API GhosttyOscCommand ghostty_osc_end(GhosttyOscParser parser, uint8_t terminator);
⋮----
GHOSTTY_API GhosttyOscCommandType ghostty_osc_command_type(GhosttyOscCommand command);
⋮----
GHOSTTY_API bool ghostty_osc_command_data(GhosttyOscCommand command, GhosttyOscCommandData data, void *out);
</file>

<file path="include/ghostty/vt/paste.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyPasteSource;
⋮----
} GhosttyPaste;
⋮----
GHOSTTY_API GhosttyResult ghostty_terminal_paste(
⋮----
GHOSTTY_API bool ghostty_paste_is_safe(const char* data, size_t len);
⋮----
GHOSTTY_API GhosttyResult ghostty_paste_encode(
</file>

<file path="include/ghostty/vt/point.h">
} GhosttyPointCoordinate;
⋮----
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyPointTag;
⋮----
} GhosttyPointValue;
⋮----
} GhosttyPoint;
</file>

<file path="include/ghostty/vt/render.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyRenderStateDirty;
⋮----
} GhosttyRenderStateCursorVisualStyle;
⋮----
} GhosttyRenderStateOverscan;
⋮----
} GhosttyRenderStateRowId;
⋮----
} GhosttyRenderStateData;
⋮----
} GhosttyRenderStateOption;
⋮----
} GhosttyRenderStateRowData;
⋮----
} GhosttyRenderStateRowOption;
⋮----
} GhosttyRenderStateRowSelection;
⋮----
} GhosttyRenderStateCursor;
⋮----
} GhosttyRenderStateColors;
⋮----
GHOSTTY_API GhosttyResult ghostty_render_state_new(const GhosttyAllocator* allocator,
⋮----
GHOSTTY_API void ghostty_render_state_free(GhosttyRenderState state);
⋮----
GHOSTTY_API GhosttyResult ghostty_render_state_update(GhosttyRenderState state,
⋮----
... (40 lines truncated)
</file>

<file path="include/ghostty/vt/screen.h">
typedef uint64_t GhosttyCell;
⋮----
typedef uint64_t GhosttyRow;
⋮----
} GhosttyCellsView;
⋮----
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyCellContentTag;
⋮----
} GhosttyCellWide;
⋮----
} GhosttyCellSemanticContent;
⋮----
} GhosttyCellData;
⋮----
} GhosttyRowSemanticPrompt;
⋮----
} GhosttyRowData;
⋮----
GHOSTTY_API GhosttyResult ghostty_cell_get(GhosttyCell cell,
⋮----
GHOSTTY_API GhosttyResult ghostty_cell_get_multi(GhosttyCell cell,
⋮----
GHOSTTY_API GhosttyResult ghostty_row_get(GhosttyRow row,
⋮----
GHOSTTY_API GhosttyResult ghostty_row_get_multi(GhosttyRow row,
</file>

<file path="include/ghostty/vt/search.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttySearchStatus;
⋮----
} GhosttySearchScroll;
⋮----
} GhosttySearchData;
⋮----
} GhosttySearchOption;
⋮----
GHOSTTY_API GhosttyResult ghostty_search_new(
⋮----
GHOSTTY_API void ghostty_search_free(GhosttySearch search);
⋮----
GHOSTTY_API GhosttyResult ghostty_search_tick(
⋮----
GHOSTTY_API GhosttyResult ghostty_search_feed(GhosttySearch search);
⋮----
GHOSTTY_API GhosttyResult ghostty_search_run(GhosttySearch search);
⋮----
GHOSTTY_API GhosttyResult ghostty_search_set(
⋮----
GHOSTTY_API GhosttyResult ghostty_search_get(
⋮----
GHOSTTY_API GhosttyResult ghostty_search_get_multi(
</file>

<file path="include/ghostty/vt/selection.h">
} GhosttySelection;
⋮----
} GhosttySelectionBuffer;
⋮----
} GhosttyTerminalSelectWordOptions;
⋮----
} GhosttyTerminalSelectWordBetweenOptions;
⋮----
} GhosttyTerminalSelectLineOptions;
⋮----
} GhosttyTerminalSelectionFormatOptions;
⋮----
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttySelectionOrder;
⋮----
} GhosttySelectionAdjust;
⋮----
} GhosttySelectionGestureBehavior;
⋮----
} GhosttySelectionGestureBehaviors;
⋮----
} GhosttySelectionGestureGeometry;
⋮----
} GhosttySelectionGestureAutoscroll;
⋮----
} GhosttySelectionGestureData;
⋮----
} GhosttySelectionGestureEventType;
⋮----
... (44 lines truncated)
</file>

<file path="include/ghostty/vt/sgr.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttySgrAttributeTag;
⋮----
} GhosttySgrUnderline;
⋮----
} GhosttySgrUnknown;
⋮----
} GhosttySgrAttributeValue;
⋮----
} GhosttySgrAttribute;
⋮----
GHOSTTY_API GhosttyResult ghostty_sgr_new(const GhosttyAllocator* allocator,
⋮----
GHOSTTY_API void ghostty_sgr_free(GhosttySgrParser parser);
⋮----
GHOSTTY_API void ghostty_sgr_reset(GhosttySgrParser parser);
⋮----
GHOSTTY_API GhosttyResult ghostty_sgr_set_params(GhosttySgrParser parser,
⋮----
GHOSTTY_API bool ghostty_sgr_next(GhosttySgrParser parser, GhosttySgrAttribute* attr);
⋮----
GHOSTTY_API size_t ghostty_sgr_unknown_full(GhosttySgrUnknown unknown,
⋮----
GHOSTTY_API size_t ghostty_sgr_unknown_partial(GhosttySgrUnknown unknown,
⋮----
GHOSTTY_API GhosttySgrAttributeTag ghostty_sgr_attribute_tag(GhosttySgrAttribute attr);
</file>

<file path="include/ghostty/vt/size_report.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttySizeReportStyle;
⋮----
} GhosttySizeReportSize;
⋮----
GHOSTTY_API GhosttyResult ghostty_size_report_encode(
</file>

<file path="include/ghostty/vt/snapshot.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttySnapshotDecoderOption;
⋮----
} GhosttySnapshotDecoderData;
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_encode(GhosttyTerminal terminal,
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_encode_buf(
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_encode_alloc(
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_decoder_new(
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_decoder_new_buf(
⋮----
GHOSTTY_API void ghostty_snapshot_decoder_free(GhosttySnapshotDecoder decoder);
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_decoder_set(
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_decoder_ready(
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_decoder_next(
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_decoder_decode(
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_decoder_get(
⋮----
GHOSTTY_API GhosttyResult ghostty_snapshot_decoder_get_multi(
</file>

<file path="include/ghostty/vt/style.h">
typedef uint16_t GhosttyStyleId;
⋮----
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyStyleColorTag;
⋮----
} GhosttyStyleColorValue;
⋮----
} GhosttyStyleColor;
⋮----
} GhosttyStyle;
⋮----
GHOSTTY_API void ghostty_style_default(GhosttyStyle* style);
⋮----
GHOSTTY_API bool ghostty_style_is_default(const GhosttyStyle* style);
</file>

<file path="include/ghostty/vt/sys.h">
} GhosttySysImage;
⋮----
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttySysLogLevel;
⋮----
} GhosttySysOption;
⋮----
GHOSTTY_API GhosttyResult ghostty_sys_set(GhosttySysOption option,
⋮----
GHOSTTY_API void ghostty_sys_log_stderr(void* userdata,
</file>

<file path="include/ghostty/vt/terminal.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyTerminalCompressionMode;
⋮----
} GhosttyTerminalCompressionResult;
⋮----
} GhosttyTerminalScrollViewportTag;
⋮----
} GhosttyTerminalScrollViewportValue;
⋮----
} GhosttyTerminalScrollViewport;
⋮----
} GhosttyTerminalScreen;
⋮----
} GhosttyTerminalCursorStyle;
⋮----
} GhosttyTerminalScrollbar;
⋮----
} GhosttyTerminalMemoryUsage;
⋮----
} GhosttyTerminalUnknownSequenceTag;
⋮----
} GhosttyTerminalUnknownStringSequence;
⋮----
} GhosttyTerminalUnknownOscSequence;
⋮----
} GhosttyTerminalUnknownSequenceValue;
⋮----
} GhosttyTerminalUnknownSequence;
⋮----
... (74 lines truncated)
</file>

<file path="include/ghostty/vt/types.h">
typedef enum GHOSTTY_ENUM_TYPED {
⋮----
} GhosttyResult;
⋮----
} GhosttyFormatterFormat;
⋮----
} GhosttyString;
⋮----
} GhosttyBuffer;
⋮----
} GhosttySurfacePosition;
⋮----
} GhosttyCodepoints;
⋮----
GHOSTTY_API const char *ghostty_type_json(void);
</file>

<file path="include/ghostty/vt/unicode.h">
GHOSTTY_API uint8_t ghostty_unicode_codepoint_width(uint32_t cp);
⋮----
GHOSTTY_API size_t ghostty_unicode_grapheme_width(const uint32_t *cps,
</file>

<file path="include/ghostty/vt/wasm.h">
GHOSTTY_API void* ghostty_wasm_alloc(size_t len);
⋮----
GHOSTTY_API void ghostty_wasm_free(void *ptr, size_t len);
⋮----
GHOSTTY_API void** ghostty_wasm_alloc_opaque(void);
⋮----
GHOSTTY_API void ghostty_wasm_free_opaque(void **ptr);
⋮----
GHOSTTY_API void* ghostty_wasm_take_opaque(void **slot);
</file>

<file path="include/ghostty/vt.h">

</file>

<file path="include/ghostty.h">
} ghostty_platform_e;
⋮----
} ghostty_clipboard_e;
⋮----
} ghostty_clipboard_content_s;
⋮----
} ghostty_clipboard_complete_s;
⋮----
} ghostty_clipboard_confirm_s;
⋮----
} ghostty_clipboard_request_e;
⋮----
} ghostty_clipboard_read_result_e;
⋮----
} ghostty_input_mouse_state_e;
⋮----
} ghostty_input_mouse_button_e;
⋮----
} ghostty_input_mouse_momentum_e;
⋮----
} ghostty_color_scheme_e;
⋮----
typedef int ghostty_input_scroll_mods_t;
⋮----
} ghostty_input_mods_e;
⋮----
} ghostty_binding_flags_e;
⋮----
} ghostty_input_action_e;
⋮----
... (288 lines truncated)
</file>

<file path="include/module.modulemap">
// This makes Ghostty available to the XCode build for the macOS app.
// We append "Kit" to it not to be cute, but because targets have to have
// unique names and we use Ghostty for other things.
module GhosttyKit {
    umbrella header "ghostty.h"
    export *
}
</file>

<file path="macos/GhosttyUITests/AppKitExtensions.swift">
var isLightColor: Bool {
⋮----
var luminance: Double {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
⋮----
func colorAt(x: Int, y: Int) -> NSColor? {
</file>

<file path="macos/GhosttyUITests/GhosttyCommandPaletteTests.swift">
final class GhosttyCommandPaletteTests: GhosttyCustomConfigCase {
@MainActor func testDismissingCommandPalette() async throws {
let app = try ghosttyApplication()
⋮----
let clearScreenButton = app.buttons
⋮----
@MainActor func testSelectCommandWithMouse() async throws {
</file>

<file path="macos/GhosttyUITests/GhosttyCustomConfigCase.swift">
class GhosttyCustomConfigCase: XCTestCase {
⋮----
override class var defaultTestSuite: XCTestSuite {
⋮----
static let defaultsSuiteName: String = "GHOSTTY_UI_TESTS"
⋮----
private let configFile: URL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
⋮----
override func setUpWithError() throws {
⋮----
override func tearDown() async throws {
⋮----
func updateConfig(_ newConfig: String) throws {
⋮----
func ghosttyApplication(defaultsSuite: String = GhosttyCustomConfigCase.defaultsSuiteName) throws -> XCUIApplication {
let app = XCUIApplication()
</file>

<file path="macos/GhosttyUITests/GhosttyMouseStateTests.swift">
final class GhosttyMouseStateTests: GhosttyCustomConfigCase {
⋮----
@MainActor func testSelectionFocusChange() async throws {
let app = XCUIApplication()
⋮----
let lines = (1...200).map { "Line \($0): The quick brown fox jumps over the lazy dog. Lorem ipsum dolor sit amet, consectetur adipiscing elit." }
let text = lines.joined(separator: "\n") + "\n"
let tmpFile = NSTemporaryDirectory() + "ghostty_test_dummy.txt"
⋮----
let finder = XCUIApplication(bundleIdentifier: "com.apple.finder")
⋮----
let surface = app.groups["Terminal pane"]
⋮----
@MainActor func testSearchFocusState() async throws {
let app = try ghosttyApplication()
⋮----
let textfield = app.textFields.firstMatch
⋮----
var stringValue: String? {
</file>

<file path="macos/GhosttyUITests/GhosttyThemeTests.swift">
final class GhosttyThemeTests: GhosttyCustomConfigCase {
override static var runsForEachTargetApplicationUIConfiguration: Bool {
⋮----
let windowTitle = "GhosttyThemeTests"
private func assertTitlebarAppearance(
⋮----
let titleView = app.windows.element(boundBy: i).staticTexts.element(matching: NSPredicate(format: "value == '\(title ?? windowTitle)'"))
⋮----
let image = titleView.screenshot().image
⋮----
func testIssue8282() async throws {
⋮----
let app = try ghosttyApplication()
⋮----
func testLightTransparentWindowThemeWithDarkTerminal() async throws {
⋮----
func testLightNativeWindowThemeWithDarkTerminal() async throws {
⋮----
func testReloadingLightTransparentWindowTheme() async throws {
⋮----
func testSwitchingSystemTheme() async throws {
⋮----
func testReloadFromLightWindowThemeToDefaultTheme() async throws {
⋮----
func testReloadFromDefaultThemeToDarkWindowTheme() async throws {
⋮----
func testReloadingFromDarkThemeToSystemLightTheme() async throws {
⋮----
func testQuickTerminalThemeChange() async throws {
⋮----
... (2 lines truncated)
</file>

<file path="macos/GhosttyUITests/GhosttyTitlebarTabsUITests.swift">
final class GhosttyTitlebarTabsUITests: GhosttyCustomConfigCase {
override func setUp() async throws {
⋮----
func testCustomTitlebar() throws {
let app = try ghosttyApplication()
⋮----
let resetZoomButton = app.groups.buttons["ResetZoom"]
let windowTitle = app.windows.firstMatch.title
let titleView = app.staticTexts.element(matching: NSPredicate(format: "value == '\(windowTitle)'"))
⋮----
func testTabsGeometryInNormalWindow() throws {
⋮----
func testTabsGeometryInFullscreen() throws {
⋮----
func testTabsGeometryAfterMovingTabs() throws {
⋮----
let firstTabInFirstWindow = app.windows.firstMatch.tabs.firstMatch
let firstTabInSecondWindow = app.windows.element(boundBy: 1).tabs.firstMatch
⋮----
func testTabsGeometryAfterMergingAllWindows() throws {
⋮----
func checkTabsGeometry(_ window: XCUIElement) {
let closeTabButtons = window.buttons.matching(identifier: "_closeButton")
⋮----
var previousTabHeight: CGFloat?
⋮----
let currentTab = window.tabs.element(boundBy: idx)
⋮----
let titleFrame = currentTab.frame
let shortcutLabelFrame = window.staticTexts.element(matching: NSPredicate(format: "value CONTAINS[c] '⌘\(idx + 1)'")).firstMatch.frame
... (2 lines truncated)
</file>

<file path="macos/GhosttyUITests/GhosttyTitleUITests.swift">
final class GhosttyTitleUITests: GhosttyCustomConfigCase {
override func setUp() async throws {
⋮----
func testTitle() throws {
let app = try ghosttyApplication()
</file>

<file path="macos/GhosttyUITests/GhosttyWindowPositionUITests.swift">
final class GhosttyWindowPositionUITests: GhosttyCustomConfigCase {
⋮----
@MainActor func testWindowCascading() async throws {
⋮----
let app = try ghosttyApplication()
⋮----
let window = app.windows.firstMatch
let windowFrame = window.frame
⋮----
let window2 = app.windows.firstMatch
⋮----
let windowFrame2 = window2.frame
⋮----
let window3 = app.windows.firstMatch
⋮----
let windowFrame3 = window3.frame
⋮----
let window4 = app.windows.firstMatch
⋮----
let windowFrame4 = window4.frame
⋮----
@MainActor func testDragSplitWindowPosition() async throws {
⋮----
let rightSplit = app.groups["Right pane"]
let rightFrame = rightSplit.frame
⋮----
let sourcePos = rightSplit.coordinate(withNormalizedOffset: .zero)
⋮----
let targetPos = rightSplit.coordinate(withNormalizedOffset: .zero)
⋮----
... (27 lines truncated)
</file>

<file path="macos/Sources/App/AppDelegate.swift">
class AppDelegate: NSObject,
⋮----
static let logger = Logger(
⋮----
@IBOutlet private var menuAbout: NSMenuItem?
@IBOutlet private var menuServices: NSMenu?
@IBOutlet private var menuCheckForUpdates: NSMenuItem?
@IBOutlet private var menuOpenConfig: NSMenuItem?
@IBOutlet private var menuReloadConfig: NSMenuItem?
@IBOutlet private var menuSecureInput: NSMenuItem?
@IBOutlet private var menuQuit: NSMenuItem?
⋮----
@IBOutlet private var menuNewWindow: NSMenuItem?
@IBOutlet private var menuNewTab: NSMenuItem?
@IBOutlet private var menuSplitRight: NSMenuItem?
@IBOutlet private var menuSplitLeft: NSMenuItem?
@IBOutlet private var menuSplitDown: NSMenuItem?
@IBOutlet private var menuSplitUp: NSMenuItem?
@IBOutlet private var menuClose: NSMenuItem?
@IBOutlet private var menuCloseTab: NSMenuItem?
@IBOutlet private var menuCloseWindow: NSMenuItem?
@IBOutlet private var menuCloseAllWindows: NSMenuItem?
⋮----
@IBOutlet private var menuUndo: NSMenuItem?
@IBOutlet private var menuRedo: NSMenuItem?
@IBOutlet private var menuCopy: NSMenuItem?
@IBOutlet private var menuPaste: NSMenuItem?
@IBOutlet private var menuPasteSelection: NSMenuItem?
@IBOutlet private var menuSelectAll: NSMenuItem?
@IBOutlet private var menuFindParent: NSMenuItem?
... (307 lines truncated)
</file>

<file path="macos/Sources/App/AppDelegate+Ghostty.swift">
func ghosttySurface(id: UUID) -> Ghostty.SurfaceView? {
</file>

<file path="macos/Sources/App/CommandLineOpenFileFilter.swift">
final class CommandLineOpenFileFilter {
private let workingDirectory: URL
private var filesToIgnore: Set<URL>
⋮----
init(
⋮----
let workingDirectory = URL(
⋮----
let url = Self.fileURL(argument, relativeTo: workingDirectory)
⋮----
func shouldIgnore(_ filename: String) -> Bool {
let url = Self.fileURL(filename, relativeTo: workingDirectory)
⋮----
private static func fileURL(_ path: String, relativeTo workingDirectory: URL) -> URL {
let expanded = (path as NSString).expandingTildeInPath
</file>

<file path="macos/Sources/App/ghostty-bridging-header.h">

</file>

<file path="macos/Sources/App/main.swift">
let stderrHandle = FileHandle.standardError
</file>

<file path="macos/Sources/Features/About/AboutController.swift">
class AboutController: NSWindowController, NSWindowDelegate {
static let shared: AboutController = AboutController()
⋮----
private let viewModel = AboutViewModel()
override var windowNibName: NSNib.Name? { "About" }
⋮----
override func windowDidLoad() {
⋮----
func show() {
⋮----
func hide() {
⋮----
@IBAction func close(_ sender: Any) {
⋮----
@IBAction func closeWindow(_ sender: Any) {
⋮----
@objc func cancel(_ sender: Any?) {
⋮----
func windowWillClose(_ notification: Notification) {
</file>

<file path="macos/Sources/Features/About/AboutView.swift">
struct AboutView: View {
@Environment(\.openURL) var openURL
⋮----
private let githubURL = URL(string: "https://github.com/ghostty-org/ghostty")
private let docsURL = URL(string: "https://ghostty.org/docs")
⋮----
private var build: String? { Bundle.main.infoDictionary?["CFBundleVersion"] as? String }
private var commit: String? { Bundle.main.infoDictionary?["GhosttyCommit"] as? String }
private var version: String? { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String }
⋮----
private enum VersionConfig {
⋮----
private var copyright: String? { Bundle.main.infoDictionary?["NSHumanReadableCopyright"] as? String }
⋮----
private struct VisualEffectBackground: NSViewRepresentable {
let material: NSVisualEffectView.Material
let blendingMode: NSVisualEffectView.BlendingMode
let isEmphasized: Bool
⋮----
init(material: NSVisualEffectView.Material,
⋮----
func updateNSView(_ nsView: NSVisualEffectView, context: Context) {
⋮----
func makeNSView(context: Context) -> NSVisualEffectView {
let visualEffect = NSVisualEffectView()
⋮----
var body: some View {
⋮----
private struct PropertyRow: View {
private let label: String
... (10 lines truncated)
</file>

<file path="macos/Sources/Features/About/AboutViewModel.swift">
class AboutViewModel: ObservableObject {
@Published var currentIcon: Ghostty.MacOSIcon?
@Published var isHovering: Bool = false
⋮----
private var timerCancellable: AnyCancellable?
⋮----
private let icons: [Ghostty.MacOSIcon] = [
⋮----
func startCyclingIcons() {
⋮----
func stopCyclingIcons() {
⋮----
func advanceToNextIcon() {
let currentIndex = currentIcon.flatMap(icons.firstIndex(of:)) ?? 0
let nextIndex = icons.indexWrapping(after: currentIndex)
</file>

<file path="macos/Sources/Features/About/CyclingIconView.swift">
struct CyclingIconView: View {
@EnvironmentObject var viewModel: AboutViewModel
⋮----
var body: some View {
⋮----
private func iconView(for icon: Ghostty.MacOSIcon?) -> some View {
let iconImage: Image = switch icon?.assetName {
</file>

<file path="macos/Sources/Features/App Intents/Entities/CommandEntity.swift">
struct CommandEntity: AppEntity {
let id: ID
⋮----
var title: String
⋮----
var description: String
⋮----
var action: String
⋮----
let command: Ghostty.Command
⋮----
struct ID: Hashable {
let terminalId: TerminalEntity.ID
let actionKey: String
⋮----
static var typeDisplayRepresentation: TypeDisplayRepresentation {
⋮----
var displayRepresentation: DisplayRepresentation {
⋮----
static var defaultQuery = CommandQuery()
⋮----
init(_ command: Ghostty.Command, for terminal: TerminalEntity) {
⋮----
var rawValue: String {
⋮----
init?(rawValue: String) {
let components = rawValue.split(separator: ":", maxSplits: 1)
⋮----
static func entityIdentifier(for entityIdentifierString: String) -> CommandEntity.ID? {
⋮----
... (17 lines truncated)
</file>

<file path="macos/Sources/Features/App Intents/Entities/TerminalEntity.swift">
private let logger = Logger(
⋮----
struct TerminalEntity: AppEntity {
let id: UUID
⋮----
var title: String
⋮----
var workingDirectory: String?
⋮----
var pid: Int?
⋮----
var tty: String?
⋮----
var kind: Kind
⋮----
var screenshot: NSImage?
⋮----
static var typeDisplayRepresentation: TypeDisplayRepresentation {
⋮----
var displayRepresentation: DisplayRepresentation {
var rep = DisplayRepresentation(title: "\(title)")
⋮----
var surfaceView: Ghostty.SurfaceView? {
⋮----
var surfaceModel: Ghostty.Surface? {
⋮----
static var defaultQuery = TerminalQuery()
⋮----
init(_ view: Ghostty.SurfaceView) {
⋮----
... (36 lines truncated)
</file>

<file path="macos/Sources/Features/App Intents/CloseTerminalIntent.swift">
struct CloseTerminalIntent: AppIntent {
static var title: LocalizedStringResource = "Close Terminal"
static var description = IntentDescription("Close an existing terminal.")
⋮----
var terminal: TerminalEntity
⋮----
static var supportedModes: IntentModes = .background
⋮----
func perform() async throws -> some IntentResult {
</file>

<file path="macos/Sources/Features/App Intents/CommandPaletteIntent.swift">
struct CommandPaletteIntent: AppIntent {
static var title: LocalizedStringResource = "Invoke Command Palette Action"
⋮----
var terminal: TerminalEntity
⋮----
var command: CommandEntity
⋮----
static var supportedModes: IntentModes = .background
⋮----
func perform() async throws -> some IntentResult & ReturnsValue<Bool> {
⋮----
let performed = surface.perform(action: command.action)
</file>

<file path="macos/Sources/Features/App Intents/FocusTerminalIntent.swift">
struct FocusTerminalIntent: AppIntent {
static var title: LocalizedStringResource = "Focus Terminal"
static var description = IntentDescription("Move focus to an existing terminal.")
⋮----
var terminal: TerminalEntity
⋮----
static var supportedModes: IntentModes = .background
⋮----
func perform() async throws -> some IntentResult {
</file>

<file path="macos/Sources/Features/App Intents/GetTerminalDetailsIntent.swift">
struct GetTerminalDetailsIntent: AppIntent {
static var title: LocalizedStringResource = "Get Details of Terminal"
⋮----
var detail: TerminalDetail
⋮----
var terminal: TerminalEntity
⋮----
static var supportedModes: IntentModes = .background
⋮----
static var parameterSummary: some ParameterSummary {
⋮----
func perform() async throws -> some IntentResult & ReturnsValue<String?> {
⋮----
enum TerminalDetail: String {
⋮----
static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Terminal Detail")
⋮----
static var caseDisplayRepresentations: [Self: DisplayRepresentation] = [
</file>

<file path="macos/Sources/Features/App Intents/GhosttyIntentError.swift">
enum GhosttyIntentError: Error, CustomLocalizedStringResourceConvertible {
⋮----
var localizedStringResource: LocalizedStringResource {
</file>

<file path="macos/Sources/Features/App Intents/InputIntent.swift">
struct InputTextIntent: AppIntent {
static var title: LocalizedStringResource = "Input Text to Terminal"
⋮----
var text: String
⋮----
var terminal: TerminalEntity
⋮----
static var supportedModes: IntentModes = [.background, .foreground]
⋮----
func perform() async throws -> some IntentResult {
⋮----
struct KeyEventIntent: AppIntent {
static var title: LocalizedStringResource = "Send Keyboard Event to Terminal"
static var description = IntentDescription("Simulate a keyboard event. This will not handle text encoding; use the 'Input Text' action for that.")
⋮----
var key: Ghostty.Input.Key
⋮----
var mods: [KeyEventMods]
⋮----
var action: Ghostty.Input.Action
⋮----
let ghosttyMods = mods.reduce(Ghostty.Input.Mods()) { result, mod in
⋮----
let keyEvent = Ghostty.Input.KeyEvent(
⋮----
struct MouseButtonIntent: AppIntent {
static var title: LocalizedStringResource = "Send Mouse Button Event to Terminal"
⋮----
var button: Ghostty.Input.MouseButton
⋮----
... (32 lines truncated)
</file>

<file path="macos/Sources/Features/App Intents/IntentPermission.swift">
func requestIntentPermission() async -> Bool {
</file>

<file path="macos/Sources/Features/App Intents/KeybindIntent.swift">
struct KeybindIntent: AppIntent {
static var title: LocalizedStringResource = "Invoke a Keybind Action"
⋮----
var terminal: TerminalEntity
⋮----
var action: String
⋮----
static var supportedModes: IntentModes = [.background, .foreground]
⋮----
func perform() async throws -> some IntentResult & ReturnsValue<Bool> {
⋮----
let performed = surface.perform(action: action)
</file>

<file path="macos/Sources/Features/App Intents/NewTerminalIntent.swift">
struct NewTerminalIntent: AppIntent {
static var title: LocalizedStringResource = "New Terminal"
static var description = IntentDescription("Create a new terminal.")
⋮----
var location: NewTerminalLocation
⋮----
var command: String?
⋮----
var workingDirectory: IntentFile?
⋮----
var env: [String]
⋮----
var parent: TerminalEntity?
⋮----
static var supportedModes: IntentModes = .background
⋮----
static var openAppWhenRun = false
⋮----
func perform() async throws -> some IntentResult & ReturnsValue<TerminalEntity?> {
⋮----
let ghostty = appDelegate.ghostty
⋮----
var config = Ghostty.SurfaceConfiguration()
⋮----
let dir = url.hasDirectoryPath ? url : url.deletingLastPathComponent()
⋮----
let key = String(envVar[..<separatorIndex])
let value = String(envVar[envVar.index(after: separatorIndex)...])
⋮----
let parent: Ghostty.SurfaceView?
... (13 lines truncated)
</file>

<file path="macos/Sources/Features/App Intents/QuickTerminalIntent.swift">
struct QuickTerminalIntent: AppIntent {
static var title: LocalizedStringResource = "Open the Quick Terminal"
static var description = IntentDescription("Open the Quick Terminal. If it is already open, then do nothing.")
⋮----
static var supportedModes: IntentModes = .background
⋮----
func perform() async throws -> some IntentResult & ReturnsValue<[TerminalEntity]> {
⋮----
let wasInitialized = delegate.quickControllerInitialized
⋮----
let c = delegate.quickController
⋮----
var terminals: [TerminalEntity] = []
</file>

<file path="macos/Sources/Features/AppleScript/AppDelegate+AppleScript.swift">
var scriptWindows: [ScriptWindow] {
⋮----
var seen: Set<ObjectIdentifier> = []
var result: [ScriptWindow] = []
⋮----
let primaryControllerID = ObjectIdentifier(primary)
⋮----
var frontWindow: ScriptWindow? {
⋮----
func valueInScriptWindows(uniqueID: String) -> ScriptWindow? {
⋮----
var terminals: [ScriptTerminal] {
⋮----
func valueInTerminals(uniqueID: String) -> ScriptTerminal? {
⋮----
func handlePerformActionScriptCommand(_ command: NSScriptCommand) -> NSNumber? {
⋮----
func handleNewSurfaceConfigurationScriptCommand(_ command: NSScriptCommand) -> NSDictionary? {
⋮----
let configuration = try Ghostty.SurfaceConfiguration(
⋮----
func handleNewWindowScriptCommand(_ command: NSScriptCommand) -> ScriptWindow? {
⋮----
let baseConfig: Ghostty.SurfaceConfiguration?
⋮----
let controller = TerminalController.newWindow(
⋮----
let createdWindowID = ScriptWindow.stableID(primaryController: controller)
⋮----
func handleQuitScriptCommand(_ command: NSScriptCommand) {
... (22 lines truncated)
</file>

<file path="macos/Sources/Features/AppleScript/Ghostty.Input.Mods+AppleScript.swift">
init?(scriptModifiers string: String) {
</file>

<file path="macos/Sources/Features/AppleScript/ScriptInputTextCommand.swift">
final class ScriptInputTextCommand: NSScriptCommand {
override func performDefaultImplementation() -> Any? {
</file>

<file path="macos/Sources/Features/AppleScript/ScriptKeyEventCommand.swift">
final class ScriptKeyEventCommand: NSScriptCommand {
override func performDefaultImplementation() -> Any? {
⋮----
let keyEvent: Ghostty.Input.KeyEvent
⋮----
enum ArgumentError: Error, Equatable {
⋮----
static func parse(
⋮----
let action: Ghostty.Input.Action
⋮----
let mods: Ghostty.Input.Mods
</file>

<file path="macos/Sources/Features/AppleScript/ScriptMouseButtonCommand.swift">
final class ScriptMouseButtonCommand: NSScriptCommand {
override func performDefaultImplementation() -> Any? {
⋮----
let action: Ghostty.Input.MouseState
⋮----
let mods: Ghostty.Input.Mods
⋮----
let mouseEvent = Ghostty.Input.MouseButtonEvent(
⋮----
private enum ScriptMouseButtonValue {
⋮----
var ghosttyButton: Ghostty.Input.MouseButton {
</file>

<file path="macos/Sources/Features/AppleScript/ScriptMousePosCommand.swift">
final class ScriptMousePosCommand: NSScriptCommand {
override func performDefaultImplementation() -> Any? {
⋮----
let mods: Ghostty.Input.Mods
⋮----
let mousePosEvent = Ghostty.Input.MousePosEvent(
</file>

<file path="macos/Sources/Features/AppleScript/ScriptMouseScrollCommand.swift">
final class ScriptMouseScrollCommand: NSScriptCommand {
override func performDefaultImplementation() -> Any? {
⋮----
let precision = evaluatedArguments?["precision"] as? Bool ?? false
⋮----
let momentum: Ghostty.Input.Momentum
⋮----
let scrollEvent = Ghostty.Input.MouseScrollEvent(
</file>

<file path="macos/Sources/Features/AppleScript/ScriptRecord.swift">
protocol ScriptRecord {
⋮----
init()
⋮----
init(scriptRecord: NSDictionary?) throws
⋮----
enum RecordParseError: LocalizedError {
⋮----
var errorDescription: String? {
</file>

<file path="macos/Sources/Features/AppleScript/ScriptSurfaceConfiguration.swift">
init(scriptRecord source: NSDictionary?) throws {
⋮----
let value = number.doubleValue
⋮----
var dictionaryRepresentation: NSDictionary {
var record: [String: Any] = [
⋮----
private static func parseScriptEnvironmentAssignments(_ assignments: [String]) throws -> [String: String] {
var result: [String: String] = [:]
⋮----
let key = String(assignment[..<separator])
let valueStart = assignment.index(after: separator)
let value = String(assignment[valueStart...])
</file>

<file path="macos/Sources/Features/AppleScript/ScriptTab.swift">
final class ScriptTab: NSObject {
⋮----
private let stableID: String
⋮----
private weak var window: ScriptWindow?
⋮----
private weak var controller: BaseTerminalController?
⋮----
init(window: ScriptWindow, controller: BaseTerminalController) {
⋮----
var idValue: String {
⋮----
/// Exposed as the AppleScript `title` property.
///
/// Returns the title of the tab's window.
⋮----
var title: String {
⋮----
/// Exposed as the AppleScript `index` property.
⋮----
/// Cocoa scripting expects this to be 1-based for user-facing collections.
⋮----
var index: Int {
⋮----
/// Exposed as the AppleScript `selected` property.
⋮----
/// Powers script conditions such as `if selected of tab 1 then ...`.
⋮----
var selected: Bool {
⋮----
... (35 lines truncated)
</file>

<file path="macos/Sources/Features/AppleScript/ScriptTerminal.swift">
final class ScriptTerminal: NSObject {
⋮----
weak var surfaceView: Ghostty.SurfaceView?
⋮----
init(surfaceView: Ghostty.SurfaceView) {
⋮----
var stableID: String {
⋮----
/// Exposed as the AppleScript `title` property.
⋮----
var title: String {
⋮----
/// Exposed as the AppleScript `working directory` property.
///
/// The `sdef` uses a spaced name, but Cocoa scripting maps that to the
/// camel-cased selector name `workingDirectory`.
⋮----
var workingDirectory: String {
⋮----
/// Exposed as the AppleScript `pid` property.
⋮----
var pid: Int {
⋮----
/// Exposed as the AppleScript `tty` property.
⋮----
var tty: String {
⋮----
/// Used by command handling (`perform action ... on <terminal>`).
func perform(action: String) -> Bool {
⋮----
... (16 lines truncated)
</file>

<file path="macos/Sources/Features/AppleScript/ScriptWindow.swift">
final class ScriptWindow: NSObject {
⋮----
let stableID: String
⋮----
private weak var primaryController: BaseTerminalController?
⋮----
init(primaryController: BaseTerminalController) {
⋮----
var idValue: String {
⋮----
/// Exposed as the AppleScript `title` property.
///
/// Returns the title of the window (from the selected/primary controller's NSWindow).
⋮----
var title: String {
⋮----
/// Exposed as the AppleScript `tabs` element.
⋮----
/// Cocoa asks for this collection when a script evaluates `tabs of window ...`
/// or any tab-filter expression. We build wrappers from live controller state
/// so tab additions/removals are reflected immediately.
⋮----
var tabs: [ScriptTab] {
⋮----
/// Exposed as the AppleScript `selected tab` property.
⋮----
/// This powers expressions like `selected tab of window 1`.
⋮----
var selectedTab: ScriptTab? {
⋮----
... (67 lines truncated)
</file>

<file path="macos/Sources/Features/ClipboardConfirmation/ClipboardConfirmationController.swift">
class ClipboardConfirmationController: NSWindowController {
override var windowNibName: NSNib.Name? { "ClipboardConfirmation" }
⋮----
private(set) var confirmation: Ghostty.ClipboardConfirmationRequest
weak private var delegate: ClipboardConfirmationViewDelegate?
⋮----
init(
⋮----
required init?(coder: NSCoder) {
⋮----
func replaceConfirmation(with confirmation: Ghostty.ClipboardConfirmationRequest) {
⋮----
override func windowDidLoad() {
⋮----
private func configure(_ window: NSWindow) {
</file>

<file path="macos/Sources/Features/ClipboardConfirmation/ClipboardConfirmationView.swift">
protocol ClipboardConfirmationViewDelegate: AnyObject {
func clipboardConfirmationComplete(_ action: ClipboardConfirmationView.Action, remember: Bool)
⋮----
struct ClipboardConfirmationView: View {
enum Action: String {
⋮----
static func text(_ action: Action, _ reason: Ghostty.ClipboardRequest) -> String {
⋮----
let contents: String
⋮----
let request: Ghostty.ClipboardRequest
⋮----
var canRemember: Bool = false
⋮----
var previewImage: NSImage?
⋮----
weak var delegate: ClipboardConfirmationViewDelegate?
⋮----
@State private var remember: Bool = false
⋮----
@State private var cursorHiddenCount: UInt = 0
⋮----
var body: some View {
⋮----
private func onCancel() {
⋮----
private func onPaste() {
</file>

<file path="macos/Sources/Features/Command Palette/CommandPalette.swift">
struct CommandOption: Identifiable, Hashable {
⋮----
let id = UUID()
⋮----
let title: String
⋮----
let subtitle: String?
⋮----
let description: String?
⋮----
let symbols: [String]?
⋮----
let leadingIcon: String?
⋮----
let leadingColor: Color?
⋮----
let badge: String?
⋮----
let emphasis: Bool
⋮----
let sortKey: ObjectIdentifier?
⋮----
let action: () -> Void
⋮----
init(
⋮----
func hash(into hasher: inout Hasher) {
⋮----
struct CommandPaletteView: View {
@Binding var isPresented: Bool
... (124 lines truncated)
</file>

<file path="macos/Sources/Features/Command Palette/TerminalCommandPalette.swift">
func sortedTerminalPaletteOptions(_ options: [CommandOption]) -> [CommandOption] {
⋮----
let lhsTitle = lhs.title.replacingOccurrences(of: ":", with: "\t")
let rhsTitle = rhs.title.replacingOccurrences(of: ":", with: "\t")
let comparison = lhsTitle.localizedCaseInsensitiveCompare(rhsTitle)
⋮----
struct TerminalCommandPaletteView: View {
⋮----
let surfaceView: Ghostty.SurfaceView
⋮----
@Binding var isPresented: Bool
⋮----
@ObservedObject var ghosttyConfig: Ghostty.Config
⋮----
var updateViewModel: UpdateViewModel?
⋮----
var onAction: ((String) -> Void)
⋮----
var body: some View {
⋮----
private var commandOptions: [CommandOption] {
var options: [CommandOption] = []
⋮----
private var updateOptions: [CommandOption] {
⋮----
let title: String
⋮----
private var terminalOptions: [CommandOption] {
⋮----
let symbols = appDelegate.ghostty.config.keyboardShortcut(for: c.action)?.keyList
... (20 lines truncated)
</file>

<file path="macos/Sources/Features/Custom App Icon/Extensions/Notification+AppIcon.swift">
static let ghosttyIconDidChange = Notification.Name("com.mitchellh.ghostty.iconDidChange")
</file>

<file path="macos/Sources/Features/Custom App Icon/Extensions/UserDefaults+AppIcon.swift">
private static let customIconKeyOld = "CustomGhosttyIcon"
private static let customIconKeyNew = "CustomGhosttyIcon2"
⋮----
var appIcon: AppIcon? {
</file>

<file path="macos/Sources/Features/Custom App Icon/AppIcon.swift">
enum AppIcon: Equatable, Codable, Sendable {
⋮----
if let data = try? Data(contentsOf: URL(filePath: config.macosCustomIcon, relativeTo: nil)) {
⋮----
let ghostColor = config.macosIconGhostColor,
⋮----
func image(in bundle: Bundle) -> NSImage? {
⋮----
func update(icon: AppIcon?) {
</file>

<file path="macos/Sources/Features/Custom App Icon/ColorizedGhosttyIcon.swift">
struct ColorizedGhosttyIcon {
⋮----
let screenColors: [NSColor]
⋮----
let ghostColor: NSColor
⋮----
let frame: Ghostty.MacOSIconFrame
⋮----
func makeImage(in bundle: Bundle) -> NSImage? {
⋮----
let baseName = switch frame {
⋮----
private enum CodingKeys: String, CodingKey {
⋮----
static let currentVersion: Int = 1
⋮----
init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
⋮----
let version = try container.decodeIfPresent(Int.self, forKey: .version) ?? 0
⋮----
let screenColorHexes = try container.decode([String].self, forKey: .screenColors)
let screenColors = screenColorHexes.compactMap(NSColor.init(hex:))
let ghostColorHex = try container.decode(String.self, forKey: .ghostColor)
⋮----
let frame = try container.decode(Ghostty.MacOSIconFrame.self, forKey: .frame)
⋮----
func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
</file>

<file path="macos/Sources/Features/Custom App Icon/ColorizedGhosttyIconImage.swift">
func ghosttyIconImage() -> Image {
</file>

<file path="macos/Sources/Features/Custom App Icon/ColorizedGhosttyIconView.swift">
struct ColorizedGhosttyIconView: View {
var body: some View {
</file>

<file path="macos/Sources/Features/Custom App Icon/DockTilePlugin.swift">
class DockTilePlugin: NSObject, NSDockTilePlugIn {
⋮----
private let pluginBundle = Bundle(for: DockTilePlugin.self)
⋮----
private let ghosttyUserDefaults = UserDefaults(suiteName: "com.mitchellh.ghostty.debug")
⋮----
private let ghosttyUserDefaults = UserDefaults(suiteName: "com.mitchellh.ghostty")
⋮----
private var iconChangeObserver: Any?
⋮----
func setDockTile(_ dockTile: NSDockTile?) {
⋮----
private func iconDidChange(_ newIcon: AppIcon?, dockTile: NSDockTile) {
⋮----
private func resetIcon(dockTile: NSDockTile) {
let appIcon: NSImage?
⋮----
func setIcon(_ newIcon: NSImage?) {
⋮----
let iconView = NSImageView(frame: CGRect(origin: .zero, size: self.size))
</file>

<file path="macos/Sources/Features/Global Keybinds/GlobalEventTap.swift">
class GlobalEventTap {
static let shared = GlobalEventTap()
⋮----
fileprivate static let logger = Logger(
⋮----
fileprivate var eventTap: CFMachPort?
⋮----
private var enableTimer: Timer?
⋮----
private init() {}
⋮----
deinit {
⋮----
func enable() {
⋮----
let options = [
⋮----
func disable() {
⋮----
private func tryEnable() -> Bool {
⋮----
let eventMask = [
⋮----
private func cgEventFlagsChangedHandler(
⋮----
let result = Unmanaged.passUnretained(cgEvent)
⋮----
let key_ev = event.ghosttyKeyEvent(GHOSTTY_ACTION_PRESS)
</file>

<file path="macos/Sources/Features/QuickTerminal/QuickTerminalController.swift">
class QuickTerminalController: BaseTerminalController {
override var windowNibName: NSNib.Name? { "QuickTerminal" }
⋮----
let position: QuickTerminalPosition
⋮----
private(set) var visible: Bool = false
⋮----
private var previousApp: NSRunningApplication?
⋮----
private var previousActiveSpace: CGSSpace?
⋮----
let screenStateCache: QuickTerminalScreenStateCache
⋮----
private var hiddenDock: HiddenDock?
⋮----
private var derivedConfig: DerivedConfig
⋮----
private var isHandlingResize: Bool = false
⋮----
let restorable: Bool
private var restorationState: QuickTerminalRestorableState?
⋮----
init(_ ghostty: Ghostty.App,
⋮----
// Important detail here: we initialize with an empty surface tree so
// that we don't start a terminal process. This gets started when the
// first terminal is shown in `animateIn`.
⋮----
// Setup our notifications for behaviors
let center = NotificationCenter.default
... (104 lines truncated)
</file>

<file path="macos/Sources/Features/QuickTerminal/QuickTerminalPosition.swift">
enum QuickTerminalPosition: String {
⋮----
func setLoaded(_ window: NSWindow, size: QuickTerminalSize) {
⋮----
func setInitial(
⋮----
func setFinal(
⋮----
func configuredFrameSize(on screen: NSScreen, terminalSize: QuickTerminalSize) -> NSSize {
let dimensions = terminalSize.calculate(position: self, screenDimensions: screen.visibleFrame.size)
⋮----
func initialOrigin(for window: NSWindow, on screen: NSScreen) -> CGPoint {
⋮----
func finalOrigin(for window: NSWindow, on screen: NSScreen) -> CGPoint {
⋮----
func conflictsWithDock(on screen: NSScreen) -> Bool {
⋮----
func centeredOrigin(for window: NSWindow, on screen: NSScreen) -> CGPoint {
⋮----
func verticallyCenteredOrigin(for window: NSWindow, on screen: NSScreen) -> CGPoint {
</file>

<file path="macos/Sources/Features/QuickTerminal/QuickTerminalRestorableState.swift">
struct QuickTerminalRestorableState: TerminalRestorable {
static var version: Int { 1 }
⋮----
var focusedSurface: String? {
⋮----
var surfaceTree: SplitTree<Ghostty.SurfaceView> {
⋮----
var screenStateEntries: QuickTerminalScreenStateCache.Entries {
⋮----
private let internalState: InternalState<Ghostty.SurfaceView>
⋮----
init(from controller: QuickTerminalController) {
⋮----
init(copy other: QuickTerminalRestorableState) {
⋮----
var baseConfig: Ghostty.SurfaceConfiguration? {
var config = Ghostty.SurfaceConfiguration()
⋮----
struct InternalState<ViewType: NSView & Codable & Identifiable>: Codable {
⋮----
let focusedSurface: String?
let surfaceTree: SplitTree<ViewType>
let screenStateEntries: QuickTerminalScreenStateCache.Entries
</file>

<file path="macos/Sources/Features/QuickTerminal/QuickTerminalScreen.swift">
enum QuickTerminalScreen {
⋮----
var screen: NSScreen? {
⋮----
let mouseLoc = NSEvent.mouseLocation
</file>

<file path="macos/Sources/Features/QuickTerminal/QuickTerminalScreenStateCache.swift">
class QuickTerminalScreenStateCache {
⋮----
private static let maxSavedScreens = 10
⋮----
private static let screenStaleTTL: TimeInterval = 14 * 24 * 60 * 60
⋮----
private(set) var stateByDisplay: Entries = [:]
⋮----
init(stateByDisplay: Entries = [:]) {
⋮----
deinit {
⋮----
func save(frame: NSRect, for screen: NSScreen) {
⋮----
let entry = DisplayEntry(
⋮----
func frame(for screen: NSScreen) -> NSRect? {
⋮----
@objc private func onScreensChanged(_ note: Notification) {
let screens = NSScreen.screens
let now = Date()
let currentIDs = Set(screens.compactMap { $0.displayUUID })
⋮----
private func pruneCapacity() {
⋮----
let toRemove = stateByDisplay
⋮----
struct DisplayEntry: Codable {
var frame: NSRect
var screenSize: CGSize
... (5 lines truncated)
</file>

<file path="macos/Sources/Features/QuickTerminal/QuickTerminalSize.swift">
struct QuickTerminalSize {
let primary: Size?
let secondary: Size?
⋮----
init(primary: Size? = nil, secondary: Size? = nil) {
⋮----
init(from cStruct: ghostty_config_quick_terminal_size_s) {
⋮----
enum Size {
⋮----
func toPixels(parentDimension: CGFloat) -> CGFloat {
⋮----
func calculate(position: QuickTerminalPosition, screenDimensions: CGSize) -> CGSize {
let dims = CGSize(width: screenDimensions.width, height: screenDimensions.height)
</file>

<file path="macos/Sources/Features/QuickTerminal/QuickTerminalSpaceBehavior.swift">
enum QuickTerminalSpaceBehavior {
⋮----
var collectionBehavior: NSWindow.CollectionBehavior {
let commonBehavior: [NSWindow.CollectionBehavior] = [
</file>

<file path="macos/Sources/Features/QuickTerminal/QuickTerminalWindow.swift">
class QuickTerminalWindow: NSPanel {
⋮----
override var canBecomeKey: Bool { return true }
override var canBecomeMain: Bool { return true }
⋮----
override func awakeFromNib() {
⋮----
var initialFrame: NSRect?
⋮----
override func setFrame(_ frameRect: NSRect, display flag: Bool) {
</file>

<file path="macos/Sources/Features/Secure Input/SecureInput.swift">
class SecureInput: ObservableObject {
static let shared = SecureInput()
⋮----
private static let logger = Logger(
⋮----
var global: Bool = false {
⋮----
private var scoped: [ObjectIdentifier: Bool] = [:]
⋮----
@Published private(set) var enabled: Bool = false
⋮----
private var desired: Bool {
⋮----
private init() {
⋮----
let center = NotificationCenter.default
⋮----
deinit {
⋮----
func setScoped(_ object: ObjectIdentifier, focused: Bool) {
⋮----
func removeScoped(_ object: ObjectIdentifier) {
⋮----
private func apply() {
⋮----
let err: OSStatus
⋮----
@objc private func onDidBecomeActive(notification: NSNotification) {
⋮----
let err = EnableSecureEventInput()
... (5 lines truncated)
</file>

<file path="macos/Sources/Features/Secure Input/SecureInputOverlay.swift">
struct SecureInputOverlay: View {
⋮----
@State private var gradientAngle: Angle = .degrees(0)
@State private var gradientOpacity: CGFloat = 0.5
⋮----
@State private var isPopover = false
⋮----
var body: some View {
</file>

<file path="macos/Sources/Features/Services/ServiceProvider.swift">
class ServiceProvider: NSObject {
static private let errorNoString = NSString(string: "Could not load any text from the clipboard.")
⋮----
private enum OpenTarget {
⋮----
@objc func openTab(
⋮----
@objc func openWindow(
⋮----
private func openTerminal(
⋮----
let directoryURLs = Set(
⋮----
let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? url.hasDirectoryPath
⋮----
var config = Ghostty.SurfaceConfiguration()
</file>

<file path="macos/Sources/Features/Settings/ConfigurationErrorsController.swift">
class ConfigurationErrorsController: NSWindowController, NSWindowDelegate, ConfigurationErrorsViewModel {
⋮----
static let sharedInstance = ConfigurationErrorsController()
⋮----
override var windowNibName: NSNib.Name? { "ConfigurationErrors" }
⋮----
@Published var errors: [String] = [] {
⋮----
override func windowWillLoad() {
⋮----
override func windowDidLoad() {
</file>

<file path="macos/Sources/Features/Settings/ConfigurationErrorsView.swift">
protocol ConfigurationErrorsViewModel: ObservableObject {
⋮----
struct ConfigurationErrorsView<ViewModel: ConfigurationErrorsViewModel>: View {
@ObservedObject var model: ViewModel
⋮----
var body: some View {
⋮----
private func reloadConfig() {
</file>

<file path="macos/Sources/Features/Settings/SettingsView.swift">
struct SettingsView: View {
⋮----
@EnvironmentObject private var appDelegate: AppDelegate
⋮----
var body: some View {
⋮----
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
</file>

<file path="macos/Sources/Features/Splits/SplitTree.swift">
struct SplitTree<ViewType: NSView & Codable & Identifiable> {
⋮----
let root: Node?
⋮----
let zoomed: Node?
⋮----
indirect enum Node: Codable {
⋮----
struct Split: Equatable, Codable {
let direction: Direction
let ratio: Double
let left: Node
let right: Node
⋮----
enum Direction: Codable {
⋮----
struct Path: Codable {
let path: [Component]
⋮----
var isEmpty: Bool { path.isEmpty }
⋮----
enum Component: Codable {
⋮----
struct Spatial {
let slots: [Slot]
⋮----
struct Slot {
let node: Node
let bounds: CGRect
⋮----
... (232 lines truncated)
</file>

<file path="macos/Sources/Features/Splits/SplitView.Divider.swift">
struct Divider: View {
let direction: SplitViewDirection
let visibleSize: CGFloat
let invisibleSize: CGFloat
let color: Color
@Binding var split: CGFloat
⋮----
private var visibleWidth: CGFloat? {
⋮----
private var visibleHeight: CGFloat? {
⋮----
private var invisibleWidth: CGFloat? {
⋮----
private var invisibleHeight: CGFloat? {
⋮----
private var pointerStyle: BackportPointerStyle {
⋮----
var body: some View {
⋮----
let adjustment: CGFloat = 0.025
⋮----
private var axLabel: String {
⋮----
private var axHint: String {
</file>

<file path="macos/Sources/Features/Splits/SplitView.swift">
struct SplitView<L: View, R: View>: View {
⋮----
let direction: SplitViewDirection
⋮----
let dividerColor: Color
⋮----
let resizeIncrements: NSSize
⋮----
let left: L
let right: R
⋮----
let onEqualize: () -> Void
⋮----
let minSize: CGFloat = 10
⋮----
@Binding var split: CGFloat
⋮----
private let splitterVisibleSize: CGFloat = 1
private let splitterInvisibleSize: CGFloat = 6
⋮----
var body: some View {
⋮----
let leftRect = self.leftRect(for: geo.size)
let rightRect = self.rightRect(for: geo.size, leftRect: leftRect)
let splitterPoint = self.splitterPoint(for: geo.size, leftRect: leftRect)
⋮----
init(
⋮----
private func dragGesture(_ size: CGSize, splitterPoint: CGPoint) -> some Gesture {
⋮----
... (20 lines truncated)
</file>

<file path="macos/Sources/Features/Splits/TerminalSplitTreeView.swift">
enum TerminalSplitOperation {
⋮----
struct Resize {
let node: SplitTree<Ghostty.SurfaceView>.Node
let ratio: Double
⋮----
struct Drop {
⋮----
let payload: Ghostty.SurfaceView
⋮----
let destination: Ghostty.SurfaceView
⋮----
let zone: TerminalSplitDropZone
⋮----
struct TerminalSplitTreeView: View {
let tree: SplitTree<Ghostty.SurfaceView>
let action: (TerminalSplitOperation) -> Void
⋮----
var body: some View {
⋮----
private struct TerminalSplitSubtreeView: View {
@EnvironmentObject var ghostty: Ghostty.App
⋮----
var isRoot: Bool = false
⋮----
let splitViewDirection: SplitViewDirection = switch split.direction {
⋮----
private struct TerminalSplitLeaf: View {
let surfaceView: Ghostty.SurfaceView
let isSplit: Bool
... (40 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/Window Styles/HiddenTitlebarTerminalWindow.swift">
class HiddenTitlebarTerminalWindow: TerminalWindow {
⋮----
override var supportsUpdateAccessory: Bool { false }
⋮----
override func awakeFromNib() {
⋮----
deinit {
⋮----
private static let hiddenStyleMask: NSWindow.StyleMask = [
⋮----
private func reapplyHiddenStyle() {
⋮----
override var title: String {
⋮----
override var contentLayoutRect: CGRect {
var rect = super.contentLayoutRect
⋮----
@objc private func fullscreenDidExit(_ notification: Notification) {
</file>

<file path="macos/Sources/Features/Terminal/Window Styles/TerminalWindow.swift">
class TerminalWindow: NSWindow {
⋮----
static let terminalDidAwake = Notification.Name("TerminalWindowDidAwake")
⋮----
static let terminalWillCloseNotification = Notification.Name("TerminalWindowWillClose")
⋮----
static let defaultLevelKey: String = "TerminalDefaultLevel"
⋮----
private var viewModel = ViewModel()
⋮----
private let resetZoomAccessory = NSTitlebarAccessoryViewController()
⋮----
private let updateAccessory = NSTitlebarAccessoryViewController()
⋮----
private lazy var tabColorIndicator: NSHostingView<TabColorIndicatorView> = {
let view = NSHostingView(rootView: TabColorIndicatorView(tabColor: tabColor))
⋮----
private(set) var derivedConfig: DerivedConfig = .init()
⋮----
private var tabMenuObserver: NSObjectProtocol?
⋮----
private(set) lazy var tabTitleEditor = TabTitleEditor(
⋮----
var supportsUpdateAccessory: Bool {
⋮----
private var glassEffectView: NSView?
⋮----
var terminalController: TerminalController? {
⋮----
var tabColor: TerminalTabColor = .none {
... (175 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/Window Styles/TitlebarTabsTahoeTerminalWindow.swift">
class TitlebarTabsTahoeTerminalWindow: TransparentTitlebarTerminalWindow, NSToolbarDelegate {
⋮----
private var viewModel = ViewModel()
⋮----
override var supportsUpdateAccessory: Bool { false }
⋮----
deinit {
⋮----
override var titlebarFont: NSFont? {
⋮----
override var title: String {
⋮----
override func awakeFromNib() {
⋮----
let toolbar = NSToolbar(identifier: "TerminalToolbar")
⋮----
override func syncAppearance(_ surfaceConfig: Ghostty.SurfaceView.DerivedConfig) {
⋮----
override func becomeMain() {
⋮----
override func resignMain() {
⋮----
override func addTitlebarAccessoryViewController(_ childViewController: NSTitlebarAccessoryViewController) {
⋮----
override func removeTitlebarAccessoryViewController(at index: Int) {
⋮----
private var tabBarObserver: NSObjectProtocol? {
⋮----
func setupTabBar() {
⋮----
... (34 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/Window Styles/TitlebarTabsVenturaTerminalWindow.swift">
class TitlebarTabsVenturaTerminalWindow: TerminalWindow {
⋮----
override var supportsUpdateAccessory: Bool { false }
⋮----
fileprivate var isLightTheme: Bool = false
⋮----
lazy var titlebarColor: NSColor = backgroundColor {
⋮----
private var hasWindowButtons: Bool {
⋮----
let closeIsHidden = standardWindowButton(.closeButton)?.isHiddenOrHasHiddenAncestor ?? true
let miniaturizeIsHidden = standardWindowButton(.miniaturizeButton)?.isHiddenOrHasHiddenAncestor ?? true
let zoomIsHidden = standardWindowButton(.zoomButton)?.isHiddenOrHasHiddenAncestor ?? true
⋮----
override func awakeFromNib() {
⋮----
private var effectViewIsHidden = false
⋮----
override func becomeKey() {
⋮----
override func resignKey() {
⋮----
override func layoutIfNeeded() {
⋮----
override func update() {
⋮----
override func updateConstraintsIfNeeded() {
⋮----
override func mergeAllWindows(_ sender: Any?) {
⋮----
... (119 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/Window Styles/TransparentTitlebarTerminalWindow.swift">
class TransparentTitlebarTerminalWindow: TerminalWindow {
⋮----
private var lastSurfaceConfig: Ghostty.SurfaceView.DerivedConfig?
⋮----
private weak var observedTabGroup: NSWindowTabGroup?
private var tabGroupWindowsObservation: NSKeyValueObservation?
private var tabBarVisibleObservation: NSKeyValueObservation?
⋮----
deinit {
⋮----
override func awakeFromNib() {
⋮----
override func becomeMain() {
⋮----
override func update() {
⋮----
override func syncAppearance(_ surfaceConfig: Ghostty.SurfaceView.DerivedConfig) {
⋮----
private func syncAppearanceTahoe(_ surfaceConfig: Ghostty.SurfaceView.DerivedConfig) {
⋮----
let isGlassStyle = derivedConfig.backgroundBlur.isGlassStyle
let isTransparentTitlebar = derivedConfig.macosTitlebarStyle == .transparent ||
⋮----
private func syncAppearanceVentura(_ surfaceConfig: Ghostty.SurfaceView.DerivedConfig) {
⋮----
final func reduceTabBarBackgroundGoldenGate() {
⋮----
private var titlebarBackgroundView: NSView? {
⋮----
private func setupKVO() {
... (12 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/BaseTerminalController.swift">
class BaseTerminalController: NSWindowController,
⋮----
private static let surfaceControllers =
⋮----
let ghostty: Ghostty.App
⋮----
var focusedSurface: Ghostty.SurfaceView? {
⋮----
@Published var surfaceTree: SplitTree<Ghostty.SurfaceView> = .init() {
⋮----
@Published var commandPaletteIsShowing: Bool = false
⋮----
@Published var updateOverlayIsVisible: Bool = false
⋮----
@Published private(set) var bell: Bool = false
⋮----
var focusFollowsMouse: Bool {
⋮----
private var alert: NSAlert?
⋮----
private var clipboardConfirmation: ClipboardConfirmationController?
⋮----
private(set) var fullscreenStyle: FullscreenStyle?
⋮----
private var eventMonitor: Any?
⋮----
private var savedFrame: SavedFrame?
⋮----
private var appliedColorScheme: ghostty_color_scheme_e?
⋮----
... (308 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/ErrorView.swift">
struct ErrorView: View {
var body: some View {
⋮----
struct ErrorView_Previews: PreviewProvider {
static var previews: some View {
</file>

<file path="macos/Sources/Features/Terminal/TerminalController.swift">
class TerminalController: BaseTerminalController, TabGroupCloseCoordinator.Controller {
override var windowNibName: NSNib.Name? {
let defaultValue = "Terminal"
⋮----
let config = appDelegate.ghostty.config
⋮----
let nib = switch config.macosTitlebarStyle {
⋮----
private var tabListenForFrame: Bool = false
⋮----
private var tabWindowsHash: Int = 0
⋮----
private var pendingInitialPresentation: DispatchWorkItem?
⋮----
private var restorable: Bool = true
⋮----
private(set) var derivedConfig: DerivedConfig
⋮----
private var surfaceAppearanceCancellables: Set<AnyCancellable> = []
⋮----
init(_ ghostty: Ghostty.App,
⋮----
// Setup our initial derived config based on the current app config
⋮----
// Setup our notifications for behaviors
let center = NotificationCenter.default
⋮----
required init?(coder: NSCoder) {
⋮----
deinit {
... (241 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/TerminalRestorable.swift">
protocol TerminalRestorable: Codable {
⋮----
init(copy other: Self)
⋮----
static var minimumVersion: Int { version }
⋮----
static var selfKey: String { "state" }
static var versionKey: String { "version" }
⋮----
private var debugDescription: String {
⋮----
var baseConfig: Ghostty.SurfaceConfiguration? { nil }
⋮----
init?(coder aDecoder: NSCoder) {
⋮----
let current = aDecoder.decodeInteger(forKey: Self.versionKey)
⋮----
func encode(with coder: NSCoder) {
⋮----
final class TerminalRestorableState: TerminalRestorable {
static var version: Int { 7 }
static var minimumVersion: Int { 5 }
⋮----
var focusedSurface: String? {
⋮----
var surfaceTree: SplitTree<Ghostty.SurfaceView> {
⋮----
var effectiveFullscreenMode: FullscreenMode? {
⋮----
var tabColor: TerminalTabColor? {
... (26 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/TerminalRestorableState+InteralState.swift">
struct InternalState<ViewType: NSView & Codable & Identifiable>: Codable {
⋮----
let focusedSurface: String?
let surfaceTree: SplitTree<ViewType>
⋮----
let effectiveFullscreenMode: FullscreenMode?
let tabColor: TerminalTabColor?
let titleOverride: String?
⋮----
init(from controller: TerminalController) {
</file>

<file path="macos/Sources/Features/Terminal/TerminalTabColor.swift">
enum TerminalTabColor: Int, CaseIterable, Codable {
⋮----
var localizedName: String {
⋮----
var displayColor: NSColor? {
⋮----
func swatchImage(selected: Bool) -> NSImage {
let size = NSSize(width: 18, height: 18)
⋮----
let circleRect = rect.insetBy(dx: 1, dy: 1)
let circlePath = NSBezierPath(ovalIn: circleRect)
⋮----
let slash = NSBezierPath()
⋮----
let highlight = NSBezierPath(ovalIn: rect.insetBy(dx: 0.5, dy: 0.5))
⋮----
struct TabColorMenuView: View {
@State private var currentSelection: TerminalTabColor
let onSelect: (TerminalTabColor) -> Void
⋮----
init(selectedColor: TerminalTabColor, onSelect: @escaping (TerminalTabColor) -> Void) {
⋮----
var body: some View {
⋮----
static let paletteRows: [[TerminalTabColor]] = [
⋮----
private static var leadingPadding: CGFloat {
⋮----
private struct TabColorSwatch: View {
let color: TerminalTabColor
... (3 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/TerminalView.swift">
protocol TerminalViewDelegate: AnyObject {
⋮----
func focusedSurfaceDidChange(to: Ghostty.SurfaceView?)
⋮----
func pwdDidChange(to: URL?)
⋮----
func cellSizeDidChange(to: NSSize)
⋮----
func performAction(_ action: String, on: Ghostty.SurfaceView)
⋮----
func performSplitAction(_ action: TerminalSplitOperation)
⋮----
protocol TerminalViewModel: ObservableObject {
⋮----
struct TerminalView<ViewModel: TerminalViewModel>: View {
@ObservedObject var ghostty: Ghostty.App
⋮----
@ObservedObject var viewModel: ViewModel
⋮----
weak var delegate: (any TerminalViewDelegate)?
⋮----
@State private var lastFocusedSurface: Weak<Ghostty.SurfaceView>?
⋮----
@FocusState private var focused: Bool
⋮----
@FocusedValue(\.ghosttySurfaceView) private var focusedSurface
@FocusedValue(\.ghosttySurfacePwd) private var surfacePwd
@FocusedValue(\.ghosttySurfaceCellSize) private var cellSize
⋮----
private var pwdURL: URL? {
... (8 lines truncated)
</file>

<file path="macos/Sources/Features/Terminal/TerminalViewContainer.swift">
class TerminalViewContainer: NSView {
private let terminalView: NSView
⋮----
private(set) var glassEffectView: NSView?
private var derivedConfig: DerivedConfig?
⋮----
var windowThemeFrameView: NSView? {
⋮----
var windowCornerRadius: CGFloat? {
⋮----
init<Root: View>(@ViewBuilder rootView: () -> Root) {
⋮----
required init?(coder: NSCoder) {
⋮----
var initialContentSize: NSSize?
⋮----
override var intrinsicContentSize: NSSize {
let hostingSize = terminalView.intrinsicContentSize
⋮----
private func setup() {
⋮----
override func viewDidMoveToWindow() {
⋮----
override func layout() {
⋮----
func ghosttyConfigDidChange(_ config: Ghostty.Config, preferredBackgroundColor: NSColor?) {
let newValue = DerivedConfig(config: config, preferredBackgroundColor: preferredBackgroundColor, cornerRadius: windowCornerRadius)
⋮----
var terminalViewContainer: TerminalViewContainer? {
⋮----
... (42 lines truncated)
</file>

<file path="macos/Sources/Features/Update/UpdateBadge.swift">
struct UpdateBadge: View {
⋮----
@ObservedObject var model: UpdateViewModel
⋮----
@State private var rotationAngle: Double = 0
⋮----
var body: some View {
⋮----
private var badgeContent: some View {
⋮----
let progress = min(1, max(0, Double(download.progress) / Double(expectedLength)))
⋮----
private struct ProgressRingView: View {
⋮----
let progress: Double
⋮----
let lineWidth: CGFloat = 2
</file>

<file path="macos/Sources/Features/Update/UpdateController.swift">
class UpdateController {
private(set) var updater: SPUUpdater
private let userDriver: UpdateDriver
⋮----
var viewModel: UpdateViewModel {
⋮----
var shouldTerminateWithoutWarning: Bool {
⋮----
init() {
let hostBundle = Bundle.main
⋮----
func startUpdater() {
⋮----
func checkForUpdates() {
⋮----
let alert = NSAlert()
⋮----
let accessoryView = NSHostingView(
⋮----
private struct InstallingAccessoryView: View {
let installing: UpdateState.Installing
⋮----
var body: some View {
</file>

<file path="macos/Sources/Features/Update/UpdateDelegate.swift">
func feedURLString(for updater: SPUUpdater) -> String? {
⋮----
func updater(_ updater: SPUUpdater, willInstallUpdateOnQuit item: SUAppcastItem, immediateInstallationBlock immediateInstallHandler: @escaping () -> Void) -> Bool {
</file>

<file path="macos/Sources/Features/Update/UpdateDriver.swift">
class UpdateDriver: NSObject, SPUUserDriver {
let viewModel: UpdateViewModel
let standard: SPUStandardUserDriver
⋮----
init(viewModel: UpdateViewModel, hostBundle: Bundle) {
⋮----
deinit {
⋮----
@objc private func handleTerminalWindowWillClose() {
⋮----
func show(_ request: SPUUpdatePermissionRequest,
⋮----
func showUserInitiatedUpdateCheck(cancellation: @escaping () -> Void) {
⋮----
func showUpdateFound(with appcastItem: SUAppcastItem,
⋮----
func showUpdateReleaseNotes(with downloadData: SPUDownloadData) {
⋮----
func showUpdateReleaseNotesFailedToDownloadWithError(_ error: any Error) {
⋮----
func showUpdateNotFoundWithError(_ error: any Error,
⋮----
func showUpdaterError(_ error: any Error,
⋮----
func showDownloadInitiated(cancellation: @escaping () -> Void) {
⋮----
func showDownloadDidReceiveExpectedContentLength(_ expectedContentLength: UInt64) {
⋮----
func showDownloadDidReceiveData(ofLength length: UInt64) {
⋮----
... (16 lines truncated)
</file>

<file path="macos/Sources/Features/Update/UpdatePill.swift">
struct UpdatePill: View {
⋮----
@ObservedObject var model: UpdateViewModel
⋮----
@State private var showPopover = false
⋮----
@State private var resetTask: Task<Void, Never>?
⋮----
private let textFont = NSFont.systemFont(ofSize: 11, weight: .medium)
⋮----
var body: some View {
⋮----
private var pillButton: some View {
⋮----
private var textWidth: CGFloat? {
let attributes: [NSAttributedString.Key: Any] = [.font: textFont]
let size = (model.maxWidthText as NSString).size(withAttributes: attributes)
</file>

<file path="macos/Sources/Features/Update/UpdatePopoverView.swift">
struct UpdatePopoverView: View {
⋮----
@ObservedObject var model: UpdateViewModel
⋮----
@Environment(\.dismiss) private var dismiss
⋮----
var body: some View {
⋮----
private struct PermissionRequestView: View {
let request: UpdateState.PermissionRequest
let dismiss: DismissAction
⋮----
private struct CheckingView: View {
let checking: UpdateState.Checking
⋮----
private struct UpdateAvailableView: View {
let update: UpdateState.UpdateAvailable
⋮----
private let labelWidth: CGFloat = 60
⋮----
private struct DownloadingView: View {
let download: UpdateState.Downloading
⋮----
let progress = min(1, max(0, Double(download.progress) / Double(expectedLength)))
⋮----
private struct ExtractingView: View {
let extracting: UpdateState.Extracting
⋮----
private struct NotFoundView: View {
let notFound: UpdateState.NotFound
... (4 lines truncated)
</file>

<file path="macos/Sources/Features/Update/UpdateSimulator.swift">
enum UpdateSimulator {
⋮----
func simulate(with viewModel: UpdateViewModel) {
⋮----
private func simulateHappyPath(_ viewModel: UpdateViewModel) {
⋮----
private func simulateNotFound(_ viewModel: UpdateViewModel) {
⋮----
private func simulateError(_ viewModel: UpdateViewModel) {
⋮----
private func simulateSlowDownload(_ viewModel: UpdateViewModel) {
⋮----
private func simulateSlowDownloadProgress(_ viewModel: UpdateViewModel) {
let download = UpdateState.Downloading(
⋮----
let updatedDownload = UpdateState.Downloading(
⋮----
private func simulatePermissionRequest(_ viewModel: UpdateViewModel) {
let request = SPUUpdatePermissionRequest(systemProfile: [])
⋮----
private func simulateCancelDuringDownload(_ viewModel: UpdateViewModel) {
⋮----
private func simulateDownloadThenCancel(_ viewModel: UpdateViewModel) {
⋮----
private func simulateCancelDuringChecking(_ viewModel: UpdateViewModel) {
⋮----
private func simulateDownload(_ viewModel: UpdateViewModel) {
⋮----
private func simulateExtract(_ viewModel: UpdateViewModel) {
⋮----
... (5 lines truncated)
</file>

<file path="macos/Sources/Features/Update/UpdateViewModel.swift">
class UpdateViewModel: ObservableObject {
@Published var state: UpdateState = .idle
⋮----
var text: String {
⋮----
let version = update.appcastItem.displayVersionString
⋮----
let progress = Double(download.progress) / Double(expectedLength)
⋮----
var maxWidthText: String {
⋮----
var iconName: String? {
⋮----
var description: String {
⋮----
var badge: String? {
⋮----
let percentage = Double(download.progress) / Double(expectedLength) * 100
⋮----
var iconColor: Color {
⋮----
var backgroundColor: Color {
⋮----
var foregroundColor: Color {
⋮----
enum UpdateState: Equatable {
⋮----
var shouldTerminateWithoutWarning: Bool {
⋮----
var isHidden: Bool {
... (61 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Surface View/ChildExitedMessageBar.swift">
struct ChildExitedMessageBar: View {
let msg: Ghostty.ChildExitedMessage
@State private var isHovered: Bool = false
⋮----
var body: some View {
⋮----
private var message: AttributedString {
⋮----
var foregroundColor: Color {
⋮----
var backgroundStyle: AnyShapeStyle {
</file>

<file path="macos/Sources/Ghostty/Surface View/InspectorView.swift">
struct InspectableSurface: View {
@EnvironmentObject var ghostty: Ghostty.App
⋮----
@ObservedObject var surfaceView: SurfaceView
var isSplit: Bool = false
⋮----
@FocusState private var inspectorFocus: Bool
⋮----
@State private var split: CGFloat = 0.5
⋮----
var body: some View {
let center = NotificationCenter.default
let pubInspector = center.publisher(for: Notification.didControlInspector, object: surfaceView)
⋮----
private func onControlInspector(_ notification: SwiftUI.Notification) {
⋮----
struct InspectorViewRepresentable: NSViewRepresentable {
⋮----
let surfaceView: SurfaceView
⋮----
func makeNSView(context: Context) -> InspectorView {
let view = InspectorView()
⋮----
func updateNSView(_ view: InspectorView, context: Context) {
⋮----
class InspectorView: MTKView, NSTextInputClient {
let commandQueue: MTLCommandQueue
⋮----
var surfaceView: SurfaceView? {
⋮----
... (99 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Surface View/OSSurfaceView.swift">
class OSSurfaceView: NSView, ObservableObject {
⋮----
let id: UUID
⋮----
@Published var pwd: String?
⋮----
@Published var cellSize: CGSize = .zero
⋮----
@Published var healthy: Bool = true
⋮----
@Published var error: Error?
⋮----
@Published var hoverUrl: String?
⋮----
@Published var progressReport: Action.ProgressReport?
⋮----
@Published var keyTables: [String] = []
⋮----
@Published var searchState: SearchState?
⋮----
@Published var focusInstant: ContinuousClock.Instant?
⋮----
@Published var surfaceSize: ghostty_surface_size_s?
⋮----
@Published private(set) var readonly: Bool = false
⋮----
@Published private(set) var highlighted: Bool = false
⋮----
@Published private(set) var childExitedMessage: ChildExitedMessage?
⋮----
... (58 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Surface View/SurfaceDragSource.swift">
struct DraggingSurfaceKey: PreferenceKey {
static var defaultValue: SurfaceView.ID?
⋮----
static func reduce(value: inout SurfaceView.ID?, nextValue: () -> SurfaceView.ID?) {
⋮----
struct SurfaceDragSource: View {
⋮----
let surfaceView: SurfaceView
⋮----
@Binding var isDragging: Bool
⋮----
@Binding var isHovering: Bool
⋮----
var body: some View {
⋮----
fileprivate struct SurfaceDragSourceViewRepresentable: NSViewRepresentable {
⋮----
func makeNSView(context: Context) -> SurfaceDragSourceView {
let view = SurfaceDragSourceView()
⋮----
func updateNSView(_ nsView: SurfaceDragSourceView, context: Context) {
⋮----
fileprivate class SurfaceDragSourceView: NSView, NSDraggingSource {
⋮----
private static let previewScale: CGFloat = 0.2
⋮----
var surfaceView: SurfaceView?
⋮----
var onDragStateChanged: ((Bool) -> Void)?
⋮----
... (43 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Surface View/SurfaceGrabHandle.swift">
struct SurfaceGrabHandle: View {
⋮----
private static let handleSize = CGSize(width: 80, height: 12)
⋮----
private static let hoverHeightFactor: CGFloat = 0.2
⋮----
@ObservedObject var surfaceView: SurfaceView
let dragHandle: Ghostty.Config.DragHandle
⋮----
@State private var isHovering: Bool = false
@State private var isDragging: Bool = false
⋮----
private var handleVisible: Bool {
⋮----
private var ellipsisVisible: Bool {
⋮----
var body: some View {
⋮----
private static func hoverRect(in bounds: CGRect) -> CGRect {
⋮----
let hoverHeight = min(bounds.height, max(handleSize.height, bounds.height * hoverHeightFactor))
⋮----
private static func isInHoverRegion(_ point: CGPoint, in bounds: CGRect) -> Bool {
</file>

<file path="macos/Sources/Ghostty/Surface View/SurfaceProgressBar.swift">
struct SurfaceProgressBar: View {
let report: Ghostty.Action.ProgressReport
⋮----
private var color: Color {
⋮----
private var progress: UInt8? {
⋮----
private var accessibilityLabel: String {
⋮----
private var accessibilityValue: String {
⋮----
var body: some View {
⋮----
private struct BouncingProgressBar: View {
let color: Color
@State private var position: CGFloat = 0
⋮----
private let barWidthRatio: CGFloat = 0.25
</file>

<file path="macos/Sources/Ghostty/Surface View/SurfaceScrollView.swift">
class SurfaceScrollView: NSView {
private let scrollView: NSScrollView
private let documentView: NSView
private let surfaceView: Ghostty.SurfaceView
private var observers: [NSObjectProtocol] = []
private var cancellables: Set<AnyCancellable> = []
private var isLiveScrolling = false
⋮----
private var lastSentRow: Int?
⋮----
init(contentSize: CGSize, surfaceView: Ghostty.SurfaceView) {
⋮----
required init?(coder: NSCoder) {
⋮----
deinit {
⋮----
override var safeAreaInsets: NSEdgeInsets { return NSEdgeInsetsZero }
⋮----
override func layout() {
⋮----
private func synchronizeAppearance() {
let scrollbarConfig = surfaceView.derivedConfig.scrollbar
⋮----
let hasLightBackground = NSColor(surfaceView.derivedConfig.backgroundColor).isLightColor
⋮----
private func synchronizeSurfaceView() {
let visibleRect = scrollView.contentView.documentVisibleRect
⋮----
private func synchronizeCoreSurface() {
⋮----
... (35 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Surface View/SurfaceView_AppKit.swift">
class SurfaceView: OSSurfaceView, Codable, Identifiable {
⋮----
@Published private(set) var title: String = "" {
⋮----
// The progress report (if any)
override var progressReport: Action.ProgressReport? {
⋮----
// Cancel any existing timer
⋮----
// If we have a new progress report, start a timer to remove it after 15 seconds
⋮----
// The currently active key sequence. The sequence is not active if this is empty.
@Published var keySequence: [KeyboardShortcut] = []
⋮----
// The current search state. When non-nil, the search overlay should be shown.
override var searchState: SearchState? {
⋮----
// I'm not a Combine expert so if there is a better way to do this I'm
// all ears. What we're doing here is grabbing the latest needle. If the
// needle is less than 3 chars, we debounce it for a few hundred ms to
// avoid kicking off expensive searches.
⋮----
let action = "search:\(needle)"
⋮----
let action = "end_search"
⋮----
private var searchNeedleCancellable: AnyCancellable?
⋮----
private var accessibilitySelectionCancellable: AnyCancellable?
⋮----
... (689 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Surface View/SurfaceView.swift">
struct SurfaceWrapper: View {
⋮----
@ObservedObject var surfaceView: SurfaceView
⋮----
var isSplit: Bool = false
⋮----
@FocusState private var surfaceFocus: Bool
⋮----
@State private var windowFocus: Bool = true
⋮----
@ObservedObject private var secureInput = SecureInput.shared
⋮----
@EnvironmentObject private var ghostty: Ghostty.App
@Environment(\.ghosttyLastFocusedSurface) private var lastFocusedSurface
⋮----
private var isFocusedSurface: Bool {
⋮----
var body: some View {
let center = NotificationCenter.default
⋮----
let pubBecomeKey = center.publisher(for: NSWindow.didBecomeKeyNotification)
let pubResign = center.publisher(for: NSWindow.didResignKeyNotification)
⋮----
let overlayOpacity = ghostty.config.unfocusedSplitOpacity
⋮----
struct SurfaceRendererUnhealthyView: View {
⋮----
struct SurfaceErrorView: View {
⋮----
struct SurfaceResizeOverlay: View {
... (189 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Surface View/SurfaceView+Image.swift">
var asImage: NSImage? {
⋮----
let image = NSImage(size: bounds.size)
</file>

<file path="macos/Sources/Ghostty/Surface View/SurfaceView+Transferable.swift">
static var transferRepresentation: some TransferRepresentation {
⋮----
let uuid = data.withUnsafeBytes {
⋮----
enum TransferError: Error {
⋮----
static func find(uuid: UUID) -> Self? {
⋮----
static let ghosttySurfaceId = UTType(exportedAs: "com.mitchellh.ghosttySurfaceId")
⋮----
static let ghosttySurfaceId = NSPasteboard.PasteboardType(UTType.ghosttySurfaceId.identifier)
</file>

<file path="macos/Sources/Ghostty/FullscreenMode+Extension.swift">
static func from(ghostty: ghostty_action_fullscreen_e) -> Self? {
</file>

<file path="macos/Sources/Ghostty/Ghostty.Action.swift">
struct Action {}
⋮----
struct ColorChange {
let kind: Kind
let color: Color
⋮----
enum Kind {
⋮----
init(c: ghostty_action_color_change_s) {
⋮----
struct MoveTab {
let amount: Int
⋮----
init(c: ghostty_action_move_tab_s) {
⋮----
struct OpenURL {
⋮----
let url: String
⋮----
init(c: ghostty_action_open_url_s) {
⋮----
let data = Data(bytes: urlCString, count: Int(c.len))
⋮----
struct ProgressReport {
enum State {
⋮----
let state: State
let progress: UInt8?
⋮----
struct Scrollbar {
... (20 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Ghostty.App.swift">
protocol GhosttyAppDelegate: AnyObject {
⋮----
func findSurface(forUUID uuid: UUID) -> Ghostty.SurfaceView?
⋮----
class App: ObservableObject {
enum Readiness: String {
⋮----
weak var delegate: GhosttyAppDelegate?
⋮----
@Published var readiness: Readiness = .loading
⋮----
@Published private(set) var config: Config
⋮----
private var configPath: String?
⋮----
@Published var app: ghostty_app_t? {
⋮----
var needsConfirmQuit: Bool {
⋮----
init(configPath: String? = nil) {
⋮----
var runtime_cfg = ghostty_runtime_config_s(
⋮----
let center = NotificationCenter.default
⋮----
deinit {
⋮----
func appTick() {
⋮----
private static func openConfig(_ app: ghostty_app_t) {
... (313 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Ghostty.ChildExitedMessage.swift">
struct ChildExitedMessage {
enum Level {
⋮----
let text: String
let level: Level
⋮----
init(_ message: ghostty_surface_message_childexited_s, threshold abnormalCommandExitRuntime: Duration) {
var level: Level
⋮----
let measure = Measurement.init(value: Double(message.timetime_ms), unit: UnitDuration.milliseconds)
let formatter = MeasurementFormatter()
</file>

<file path="macos/Sources/Ghostty/Ghostty.ClipboardConfirmationRequest.swift">
enum ClipboardRequest {
⋮----
func text() -> String {
⋮----
static func from(request: ghostty_clipboard_request_e) -> ClipboardRequest? {
⋮----
final class ClipboardConfirmationRequest {
private(set) weak var surface: SurfaceView?
⋮----
let contents: String
⋮----
let kind: ClipboardRequest
⋮----
let canRemember: Bool
⋮----
let previewImage: NSImage?
⋮----
private var completion: ((SurfaceView, Bool, Bool) -> Void)?
⋮----
init(
⋮----
deinit {
⋮----
func complete(remember: Bool = false) {
⋮----
func cancel() {
⋮----
func cancel(from surface: SurfaceView) {
⋮----
private func finish(
... (1 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Ghostty.Command.swift">
struct Command: Sendable {
⋮----
let title: String
⋮----
let description: String
⋮----
let action: String
⋮----
let actionKey: String
⋮----
var isSupported: Bool {
⋮----
static let unsupportedActionKeys: [String] = [
⋮----
init(cValue: ghostty_command_s) {
</file>

<file path="macos/Sources/Ghostty/Ghostty.Config.swift">
class Config: ObservableObject {
⋮----
private(set) var config: ghostty_config_t? {
⋮----
var loaded: Bool { config != nil }
⋮----
var errors: [String] {
⋮----
var diags: [String] = []
let diagsCount = ghostty_config_diagnostics_count(cfg)
⋮----
let diag = ghostty_config_get_diagnostic(cfg, UInt32(i))
let message = String(cString: diag.message)
⋮----
init(config: ghostty_config_t?) {
⋮----
convenience init(at path: String? = nil, finalize: Bool = true) {
⋮----
convenience init(clone config: ghostty_config_t) {
⋮----
func clone(config: ghostty_config_t) {
⋮----
deinit {
⋮----
static func loadConfig(at path: String?, finalize: Bool) -> ghostty_config_t? {
⋮----
@MainActor func keyboardShortcut(for action: String) -> KeyboardShortcut? {
⋮----
func keybindTrigger(for action: String) -> ghostty_input_trigger_s? {
⋮----
... (344 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Ghostty.ConfigTypes.swift">
struct ConfigPath: Sendable {
let path: String
let optional: Bool
⋮----
enum MacOSIcon: String, Sendable {
⋮----
var assetName: String? {
⋮----
enum MacOSIconFrame: String, Codable {
</file>

<file path="macos/Sources/Ghostty/Ghostty.Error.swift">
enum Error: Swift.Error, CustomLocalizedStringResourceConvertible {
⋮----
var localizedStringResource: LocalizedStringResource {
</file>

<file path="macos/Sources/Ghostty/Ghostty.Event.swift">
struct ComparableKeyEvent: Equatable {
let keyCode: UInt16
let flags: NSEvent.ModifierFlags
⋮----
init(event: NSEvent) {
</file>

<file path="macos/Sources/Ghostty/Ghostty.Input.swift">
struct Input {}
⋮----
@MainActor static func keyboardShortcut(for trigger: ghostty_input_trigger_s) -> KeyboardShortcut? {
let modifierFlags = Self.eventModifierFlags(mods: trigger.mods)
let key: KeyEquivalent
⋮----
let physical = trigger.key.physical
⋮----
static func eventModifierFlags(mods: ghostty_input_mods_e) -> NSEvent.ModifierFlags {
var flags = NSEvent.ModifierFlags(rawValue: 0)
⋮----
static func ghosttyMods(_ flags: NSEvent.ModifierFlags) -> ghostty_input_mods_e {
var mods: UInt32 = GHOSTTY_MODS_NONE.rawValue
⋮----
let rawFlags = flags.rawValue
⋮----
static let keyToEquivalent: [ghostty_input_key_e: KeyEquivalent] = [
⋮----
private static let writingSystemKeyRange =
⋮----
struct BindingFlags: OptionSet, Sendable {
let rawValue: UInt32
⋮----
static let consumed = BindingFlags(rawValue: GHOSTTY_BINDING_FLAGS_CONSUMED.rawValue)
static let all = BindingFlags(rawValue: GHOSTTY_BINDING_FLAGS_ALL.rawValue)
static let global = BindingFlags(rawValue: GHOSTTY_BINDING_FLAGS_GLOBAL.rawValue)
static let performable = BindingFlags(rawValue: GHOSTTY_BINDING_FLAGS_PERFORMABLE.rawValue)
⋮----
init(rawValue: UInt32) {
⋮----
... (122 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Ghostty.Inspector.swift">
final class Inspector: Sendable {
⋮----
nonisolated(unsafe) private let inspector: ghostty_inspector_t
⋮----
var unsafeCValue: ghostty_inspector_t {
⋮----
init(cInspector: ghostty_inspector_t) {
⋮----
func setFocus(_ focused: Bool) {
⋮----
func setContentScale(x: Double, y: Double) {
⋮----
func setSize(width: UInt32, height: UInt32) {
⋮----
func mouseButton(
⋮----
func mousePos(x: Double, y: Double) {
⋮----
func mouseScroll(x: Double, y: Double, mods: ghostty_input_scroll_mods_t) {
⋮----
func key(
⋮----
func text(_ text: String) {
⋮----
func metalInit(device: MTLDevice) -> Bool {
let devicePtr = Unmanaged.passRetained(device).toOpaque()
⋮----
func metalRender(
</file>

<file path="macos/Sources/Ghostty/Ghostty.MenuShortcutManager.swift">
class MenuShortcutManager {
⋮----
private var menuItemsByShortcut: [MenuShortcutKey: Weak<NSMenuItem>] = [:]
⋮----
func reset() {
⋮----
func syncMenuShortcut(_ config: Ghostty.Config, action: String?, menuItem: NSMenuItem?) {
⋮----
func performGhosttyBindingMenuKeyEquivalent(with event: NSEvent) -> Bool {
⋮----
let physicalKey = MenuShortcutKey(
⋮----
private func performMenuItem(for key: MenuShortcutKey) -> Bool? {
⋮----
let index = parentMenu.index(of: item)
⋮----
func updateMenuShortcut(_ config: Ghostty.Config, action: String?, menuItem menu: NSMenuItem) -> Bool {
⋮----
let isPhysical = trigger.tag == GHOSTTY_TRIGGER_PHYSICAL
let physicalKeyCode = isPhysical ? Ghostty.Input.Key(cKey: trigger.key.physical)?.keyCode : nil
⋮----
struct MenuShortcutKey: Hashable {
private enum Identity: Hashable {
⋮----
private static let shortcutModifiers: NSEvent.ModifierFlags = [.shift, .control, .option, .command]
⋮----
private let identity: Identity
private let modifiersRawValue: UInt
⋮----
var modifierFlags: NSEvent.ModifierFlags {
... (13 lines truncated)
</file>

<file path="macos/Sources/Ghostty/Ghostty.Shell.swift">
enum Shell {
⋮----
private static let escapeCharacters = "\\ ()[]{}<>\"'`!#$&;|*?\t"
⋮----
static func escape(_ str: String) -> String {
var result = str
⋮----
private static let quoteUnsafe = /[^\w@%+=:,.\/-]/
⋮----
static func quote(_ str: String) -> String {
</file>

<file path="macos/Sources/Ghostty/Ghostty.Surface.swift">
final class Surface: Sendable {
⋮----
nonisolated(unsafe) private let surface: ghostty_surface_t
⋮----
var unsafeCValue: ghostty_surface_t {
⋮----
init(cSurface: ghostty_surface_t) {
⋮----
deinit {
⋮----
let surface = self.surface
⋮----
func sendText(_ text: String) {
let len = text.utf8CString.count
⋮----
func keyTranslationMods(_ mods: Input.Mods) -> Input.Mods {
⋮----
func sendKeyEvent(_ event: Input.KeyEvent) {
⋮----
func keyIsBinding(_ event: ghostty_input_key_s) -> Input.BindingFlags? {
var flags = ghostty_binding_flags_e(0)
⋮----
func keyIsBinding(_ event: Input.KeyEvent) -> Input.BindingFlags? {
⋮----
var mouseCaptured: Bool {
⋮----
var foregroundPID: Int? {
let pid = ghostty_surface_foreground_pid(surface)
⋮----
var ttyName: String? {
... (11 lines truncated)
</file>

<file path="macos/Sources/Ghostty/GhosttyDelegate.swift">
protocol Delegate {
⋮----
func ghosttySurface(id: UUID) -> SurfaceView?
</file>

<file path="macos/Sources/Ghostty/GhosttyPackage.swift">
static let userNotificationCategory = "com.mitchellh.ghostty.userNotification"
⋮----
static let userNotificationActionShow = "com.mitchellh.ghostty.userNotification.Show"
⋮----
struct Info {
var mode: ghostty_build_mode_e
var version: String
⋮----
static var info: Info {
let raw = ghostty_info()
let version = NSString(
⋮----
enum LaunchSource: String {
⋮----
static var launchSource: LaunchSource {
⋮----
class AllocatedString {
private let cString: ghostty_string_s
⋮----
init(_ c: ghostty_string_s) {
⋮----
var string: String {
⋮----
let data = Data(bytes: ptr, count: Int(cString.len))
⋮----
deinit {
⋮----
enum SetFloatWIndow {
⋮----
static func from(_ c: ghostty_action_float_window_e) -> Self? {
... (129 lines truncated)
</file>

<file path="macos/Sources/Ghostty/GhosttyPackageMeta.swift">
enum Ghostty {
⋮----
static let logger = Logger(
⋮----
struct Notification {}
</file>

<file path="macos/Sources/Ghostty/NSEvent+Extension.swift">
func ghosttyKeyEvent(
⋮----
var key_ev: ghostty_input_key_s = .init()
⋮----
var ghosttyCharacters: String? {
</file>

<file path="macos/Sources/Helpers/Extensions/Array+Extension.swift">
subscript(safe index: Int) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
⋮----
func indexWrapping(before i: Int) -> Int {
⋮----
func indexWrapping(after i: Int) -> Int {
⋮----
func withCStrings<T>(_ body: ([UnsafePointer<Int8>?]) throws -> T) rethrows -> T {
⋮----
func helper(index: Int, accumulated: [UnsafePointer<Int8>?], body: ([UnsafePointer<Int8>?]) throws -> T) rethrows -> T {
⋮----
var newAccumulated = accumulated
</file>

<file path="macos/Sources/Helpers/Extensions/Double+Extension.swift">
func clamped(to range: ClosedRange<Double>) -> Double {
</file>

<file path="macos/Sources/Helpers/Extensions/Duration+Extension.swift">
var timeInterval: TimeInterval {
</file>

<file path="macos/Sources/Helpers/Extensions/EventModifiers+Extension.swift">
init(nsFlags: NSEvent.ModifierFlags) {
var result: SwiftUI.EventModifiers = []
⋮----
init(swiftUIFlags: SwiftUI.EventModifiers) {
var result: NSEvent.ModifierFlags = []
</file>

<file path="macos/Sources/Helpers/Extensions/FileHandle+Extension.swift">
public func write(_ string: String) {
let data = Data(string.utf8)
</file>

<file path="macos/Sources/Helpers/Extensions/KeyboardShortcut+Extension.swift">
public var keyList: [String] {
var result: [String] = []
⋮----
let keyString: String
⋮----
public var description: String {
</file>

<file path="macos/Sources/Helpers/Extensions/NSAlert+Extension.swift">
static func reviewWindowsAlert(
⋮----
let alert = NSAlert()
</file>

<file path="macos/Sources/Helpers/Extensions/NSAppearance+Extension.swift">
var isDark: Bool {
⋮----
convenience init?(ghosttyConfig config: Ghostty.Config) {
⋮----
let color = NSColor(config.backgroundColor)
</file>

<file path="macos/Sources/Helpers/Extensions/NSAppleEventDescriptor+Extension.swift">
var senderBundleIdentifier: String? {
⋮----
var expectsActivation: Bool {
</file>

<file path="macos/Sources/Helpers/Extensions/NSApplication+Extension.swift">
private static var presentationOptionCounts: [NSApplication.PresentationOptions.Element: UInt] = [:]
⋮----
func acquirePresentationOption(_ option: NSApplication.PresentationOptions.Element) {
⋮----
func releasePresentationOption(_ option: NSApplication.PresentationOptions.Element) {
⋮----
public func hash(into hasher: inout Hasher) {
⋮----
var isFrontmost: Bool {
</file>

<file path="macos/Sources/Helpers/Extensions/NSColor+Extension.swift">
private static let appleColorList: NSColorList? = NSColorList(named: "Apple")
⋮----
convenience init?(named name: String) {
⋮----
static var colorNames: [String] {
⋮----
func distance(to other: NSColor) -> Double {
⋮----
let dr = a.redComponent - b.redComponent
let dg = a.greenComponent - b.greenComponent
let db = a.blueComponent - b.blueComponent
</file>

<file path="macos/Sources/Helpers/Extensions/NSImage+Extension.swift">
static func combine(images: [NSImage], blendingModes: [CGBlendMode]) -> NSImage? {
⋮----
let size = images.first!.size
⋮----
let blendMode = blendingModes[index]
⋮----
func gradient(colors: [NSColor]) -> NSImage? {
let resultImage = NSImage(size: size)
⋮----
func tint(color: NSColor) -> NSImage? {
⋮----
let newImage = NSImage(size: size)
</file>

<file path="macos/Sources/Helpers/Extensions/NSMenu+Extension.swift">
func insertItem(_ item: NSMenuItem, after action: Selector) -> UInt? {
⋮----
let insertionIndex = idx + 1
⋮----
func removeItems(withIdentifiers identifiers: Set<NSUserInterfaceItemIdentifier>) {
</file>

<file path="macos/Sources/Helpers/Extensions/NSMenuItem+Extension.swift">
func setImageIfDesired(systemSymbolName symbol: String) {
</file>

<file path="macos/Sources/Helpers/Extensions/NSPasteboard+Extension.swift">
init?(mimeType: String) {
⋮----
static var ghosttySelection: NSPasteboard = {
⋮----
func getOpinionatedStringContents() -> String? {
let strings = (pasteboardItems ?? []).compactMap { item in
⋮----
private var ghosttyFileURLs: [URL] {
⋮----
func ghosttyData(forMime mime: String) -> Data? {
⋮----
let urls = ghosttyFileURLs
⋮----
func ghosttyAvailableMimes() -> [String] {
var result: [String] = []
var seen = Set<String>()
let availableTypes = types ?? []
let mimeType: (NSPasteboard.PasteboardType) -> String? = { type in
⋮----
let hasFileURL = availableTypes.contains(.fileURL)
let hasPlainText = hasFileURL || availableTypes.contains { type in
⋮----
static func ghostty(_ clipboard: ghostty_clipboard_e) -> NSPasteboard? {
</file>

<file path="macos/Sources/Helpers/Extensions/NSScreen+Extension.swift">
var displayID: UInt32? {
⋮----
var displayUUID: UUID? {
⋮----
var hasDock: Bool {
⋮----
let menuHeight = NSApp.mainMenu?.menuBarHeight ?? 0
let notchInset: CGFloat = safeAreaInsets.top
let boundaryAreaPadding = 5.0
⋮----
var hasNotch: Bool {
⋮----
func origin(fromTopLeftOffsetX x: CGFloat, offsetY y: CGFloat, windowSize: CGSize) -> CGPoint {
let vf = visibleFrame
⋮----
let originX = vf.minX + x
let originY = vf.maxY - y - windowSize.height
</file>

<file path="macos/Sources/Helpers/Extensions/NSView+Extension.swift">
var isInResponderChain: Bool {
var responder = window?.firstResponder
⋮----
var isFirstResponder: Bool {
⋮----
func screenshot() -> NSImage? {
⋮----
let image = NSImage(size: bounds.size)
⋮----
func screenshot() -> Image? {
⋮----
var rootView: NSView {
var root: NSView = self
⋮----
func contains(_ view: NSView) -> Bool {
⋮----
func contains(className name: String) -> Bool {
⋮----
func firstSuperview(withClassName name: String) -> NSView? {
⋮----
func firstDescendant(withClassName name: String) -> NSView? {
⋮----
func descendants(withClassName name: String) -> [NSView] {
var result = [NSView]()
⋮----
func firstDescendant(withID id: String) -> NSView? {
⋮----
func firstViewFromRoot(withClassName name: String) -> NSView? {
let root = rootView
⋮----
... (24 lines truncated)
</file>

<file path="macos/Sources/Helpers/Extensions/NSWindow+Extension.swift">
var cgWindowId: CGWindowID? {
⋮----
func constrainToScreen() {
⋮----
let visibleFrame = screen.visibleFrame
var windowFrame = frame
⋮----
var isFirstWindowInTabGroup: Bool {
⋮----
func addTabbedWindowSafely(
⋮----
var error: NSError?
let success = GhosttyAddTabbedWindowSafely(self, child, ordered.rawValue, &error)
⋮----
func showWindowSafely(_ sender: Any?) -> Bool {
⋮----
let success = GhosttyShowWindowSafely(self, sender, &error)
⋮----
var titlebarView: NSView? {
⋮----
var tabBarView: NSView? {
⋮----
func tabButtonsInVisualOrder() -> [NSView] {
⋮----
func tabButtonHit(atScreenPoint screenPoint: NSPoint) -> (index: Int, tabButton: NSView)? {
⋮----
let locationInTabBarWindow = tabBarWindow.convertPoint(fromScreen: screenPoint)
let locationInTabBar = tabBarView.convert(locationInTabBarWindow, from: nil)
⋮----
let locationInTabButton = tabButton.convert(locationInTabBarWindow, from: nil)
... (3 lines truncated)
</file>

<file path="macos/Sources/Helpers/Extensions/NSWorkspace+Extension.swift">
var defaultTextEditor: URL? {
⋮----
var defaultTerminal: URL? {
⋮----
func defaultApplicationURL(forContentType contentType: String) -> URL? {
⋮----
func defaultApplicationURL(forExtension ext: String) -> URL? {
</file>

<file path="macos/Sources/Helpers/Extensions/ObjectIdentifier+Extension.swift">
var hexString: String {
</file>

<file path="macos/Sources/Helpers/Extensions/Optional+Extension.swift">
func withCString<T>(_ body: (UnsafePointer<Int8>?) throws -> T) rethrows -> T {
</file>

<file path="macos/Sources/Helpers/Extensions/OSColor+Extension.swift">
var isLightColor: Bool {
⋮----
var luminance: Double {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
⋮----
var hexString: String? {
⋮----
let red = Int(rgb.redComponent * 255)
let green = Int(rgb.greenComponent * 255)
let blue = Int(rgb.blueComponent * 255)
⋮----
convenience init?(hex: String) {
var cleanedHex = hex.trimmingCharacters(in: .whitespacesAndNewlines)
⋮----
let scanner = Scanner(string: cleanedHex)
var hexNumber: UInt64 = 0
⋮----
let red, green, blue, alpha: CGFloat
⋮----
func darken(by amount: CGFloat) -> NSColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
⋮----
convenience init(ghostty: ghostty_config_color_s) {
let red = Double(ghostty.r) / 255
let green = Double(ghostty.g) / 255
let blue = Double(ghostty.b) / 255
</file>

<file path="macos/Sources/Helpers/Extensions/OSPasteboard+Extension.swift">
@MainActor static let find = NSPasteboard(name: .find)
⋮----
@MainActor var string: String? {
</file>

<file path="macos/Sources/Helpers/Extensions/String+Extension.swift">
var startsWithASCIIControlCharacter: Bool {
⋮----
var keyEventText: String? {
⋮----
func truncate(length: Int, trailing: String = "…") -> String {
let maxLength = length - trailing.count
⋮----
func temporaryFile(_ filename: String = "temp") -> URL {
let url = FileManager.default.temporaryDirectory
⋮----
let string = self
⋮----
var abbreviatedPath: String {
let home = FileManager.default.homeDirectoryForCurrentUser.path
⋮----
var fourCharCode: UInt32 {
⋮----
var result: UInt32 = 0
</file>

<file path="macos/Sources/Helpers/Extensions/Transferable+Extension.swift">
func pasteboardItem() -> NSPasteboardItem? {
let itemProvider = NSItemProvider()
⋮----
let types = itemProvider.registeredTypeIdentifiers.compactMap { UTType($0) }
⋮----
let item = NSPasteboardItem()
let dataProvider = TransferableDataProvider(itemProvider: itemProvider)
let pasteboardTypes = types.map { NSPasteboard.PasteboardType($0.identifier) }
⋮----
private final class TransferableDataProvider: NSObject, NSPasteboardItemDataProvider {
private let itemProvider: NSItemProvider
⋮----
init(itemProvider: NSItemProvider) {
⋮----
func pasteboard(
⋮----
let semaphore = DispatchSemaphore(value: 0)
⋮----
var result: Data?
</file>

<file path="macos/Sources/Helpers/Extensions/UndoManager+Extension.swift">
var isUndoingOrRedoing: Bool {
⋮----
func disableUndoRegistration(handler: () -> Void) {
</file>

<file path="macos/Sources/Helpers/Extensions/URL+Extension.swift">
var pathWithoutTrailingSlash: String {
</file>

<file path="macos/Sources/Helpers/Extensions/UserDefaults+Extension.swift">
static var ghosttySuite: String? {
⋮----
static var ghostty: UserDefaults {
</file>

<file path="macos/Sources/Helpers/Extensions/UUID+Extension.swift">
init?(_ cfuuid: CFUUID) {
</file>

<file path="macos/Sources/Helpers/Extensions/View+Extension.swift">
func innerShadow<S: Shape, ST: ShapeStyle>(
⋮----
func pointerStyleFromCursor(_ cursor: NSCursor) -> some View {
</file>

<file path="macos/Sources/Helpers/Private/CGS.swift">
private func CGSMainConnectionID() -> CGSConnectionID
⋮----
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]
⋮----
struct CGSSpace: Hashable, CustomStringConvertible {
let rawValue: CGSSpaceID
⋮----
var description: String {
⋮----
static func active() -> CGSSpace {
let space = CGSGetActiveSpace(CGSMainConnectionID())
⋮----
static func list(for windowID: CGWindowID, mask: CGSSpaceMask = .allSpaces) -> [CGSSpace] {
⋮----
enum CGSSpaceType: UInt32 {
⋮----
var type: CGSSpaceType {
</file>

<file path="macos/Sources/Helpers/Private/Dock.swift">

</file>

<file path="macos/Sources/Helpers/AppInfo.swift">
func isRunningInXcode() -> Bool {
</file>

<file path="macos/Sources/Helpers/Backport.swift">
struct Backport<Content> {
let content: Content
⋮----
var backport: Backport<Self> { Backport(content: self) }
⋮----
enum BackportKeyPressResult {
⋮----
func pointerVisibility(_ v: BackportVisibility) -> some View {
⋮----
func pointerStyle(_ style: BackportPointerStyle?) -> some View {
⋮----
func onKeyPress(_ key: KeyEquivalent, action: @escaping (EventModifiers) -> BackportKeyPressResult) -> some View {
⋮----
enum BackportVisibility {
⋮----
var official: Visibility {
⋮----
enum BackportPointerStyle {
⋮----
var official: PointerStyle {
⋮----
enum BackportGlass {
⋮----
var official: Glass {
⋮----
struct BackportSelectionTextField: View {
private let titleKey: LocalizedStringKey
@Binding private var text: String
@Binding private var textSelection: Range<String.Index>?
⋮----
... (4 lines truncated)
</file>

<file path="macos/Sources/Helpers/CodableBridge.swift">
class CodableBridge<Wrapped: Codable>: NSObject, NSSecureCoding {
let value: Wrapped
init(_ value: Wrapped) { self.value = value }
⋮----
static var supportsSecureCoding: Bool { return true }
⋮----
required init?(coder aDecoder: NSCoder) {
⋮----
func encode(with aCoder: NSCoder) {
let archiver = NSKeyedArchiver(requiringSecureCoding: true)
</file>

<file path="macos/Sources/Helpers/Cursor.swift">
class Cursor {
private static var counter: UInt = 0
⋮----
static var isVisible: Bool {
⋮----
static func hide() {
⋮----
static func unhide() -> Bool {
⋮----
static func unhideCompletely() -> UInt {
let counter = self.counter
⋮----
enum CursorStyle {
⋮----
var cursor: NSCursor {
</file>

<file path="macos/Sources/Helpers/ExpiringUndoManager.swift">
class ExpiringUndoManager: UndoManager {
⋮----
private lazy var expiringTargets: Set<ExpiringTarget> = []
⋮----
func registerUndo<TargetType: AnyObject>(
⋮----
let expiringTarget = ExpiringTarget(
⋮----
override func removeAllActions() {
⋮----
override func removeAllActions(withTarget target: Any) {
⋮----
private class ExpiringTarget {
⋮----
private(set) weak var target: AnyObject?
⋮----
private var timer: Timer?
⋮----
private weak var undoManager: UndoManager?
⋮----
init(_ target: AnyObject? = nil, expiresAfter duration: Duration, in undoManager: UndoManager) {
⋮----
func expire() {
⋮----
deinit {
⋮----
func hash(into hasher: inout Hasher) {
</file>

<file path="macos/Sources/Helpers/Fullscreen.swift">
enum FullscreenMode: String, Codable {
⋮----
func style(for window: NSWindow) -> FullscreenStyle? {
⋮----
protocol FullscreenStyle {
⋮----
init?(_ window: NSWindow)
func enter()
func exit()
⋮----
protocol FullscreenDelegate: AnyObject {
⋮----
func fullscreenDidChange()
⋮----
class FullscreenBase {
let window: NSWindow
weak var delegate: FullscreenDelegate?
⋮----
required init?(_ window: NSWindow) {
⋮----
let center = NotificationCenter.default
⋮----
deinit {
⋮----
@objc private func didEnterFullScreenNotification(_ notification: Notification) {
⋮----
@objc private func didExitFullScreenNotification(_ notification: Notification) {
⋮----
class NativeFullscreen: FullscreenBase, FullscreenStyle {
var fullscreenMode: FullscreenMode { .native }
... (68 lines truncated)
</file>

<file path="macos/Sources/Helpers/KeyboardLayout.swift">
class KeyboardLayout {
⋮----
static var id: String? {
⋮----
let sourceId = unsafeBitCast(sourceIdPointer, to: CFString.self)
⋮----
@MainActor static func character(
</file>

<file path="macos/Sources/Helpers/LastWindowPosition.swift">
class LastWindowPosition {
static let shared = LastWindowPosition()
⋮----
private let positionKey = "NSWindowLastPosition"
⋮----
func save(_ window: NSWindow?) -> Bool {
⋮----
let frame = window.frame
let rect = [frame.origin.x, frame.origin.y, frame.size.width, frame.size.height]
⋮----
func restore(_ window: NSWindow, origin restoreOrigin: Bool = true, size restoreSize: Bool = true) -> Bool {
⋮----
let lastPosition = CGPoint(x: values[0], y: values[1])
⋮----
let visibleFrame = screen.visibleFrame
⋮----
var newFrame = window.frame
</file>

<file path="macos/Sources/Helpers/MetalView.swift">
struct MetalView<V: MTKView>: View {
@State private var metalView = V()
⋮----
var body: some View {
⋮----
private struct MetalViewRepresentable<V: MTKView>: NSViewRepresentable {
@Binding var metalView: V
⋮----
func makeNSView(context: Context) -> some NSView {
⋮----
func updateNSView(_ view: NSViewType, context: Context) {
⋮----
func updateMetalView() {
</file>

<file path="macos/Sources/Helpers/NonDraggableHostingView.swift">
class NonDraggableHostingView<Content: View>: NSHostingView<Content> {
override var mouseDownCanMoveWindow: Bool { false }
</file>

<file path="macos/Sources/Helpers/ObjCExceptionCatcher.h">
FOUNDATION_EXPORT BOOL GhosttyAddTabbedWindowSafely(
⋮----
FOUNDATION_EXPORT BOOL GhosttyShowWindowSafely(
</file>

<file path="macos/Sources/Helpers/ObjCExceptionCatcher.m">
#import "ObjCExceptionCatcher.h"

#import <AppKit/AppKit.h>

static NSError *GhosttyErrorFromException(NSException *exception, NSInteger code) {
    NSString *reason = exception.reason ?: @"Unknown Objective-C exception";
    return [NSError errorWithDomain:@"Ghostty.ObjCException"
                               code:code
                           userInfo:@{
                               NSLocalizedDescriptionKey: reason,
                               @"exception_name": exception.name,
                           }];
}

BOOL GhosttyAddTabbedWindowSafely(
    id parent,
    id child,
    NSInteger ordered,
    NSError * _Nullable * _Nullable error
) {
    // AppKit occasionally throws NSException while adding tabbed windows,
    // in particular when creating tabs from the tab overview page since some
    // macOS update recently in 2025/2026 (unclear).
    //
    // We must catch it in Objective-C; letting this cross into Swift is unsafe.
    @try {
        [((NSWindow *)parent) addTabbedWindow:(NSWindow *)child ordered:(NSWindowOrderingMode)ordered];
        return YES;
    } @catch (NSException *exception) {
        if (error != NULL) {
... (27 lines truncated)
</file>

<file path="macos/Sources/Helpers/PermissionRequest.swift">
class PermissionRequest {
⋮----
enum AllowDuration {
⋮----
static func show(
⋮----
let alert = NSAlert()
⋮----
var checkbox: NSButton?
⋮----
let checkboxTitle = formatRememberText(for: rememberDuration)
⋮----
let response = alert.runModal()
⋮----
private static func handleResponse(
⋮----
let result: Bool
⋮----
private static func getStoredResult(for key: String) -> Bool? {
let userDefaults = UserDefaults.ghostty
⋮----
private static func storeResult(_ result: Bool, for key: String, duration: Duration) {
let expiryDate = Date().addingTimeInterval(duration.timeInterval)
let storedPermission = StoredPermission(result: result, expiry: expiryDate)
⋮----
private static func formatRememberText(for duration: Duration) -> String {
let seconds = duration.timeInterval
⋮----
let minutes = Int(seconds / 60)
⋮----
... (18 lines truncated)
</file>

<file path="macos/Sources/Helpers/TabGroupCloseCoordinator.swift">
class TabGroupCloseCoordinator {
⋮----
enum CloseScope {
⋮----
protocol Controller {
⋮----
private weak var tabGroup: NSWindowTabGroup?
⋮----
private var closeRequests: [ObjectIdentifier: Callback] = [:]
⋮----
private var debounceTimer: Timer?
⋮----
deinit {
⋮----
func windowShouldClose(
⋮----
let coordinator = firstController.tabGroupCloseCoordinator
⋮----
let allWindows = Set(tabGroup.windows.map { ObjectIdentifier($0) })
⋮----
private func trigger(_ scope: CloseScope) {
</file>

<file path="macos/Sources/Helpers/TabTitleEditor.swift">
protocol TabTitleEditorDelegate: AnyObject {
⋮----
func tabTitleEditor(
⋮----
final class TabTitleEditor: NSObject, NSTextFieldDelegate {
⋮----
private weak var hostWindow: NSWindow?
⋮----
private weak var delegate: TabTitleEditorDelegate?
⋮----
private var eventMonitor: Any?
⋮----
private weak var inlineTitleEditor: NSTextField?
⋮----
private weak var inlineTitleTargetWindow: NSWindow?
⋮----
private var previousTabState: TabUIState?
⋮----
private var pendingEditWorkItem: DispatchWorkItem?
⋮----
init(hostWindow: NSWindow, delegate: TabTitleEditorDelegate) {
⋮----
deinit {
⋮----
func handleMouseDown(_ event: NSEvent) -> Bool {
⋮----
let sourceWindow = event.window ?? hostWindow
⋮----
let locationInScreen = sourceWindow.convertPoint(toScreen: event.locationInWindow)
⋮----
... (53 lines truncated)
</file>

<file path="macos/Sources/Helpers/UntrustedURL.swift">
struct UntrustedURL: Equatable {
enum DenialReason: Equatable {
⋮----
var message: String {
⋮----
enum Decision: Equatable {
⋮----
let string: String
⋮----
init(_ string: String) {
⋮----
var decision: Decision {
⋮----
var displayString: String {
let normalized: String
⋮----
var result = String()
⋮----
func fileDecision(for url: URL) -> Decision {
⋮----
let canonicalURL = url.standardizedFileURL.resolvingSymlinksInPath()
let resourceValues: URLResourceValues
⋮----
static func isUnsafeFile(
⋮----
static func isUnsafeCharacter(_ scalar: Unicode.Scalar) -> Bool {
⋮----
static let unsafePathExtensions: Set<String> = [
⋮----
static let unsafeContentTypes: [UTType] = [
... (1 lines truncated)
</file>

<file path="macos/Sources/Helpers/UntrustedURLAlert.swift">
enum UntrustedURLAlert {
static func presentConfirmation(for url: URL, displayString: String) {
⋮----
let workspace = NSWorkspace.shared
let handler = workspace.urlForApplication(toOpen: url)
⋮----
let alert = NSAlert()
⋮----
static func presentBlock(
⋮----
let pasteboard = NSPasteboard.general
⋮----
private static func deferPresentation(_ action: @escaping () -> Void) {
⋮----
private static func present(
⋮----
private static func targetView(_ target: String) -> NSView {
let scrollView = NSScrollView(frame: NSRect(
⋮----
let textView = NSTextView(frame: scrollView.contentView.bounds)
</file>

<file path="macos/Sources/Helpers/URLHoverBanner.swift">
struct URLHoverBanner: View {
⋮----
@State private var isHoveringURLLeft: Bool = false
let padding: CGFloat = 5
let cornerRadius: CGFloat = 9
let url: String
⋮----
private var displayedURL: String {
⋮----
var body: some View {
</file>

<file path="macos/Sources/Helpers/VibrantLayer.h">
VibrantLayerTypeLight,
VibrantLayerTypeDark
</file>

<file path="macos/Sources/Helpers/VibrantLayer.m">
#import "VibrantLayer.h"

@interface VibrantLayer()

@property (nonatomic) VibrantLayerType type;

@end

@implementation VibrantLayer

- (id)initForAppearance:(VibrantLayerType)type {
    self = [super init];
    if (self) {
        _type = type;
    }
    return self;
}

- (id)compositingFilter {
    if (self.type == VibrantLayerTypeLight) {
        return @"plusD";
    } else {
        return @"plusL";
    }
}

@end
</file>

<file path="macos/Sources/Helpers/Weak.swift">
class Weak<T: AnyObject> {
weak var value: T?
⋮----
init(_ value: T? = nil) {
</file>

<file path="macos/AGENTS.md">
# macOS Ghostty Application

- Use `swiftlint` for formatting and linting Swift code.
- If code outside of `macos/` directory is modified, use
  `zig build -Demit-macos-app=false` before building the macOS app to update
  the underlying Ghostty library.
- Use `macos/build.nu` to build the macOS app, do not use `zig build`
  (except to build the underlying library as mentioned above).
  - Build: `macos/build.nu [--scheme Ghostty] [--configuration Debug] [--action build]`
  - Output: `macos/build/<configuration>/Ghostty.app` (e.g. `macos/build/Debug/Ghostty.app`)
- Run unit tests directly with `macos/build.nu --action test`

## AppleScript

- The AppleScript scripting definition is in `macos/Ghostty.sdef`.
- Guard AppleScript entry points and object accessors with the
  `macos-applescript` configuration (use `NSApp.isAppleScriptEnabled`
  and `NSApp.validateScript(command:)` where applicable).
- In `macos/Ghostty.sdef`, keep top-level definitions in this order:
  1. Classes
  2. Records
  3. Enums
  4. Commands
- Test AppleScript support:
  (1) Build with `macos/build.nu`
  (2) Launch and activate the app via osascript using the absolute path
      to the built app bundle:
      `osascript -e 'tell application "<absolute path to build/Debug/Ghostty.app>" to activate'`
  (3) Wait a few seconds for the app to fully launch and open a terminal.
  (4) Run test scripts with `osascript`, always targeting the app by
... (5 lines truncated)
</file>

<file path="macos/build.nu">
#!/usr/bin/env nu

# Build the macOS Ghostty app using xcodebuild with a clean environment
# to avoid Nix shell interference (NIX_LDFLAGS, NIX_CFLAGS_COMPILE, etc.).

def main [
    --scheme: string = "Ghostty"       # Xcode scheme (Ghostty, DockTilePlugin)
    --configuration: string = "Debug"  # Build configuration (Debug, Release, ReleaseLocal)
    --action: string = "build"         # xcodebuild action (build, test, clean, etc.)
] {
    let project = ($env.FILE_PWD | path join "Ghostty.xcodeproj")
    let build_dir = ($env.FILE_PWD | path join "build")

    # Skip UI tests for CLI-based invocations because it requires
    # special permissions.
    let skip_testing = if $action == "test" {
        [-skip-testing GhosttyUITests]
    } else {
        []
    }

    (^env -i
        $"HOME=($env.HOME)"
        "PATH=/usr/bin:/bin:/usr/sbin:/sbin"
        xcodebuild
        -project $project
        -scheme $scheme
        -configuration $configuration
        $"SYMROOT=($build_dir)"
        ...$skip_testing
... (3 lines truncated)
</file>

<file path="macos/Ghostty.entitlements">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>com.apple.security.automation.apple-events</key>
	<true/>
	<key>com.apple.security.device.audio-input</key>
	<true/>
	<key>com.apple.security.device.camera</key>
	<true/>
	<key>com.apple.security.personal-information.addressbook</key>
	<true/>
	<key>com.apple.security.personal-information.calendars</key>
	<true/>
	<key>com.apple.security.personal-information.location</key>
	<true/>
	<key>com.apple.security.personal-information.photos-library</key>
	<true/>
</dict>
</plist>
</file>

<file path="macos/Ghostty.sdef">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "file://localhost/System/Library/DTDs/sdef.dtd">

<dictionary title="Ghostty Scripting Dictionary">
  <suite name="Ghostty Suite" code="Ghst" description="Ghostty scripting support.">
    <class name="application" code="capp" description="The Ghostty application.">
      <cocoa class="NSApplication"/>
      <property name="name" code="pnam" type="text" access="r" description="The name of the application."/>
      <property name="frontmost" code="pisf" type="boolean" access="r" description="Is this the active application?">
        <cocoa key="isActive"/>
      </property>
      <property name="front window" code="GFWn" type="window" access="r" description="The frontmost Ghostty window.">
        <cocoa key="frontWindow"/>
      </property>
      <property name="version" code="vers" type="text" access="r" description="The version number of the application."/>
      <responds-to command="perform action">
        <cocoa method="handlePerformActionScriptCommand:"/>
      </responds-to>
      <responds-to command="new window">
        <cocoa method="handleNewWindowScriptCommand:"/>
      </responds-to>
      <responds-to command="new tab">
        <cocoa method="handleNewTabScriptCommand:"/>
      </responds-to>
      <responds-to command="new surface configuration">
        <cocoa method="handleNewSurfaceConfigurationScriptCommand:"/>
      </responds-to>
      <responds-to command="quit">
        <cocoa method="handleQuitScriptCommand:"/>
      </responds-to>
... (291 lines truncated)
</file>

<file path="macos/Ghostty.xctestplan">
{
  "configurations" : [
    {
      "id" : "22895D97-CB9E-4452-A6AA-702CC0152032",
      "name" : "Test Scheme Action",
      "options" : {

      }
    }
  ],
  "defaultOptions" : {
    "commandLineArgumentEntries" : [
      {
        "argument" : "-NS🐞 YES"
      }
    ],
    "environmentVariableEntries" : [
      {
        "key" : "GHOSTTY_CONFIG_PATH",
        "value" : "\/tmp\/Ghostty\/testing_config.ghostty"
      }
    ],
    "performanceAntipatternCheckerEnabled" : true,
    "targetForVariableExpansion" : {
      "containerPath" : "container:Ghostty.xcodeproj",
      "identifier" : "A5B30530299BEAAA0047F10C",
      "name" : "Ghostty"
    }
  },
  "testTargets" : [
... (20 lines truncated)
</file>

<file path="macos/GhosttyDebug.entitlements">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>com.apple.security.automation.apple-events</key>
	<true/>
	<key>com.apple.security.cs.disable-library-validation</key>
	<true/>
	<key>com.apple.security.device.audio-input</key>
	<true/>
	<key>com.apple.security.device.camera</key>
	<true/>
	<key>com.apple.security.personal-information.addressbook</key>
	<true/>
	<key>com.apple.security.personal-information.calendars</key>
	<true/>
	<key>com.apple.security.personal-information.location</key>
	<true/>
	<key>com.apple.security.personal-information.photos-library</key>
	<true/>
</dict>
</plist>
</file>

<file path="macos/GhosttyReleaseLocal.entitlements">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>com.apple.security.automation.apple-events</key>
	<true/>
	<key>com.apple.security.cs.disable-library-validation</key>
	<true/>
	<key>com.apple.security.device.audio-input</key>
	<true/>
	<key>com.apple.security.device.camera</key>
	<true/>
	<key>com.apple.security.personal-information.addressbook</key>
	<true/>
	<key>com.apple.security.personal-information.calendars</key>
	<true/>
	<key>com.apple.security.personal-information.location</key>
	<true/>
	<key>com.apple.security.personal-information.photos-library</key>
	<true/>
</dict>
</plist>
</file>

<file path="nix/build-support/update-mirror.nu">
#!/usr/bin/env nu

# This script downloads external dependencies from build.zig.zon.json that
# are not already mirrored at deps.files.ghostty.org, saves them to a local
# directory, and updates the build.zig.zon files (the root one as well as
# every pkg/*/build.zig.zon) to point to the new mirror URLs.
#
# HTTP files are downloaded unmodified. Git dependencies use Zig's normalized
# cache archive so their content hashes match the originals.
#
# After running this script, the files in the output directory can be uploaded
# to blob storage, and the build.zig.zon files will already be updated with
# the new URLs.
def download-git-package [url: string, expected_hash: string, destination: string] {
  let cache_dir = (mktemp --directory)
  let result = (do { ^zig fetch --global-cache-dir $cache_dir $url } | complete)

  if $result.exit_code != 0 {
    rm --recursive $cache_dir
    error make {
      msg: $"zig fetch failed for ($url): ($result.stderr | str trim)"
    }
  }

  let actual_hash = ($result.stdout | str trim)
  if $actual_hash != $expected_hash {
    rm --recursive $cache_dir
    error make {
      msg: $"zig fetch hash mismatch for ($url): expected ($expected_hash), got ($actual_hash)"
    }
... (134 lines truncated)
</file>

<file path="nix/test-src/test_libghostty_vt.c">
int main(void) {
</file>

<file path="po/be.po">
# Belarusian translations for com.mitchellh.ghostty package.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Illia Krauchanka <illiakrauchanka@gmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-04-14 00:00+0000\n"
"Last-Translator: Illia Krauchanka <illiakrauchanka@gmail.com>\n"
"Language-Team: Belarusian\n"
"Language: be\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Адкрыць у Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Дазволіць доступ да буфера абмену"
... (1075 lines truncated)
</file>

<file path="po/bg.po">
# Bulgarian translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Damyan Bogoev <damyan.bogoev@gmail.com>, 2025.
# reo101 <pavel.atanasov2001@gmail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 13:40+0300\n"
"Last-Translator: reo101 <pavel.atanasov2001@gmail.com>\n"
"Language-Team: Bulgarian <dict@ludost.net>\n"
"Language: bg\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Отвори в Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Разрешаване на достъп до клипборда"
... (1133 lines truncated)
</file>

<file path="po/ca.po">
# Catalan translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Francesc Arpi <francesc.arpi@gmail.com>, 2025.
# Kristofer Soler <31729650+KristoferSoler@users.noreply.github.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2025-08-24 19:22+0200\n"
"Last-Translator: Kristofer Soler "
"<31729650+KristoferSoler@users.noreply.github.com>\n"
"Language-Team: \n"
"Language: ca\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Obre amb Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
... (1077 lines truncated)
</file>

<file path="po/da.po">
# Danish translations for com.mitchellh.ghostty package.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Carl Villads Priisholm <carl.priisholm@gmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 12:00+0200\n"
"Last-Translator: Carl Villads Priisholm <carl.priisholm@gmail.com>\n"
"Language-Team: Danish <dansk@dansk-gruppen.dk>\n"
"Language: da\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Åben i Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Autorisér adgang til udklipsholderen"

... (1109 lines truncated)
</file>

<file path="po/de.po">
# German translations for com.mitchellh.ghostty package
# German translation for com.mitchellh.ghostty.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Robin Pfäffle <r@rpfaeffle.com>, 2025.
# Jan Klass <kissaki@posteo.de>, 2026.
# Klaus Hipp <khipp@users.noreply.github.com>, 2026.
# derVedro unter Druck <dervedro@googlemail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-02-18 21:12+0200\n"
"Last-Translator: derVedro <dervedro@googlemail.com>\n"
"Language-Team: German <translation-team-de@lists.sourceforge.net>\n"
"Language: de\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "In Ghostty öffnen"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
... (1112 lines truncated)
</file>

<file path="po/es_AR.po">
# Spanish translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Alan Moyano <alanmoyano203@gmail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 12:56-0300\n"
"Last-Translator: Alan Moyano <alanmoyano203@gmail.com>\n"
"Language-Team: Argentinian <es@tp.org.es>\n"
"Language: es_AR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Abrir en Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Autorizar acceso al portapapeles"

... (1120 lines truncated)
</file>

<file path="po/es_BO.po">
# Spanish translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Miguel Peredo <miguelp@quientienemail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 17:33+0300\n"
"Last-Translator: Miguel Peredo <miguelp@quientienemail.com>\n"
"Language-Team: Spanish <es@tp.org.es>\n"
"Language: es_BO\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Abrir en Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Autorizar acceso al portapapeles"

... (1121 lines truncated)
</file>

<file path="po/es_ES.po">
# Spanish translations for com.mitchellh.ghostty package
# Traducciones al español para el paquete com.mitchellh.ghostty.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# José Miguel Sarasola <alosarjos@gmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 21:24+0200\n"
"Last-Translator: José Miguel Sarasola <alosarjos@gmail.com>\n"
"Language-Team: \n"
"Language: es_ES\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Abrir en Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Autorizar acceso al portapapeles"
... (1125 lines truncated)
</file>

<file path="po/eu.po">
# Basque translations for com.mitchellh.ghostty package.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Mikel Larreategi <mlarreategi@codesyntax.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-31 15:18+0200\n"
"Last-Translator: Mikel Larreategi <mlarreategi@codesyntax.com>\n"
"Language-Team: Language eu\n"
"Language: eu\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 3.4.2\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Ireki Ghostty-n"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Baimendu arbelera sartzea"

... (1104 lines truncated)
</file>

<file path="po/fr.po">
# French translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Kirwiisp <swiip__@hotmail.com>, 2025.
# Gerry Agbobada <gerry@gagbo.net>, 2026.
# Pangoraw <naydex.mc+github@gmail.com>, 2026.
# flou <flou@proton.me>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-22 11:30+0200\n"
"Last-Translator: flou <flou@proton.me>\n"
"Language-Team: French <traduc@traduc.org>\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Ouvrir dans Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
... (1109 lines truncated)
</file>

<file path="po/ga.po">
# Irish translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Aindriú Mac Giolla Eoin <aindriu80@yahoo.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-02-18 14:32+0000\n"
"Last-Translator: Aindriú Mac Giolla Eoin <aindriu80@yahoo.com>\n"
"Language-Team: Irish <gaeilge-gnulinux@lists.sourceforge.net>\n"
"Language: ga\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=n==1 ? 0 : n==2 ? 1 : 2;\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Oscail i nGhostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Údarú rochtain ar an ngearrthaisce"

... (1075 lines truncated)
</file>

<file path="po/he.po">
# Hebrew translations for com.mitchellh.ghostty.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Sl (Shahaf Levi), Sl's Repository Ltd <ghostty@slsrepo.com>, 2026.
# CraziestOwl <craziestowl@proton.me>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 19:14+0300\n"
"Last-Translator: Sl (Shahaf Levi), Sl's Repository Ltd "
"<ghostty@slsrepo.com>\n"
"Language-Team: Hebrew <he_IL@lists.sourceforge.net>\n"
"Language: he\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "פתח/י בGhostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
... (1072 lines truncated)
</file>

<file path="po/hr.po">
# Croatian translations for com.mitchellh.ghostty package
# Hrvatski prijevod za paket com.mitchellh.ghostty.
# Copyright (C) 2025 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Filip <filipm7@protonmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-25 21:00+0200\n"
"Last-Translator: Filip7 <filipm7@protonmail.com>\n"
"Language-Team: Croatian <lokalizacija@linux.hr>\n"
"Language: hr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Otvori u Ghosttyju"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
... (1105 lines truncated)
</file>

<file path="po/hu.po">
# Hungarian translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Balázs Szücs <bszucs1209@gmail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 21:23+0200\n"
"Last-Translator: Balázs Szücs <bszucs1209@gmail.com>\n"
"Language-Team: Hungarian <translation-team-hu@lists.sourceforge.net>\n"
"Language: hu\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Megnyitás a Ghostty alkalmazásban"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Vágólap-hozzáférés engedélyezése"

... (1128 lines truncated)
</file>

<file path="po/id.po">
# Indonesian translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Satrio Bayu Aji <halosatrio@gmail.com>, 2026.
# Mikail Muzakki <mikailmmuzakki@gmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-03-08 20:23+0700\n"
"Last-Translator: Mikail Muzakki <mikailmmuzakki@gmail.com>\n"
"Language-Team: Indonesian <translation-team-id@lists.sourceforge.net>\n"
"Language: id\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Buka di Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Mengesahkan akses papan klip"
... (1075 lines truncated)
</file>

<file path="po/it.po">
# Italian translations for com.mitchellh.ghostty package.
# Traduzioni italiane per il pacchetto com.mitchellh.ghostty.
# Copyright (C) 2025 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Giacomo Bettini <giaco.bettini@gmail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-09-12 18:00+0200\n"
"Last-Translator: Giacomo Bettini <giaco.bettini@gmail.com>\n"
"Language-Team: Italian <tp@lists.linux.it>\n"
"Language: it\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Apri in Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Consenti accesso agli Appunti"
... (1121 lines truncated)
</file>

<file path="po/ja.po">
# Japanese translations for com.mitchellh.ghostty package
# com.mitchellh.ghostty パッケージに対する和訳.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Lon Sagisawa <lon@sagisawa.me>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-02-11 12:02+0900\n"
"Last-Translator: Takayuki Nagatomi <tnagatomi@okweird.net>\n"
"Language-Team: Japanese\n"
"Language: ja\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Ghosttyで開く"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "クリップボードへのアクセスを承認"
... (1074 lines truncated)
</file>

<file path="po/kk.po">
# Kazakh translation for Ghostty.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Baurzhan Muftakhidinov <baurthefirst@gmail.com>, 2026.
# AnmiTaliDev <anmitalidev@nuros.org>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 00:00+0500\n"
"Last-Translator: AnmiTaliDev <anmitalidev@nuros.org>\n"
"Language-Team: Kazakh <kk_KZ@googlegroups.com>\n"
"Language: kk\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Ghostty ішінде ашу"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Алмасу буферіне қол жеткізуді рұқсат ету"
... (1107 lines truncated)
</file>

<file path="po/ko_KR.po">
# Korean translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Ruben Engelbrecht <hey@rme.gg>, 2025.
# GyuYong Jung <obliviscence@gmail.com>, 2026.
# dobbylee <leekw1245@gmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-14 23:43+0900\n"
"Last-Translator: dobbylee <leekw1245@gmail.com>\n"
"Language-Team: Korean <translation-team-ko@googlegroups.com>\n"
"Language: ko\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Ghostty에서 열기"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
... (1085 lines truncated)
</file>

<file path="po/lt.po">
# Language LT translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Tadas Lotuzas <tdslot@gmail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 08:25+0200\n"
"Last-Translator: Tadas Lotuzas <tdslot@gmail.com>\n"
"Language-Team: Language LT\n"
"Language: LT\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"(n%100<10 || n%100>=20) ? 1 : 2);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Atidaryti su Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Leisti prieigą prie iškarpinės"
... (1110 lines truncated)
</file>

<file path="po/lv.po">
# Latvian translations for com.mitchellh.ghostty package.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Ēriks Remess <eriks@remess.lv>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-10 17:32+0300\n"
"Last-Translator: Ēriks Remess <eriks@remess.lv>\n"
"Language-Team: Latvian\n"
"Language: lv\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n!=0 ? 1 : 2);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Atvērt ar Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Atļaut piekļuvi starpliktuvei"

... (1092 lines truncated)
</file>

<file path="po/mk.po">
# Macedonian translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Andrej Daskalov <andrej.daskalov@gmail.com>, 2025.
# Marija Gjorgjieva Gjondeva <mgjorgjieva2013@gmail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-30 12:23+0200\n"
"Last-Translator: Andrej Daskalov <andrej.daskalov@gmail.com>\n"
"Language-Team: Macedonian\n"
"Language: mk\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Отвори во Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Авторизирај пристап до привремена меморија"

... (1094 lines truncated)
</file>

<file path="po/nb.po">
# Norwegian Bokmal translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Hanna Rose <me@hanna.lol>, 2025.
# Uzair Aftab <git@uzaaft.me>, 2025.
# Christoffer Tønnessen <christoffer@cto.gg>, 2025.
# cryptocode <cryptocode@zolo.io>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-12 21:34+0200\n"
"Last-Translator: Uzair Aftab <u@uzaaft.me>\n"
"Language-Team: Norwegian Bokmal <l10n-no@lister.huftis.org>\n"
"Language: nb\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Åpne i Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
... (1108 lines truncated)
</file>

<file path="po/nl.po">
# Dutch translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Nico Geesink <geesinknico@gmail.com>, 2025.
# Merijntje Tak <merijntje@tak.io>, 2025.
# Kris van der Ven <306806+kjvdven@users.noreply.github.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-14 18:30+0200\n"
"Last-Translator: Kris van der Ven <306806+kjvdven@users.noreply.github.com>\n"
"Language-Team: Dutch <vertaling@vrijschrift.org>\n"
"Language: nl\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Open in Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
... (1124 lines truncated)
</file>

<file path="po/pl.po">
# Polish translations for com.mitchellh.ghostty package
# Polskie tłumaczenia dla pakietu com.mitchellh.ghostty.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Bartosz Sokorski <b.sokorski@gmail.com>, 2025.
# trag1c <dev@jakubr.me>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 21:08+0100\n"
"Last-Translator: trag1c <dev@jakubr.me>\n"
"Language-Team: Polish <translation-team-pl@lists.sourceforge.net>\n"
"Language: pl\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 "
"|| n%100>=20) ? 1 : 2);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Otwórz w Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
... (1109 lines truncated)
</file>

<file path="po/pt_BR.po">
# Portuguese translations for com.mitchellh.ghostty package
# Traduções em português brasileiro para o pacote com.mitchellh.ghostty.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Gustavo Peres <gsodevel@gmail.com>, 2025.
# Guilherme Tiscoski <github@guilhermetiscoski.com>, 2025.
# Nilton Perim Neto <niltonperimneto@gmail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-17 11:57-0500\n"
"Last-Translator: Guilherme Tiscoski <github@guilhermetiscoski.com>\n"
"Language-Team: Brazilian Portuguese <ldpbr-"
"translation@lists.sourceforge.net>\n"
"Language: pt_BR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Abrir no Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
... (1125 lines truncated)
</file>

<file path="po/README_CONTRIBUTORS.md">
# Localizing Ghostty: The Contributors' Guide

Ghostty uses the `gettext` library/framework for localization, which has the
distinct benefit of being able to be consumed directly by our two main
app runtimes: macOS and GTK (Linux). The core would ideally remain agnostic
to localization efforts, as not all consumers of libghostty would be interested
in localization support. Thus, implementors of app runtimes are left responsible
for any localization that they may add.

## GTK

In the GTK app runtime, translatable strings are mainly sourced from Blueprint
files (located under `src/apprt/gtk/ui`). Blueprints have a native syntax for
translatable strings, which look like this:

```zig
// Translators: This is the name of the button that opens the about dialog.
title: _("About Ghostty");
```

The `// Translators:` comment provides additional context to the translator
if the string itself is unclear as to what its purpose is or where it's located.

By default identical strings are collapsed together into one translatable entry.
To avoid this, assign a _context_ to the string:

```zig
label: C_("menu action", "Copy");
```

... (67 lines truncated)
</file>

<file path="po/README_TRANSLATORS.md">
# Localizing Ghostty: The Translators' Guide

First of all, thanks for helping us localize Ghostty!

To begin contributing, please make sure that you have installed `gettext`
on your system, which should be available under the `gettext` package
for most Linux and macOS package managers.

You can install `gettext` on Windows in a few ways:

- Through [an installer](https://mlocati.github.io/articles/gettext-iconv-windows.html);
- Through package managers like Scoop (`scoop install gettext`) and
  WinGet (`winget install gettext`) which repackages the aforementioned installer;
- Through Unix-like environments like [Cygwin](https://cygwin.com/cygwin/packages/summary/gettext.html)
  and [MSYS2](https://packages.msys2.org/base/gettext).

> [!WARNING]
>
> Unlike what some tutorials suggest, **we do not recommend installing `gettext`
> through GnuWin32**, since it hasn't been updated since 2010 and very likely
> does not work on modern Windows versions.

You can verify that `gettext` has been successfully installed by running the
command `gettext -V`. If everything went correctly, you should see an output like this:

```console
$ gettext -V
gettext (GNU gettext-runtime) 0.21.1
Copyright (C) 1995-2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
... (264 lines truncated)
</file>

<file path="po/ru.po">
# Russian translations for com.mitchellh.ghostty package
# Русские переводы для пакета com.mitchellh.ghostty.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# blackzeshi <sergey_zhuzhgov@mail.ru>, 2025.
# Ivan Bastrakov <bastaynav@proton.me>, 2025.
# derVedro и зайчатки разума <dervedro@googlemail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-09-16 15:45+0200\n"
"Last-Translator: derVedro <dervedro@googlemail.com>\n"
"Language-Team: Russian\n"
"Language: ru\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Открыть в Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
... (1104 lines truncated)
</file>

<file path="po/sr.po">
# Language SR translations for com.mitchellh.ghostty package.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Марко Костић <marko.m.kostic@gmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-31 21:45+0200\n"
"Last-Translator: Марко Костић <marko.m.kostic@gmail.com>\n"
"Language-Team: Language SR\n"
"Language: sr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Отвори у Ghostty-ју"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Одобри приступ остави"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:17
... (1025 lines truncated)
</file>

<file path="po/sr@latin.po">
# Language SR@latin translations for com.mitchellh.ghostty package.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Марко Костић <marko.m.kostic@gmail.com>, 2026.
#
# Do not translate or edit this file directly. It is generated from po/sr.po with:
# msgfilter -i po/sr.po -o po/sr@latin.po recode-sr-latin
# After updating po/sr.po, regenerate this file and set `Language: sr@latin`.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-31 21:45+0200\n"
"Last-Translator: Marko Kostić <marko.m.kostic@gmail.com>\n"
"Language-Team: Language SR\n"
"Language: sr@latin\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Otvori u Ghostty-ju"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
... (1106 lines truncated)
</file>

<file path="po/tr.po">
# Turkish translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Emir SARI <emir_sari@icloud.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 20:33+0300\n"
"Last-Translator: Emir SARI <emir_sari@icloud.com>\n"
"Language-Team: Turkish\n"
"Language: tr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Ghostty’de Aç"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Pano Erişimine İzin Ver"

... (1108 lines truncated)
</file>

<file path="po/uk.po">
# Ukrainian translations for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Danylo Zalizchuk <danilmail0110@gmail.com>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-19 19:34+0100\n"
"Last-Translator: Volodymyr Chernetskyi "
"<19735328+chernetskyi@users.noreply.github.com>\n"
"Language-Team: Ukrainian <trans-uk@lists.fedoraproject.org>\n"
"Language: uk\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Відкрити в Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
... (1107 lines truncated)
</file>

<file path="po/vi.po">
# Vietnamese translations for com.mitchellh.ghostty package.
# Copyright (C) 2026 "Mitchell Hashimoto, Ghostty contributors"
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Anh Thang <buianhthang89@gmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-13 21:30+0700\n"
"Last-Translator: Anh Thang <buianhthang89@gmail.com>\n"
"Language-Team: Vietnamese <translation-team-vi@lists.sourceforge.net>\n"
"Language: vi\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "Mở Ghostty"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
msgstr "Cho phép truy cập Bảng tạm"

... (1099 lines truncated)
</file>

<file path="po/zh_CN.po">
# Chinese translations for com.mitchellh.ghostty package
# com.mitchellh.ghostty 软件包的简体中文翻译.
# Copyright (C) 2025 Mitchell Hashimoto, Ghostty contributors
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Leah <hi@pluie.me>, 2025.
# Lukas <134181853+bo2themax@users.noreply.github.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-09-13 10:50+0800\n"
"Last-Translator: Lukas <134181853+bo2themax@users.noreply.github.com>\n"
"Language-Team: Chinese (simplified) <i18n-zh@googlegroups.com>\n"
"Language: zh_CN\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "在 Ghostty 中打开"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
... (1068 lines truncated)
</file>

<file path="po/zh_TW.po">
# Traditional Chinese (Taiwan) translation for com.mitchellh.ghostty package.
# Copyright (C) 2025 Mitchell Hashimoto
# This file is distributed under the same license as the com.mitchellh.ghostty package.
# Peter Dave Hello <hsu@peterdavehello.org>, 2025.
# Yi-Jyun Pan <me@pan93.com>, 2025.
# Alang Hsu <alang.hsu@gmail.com>, 2026.
#
msgid ""
msgstr ""
"Project-Id-Version: com.mitchellh.ghostty\n"
"Report-Msgid-Bugs-To: m@mitchellh.com\n"
"POT-Creation-Date: 2026-08-10 10:06-0500\n"
"PO-Revision-Date: 2026-08-14 10:59+0800\n"
"Last-Translator: Alang Hsu <alang.hsu@gmail.com>\n"
"Language-Team: Chinese (traditional)\n"
"Language: zh_TW\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"

#: dist/linux/ghostty_nautilus.py:53
msgid "Open in Ghostty"
msgstr "在 Ghostty 中開啟"

#: src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp:12
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:197
#: src/apprt/gtk/class/clipboard_confirmation_dialog.zig:201
msgid "Authorize Clipboard Access"
... (1066 lines truncated)
</file>

<file path="snap/local/launcher">
#!/bin/sh
set -e

# Set these to reasonable defaults if not already set
if [ -z "$XDG_CONFIG_HOME" ]; then
  export XDG_CONFIG_HOME="$SNAP_REAL_HOME/.config"
fi

if [ -z "$XDG_CACHE_HOME" ]; then
  export XDG_CACHE_HOME="$SNAP_REAL_HOME/.cache"
fi

if [ -z "$XDG_DATA_HOME" ]; then
  export XDG_DATA_HOME="$SNAP_REAL_HOME/.local/share"
fi

if [ -f "$SNAP_USER_DATA/.last_revision" ]; then
  if ! source "$SNAP_USER_DATA/.last_revision" 2>/dev/null; then
    # file exist but sourcing it fails, so it's likely
    # not good anyway
    rm -f "$SNAP_USER_DATA/.last_revision"
  fi
fi

if [ "$LAST_REVISION" = "$SNAP_REVISION" ]; then
  needs_update=false
else
  needs_update=true
fi

... (45 lines truncated)
</file>

<file path="src/apprt/gtk/class/application.zig">
const builtin = @import("builtin");
const std = @import("std");
const assert = @import("../../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const adw = @import("adw");
const gdk = @import("gdk");
const gio = @import("gio");
const glib = @import("glib");
const glibunix = @import("glibunix");
const gobject = @import("gobject");
const gtk = @import("gtk");

const build_config = @import("../../../build_config.zig");
const build_info = @import("../build/info.zig");
const cli = @import("../../../cli.zig");
const global = @import("../../../global.zig");
const i18n = @import("../../../os/main.zig").i18n;
const apprt = @import("../../../apprt.zig");
const CoreApp = @import("../../../App.zig");
const compat_file = @import("../../../lib/compat/file.zig");
const configpkg = @import("../../../config.zig");
const input = @import("../../../input.zig");
const internal_os = @import("../../../os/main.zig");
const systemd = @import("../../../os/systemd.zig");
const terminal = @import("../../../terminal/main.zig");
const xev = global.xev;
const Binding = @import("../../../input.zig").Binding;
const CoreConfig = configpkg.Config;
const CoreSurface = @import("../../../Surface.zig");

... (3321 lines truncated)
</file>

<file path="src/apprt/gtk/class/clipboard_confirmation_dialog.zig">
const std = @import("std");
const adw = @import("adw");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const apprt = @import("../../../apprt.zig");
const gresource = @import("../build/gresource.zig");
const i18n = @import("../../../os/main.zig").i18n;
const adw_version = @import("../adw_version.zig");
const Common = @import("../class.zig").Common;
const Dialog = @import("dialog.zig").Dialog;

const log = std.log.scoped(.gtk_ghostty_clipboard_confirmation);

/// Whether we're able to have the remember switch
const can_remember = adw_version.supportsSwitchRow();

pub const ClipboardConfirmationDialog = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = Dialog;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyClipboardConfirmationDialog",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

... (324 lines truncated)
</file>

<file path="src/apprt/gtk/class/close_confirmation_dialog.zig">
const std = @import("std");
const gobject = @import("gobject");
const gtk = @import("gtk");

const gresource = @import("../build/gresource.zig");
const i18n = @import("../../../os/main.zig").i18n;
const Common = @import("../class.zig").Common;
const Dialog = @import("dialog.zig").Dialog;

const log = std.log.scoped(.gtk_ghostty_close_confirmation_dialog);

pub const CloseConfirmationDialog = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = Dialog;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyCloseConfirmationDialog",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

    pub const properties = struct {
        pub const target = struct {
            pub const name = "target";
            const impl = gobject.ext.defineProperty(
                name,
                Self,
                Target,
... (175 lines truncated)
</file>

<file path="src/apprt/gtk/class/command_palette.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;

const adw = @import("adw");
const gio = @import("gio");
const gobject = @import("gobject");
const gtk = @import("gtk");

const input = @import("../../../input.zig");
const gresource = @import("../build/gresource.zig");
const key = @import("../key.zig");
const WeakRef = @import("../weak_ref.zig").WeakRef;
const Common = @import("../class.zig").Common;
const Application = @import("application.zig").Application;
const Window = @import("window.zig").Window;
const Surface = @import("surface.zig").Surface;
const Tab = @import("tab.zig").Tab;
const Config = @import("config.zig").Config;

const log = std.log.scoped(.gtk_ghostty_command_palette);

pub const CommandPalette = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.Bin;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyCommandPalette",
        .instanceInit = &init,
        .classInit = &Class.init,
... (758 lines truncated)
</file>

<file path="src/apprt/gtk/class/config_errors_dialog.zig">
const std = @import("std");
const gobject = @import("gobject");
const gtk = @import("gtk");

const gresource = @import("../build/gresource.zig");
const Common = @import("../class.zig").Common;
const Config = @import("config.zig").Config;
const Dialog = @import("dialog.zig").Dialog;

const log = std.log.scoped(.gtk_ghostty_config_errors_dialog);

pub const ConfigErrorsDialog = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = Dialog;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyConfigErrorsDialog",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

    pub const properties = struct {
        pub const config = gobject.ext.defineProperty(
            "config",
            Self,
            ?*Config,
            .{
                .accessor = gobject.ext.typedAccessor(
... (132 lines truncated)
</file>

<file path="src/apprt/gtk/class/config.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const gobject = @import("gobject");
const gtk = @import("gtk");

const configpkg = @import("../../../config.zig");
const CoreConfig = configpkg.Config;

const Common = @import("../class.zig").Common;

const log = std.log.scoped(.gtk_ghostty_config);

/// Wraps a `Ghostty.Config` object in a GObject so it can be reference
/// counted. When this object is freed, the underlying config is also freed.
///
/// It is highly recommended to NOT take a reference to this object,
/// since configuration takes up a lot of memory (relatively). Instead,
/// receivers of this should usually create a `DerivedConfig` struct from
/// this, copy any memory they require, and own that structure instead.
///
/// This can also expose helpers to access configuration in ways that
/// may be more ergonomic to GTK primitives.
pub const Config = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = gobject.Object;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyConfig",
        .classInit = &Class.init,
        .parent_class = &Class.parent,
... (146 lines truncated)
</file>

<file path="src/apprt/gtk/class/debug_warning.zig">
const adw = @import("adw");
const gobject = @import("gobject");
const gtk = @import("gtk");

const adw_version = @import("../adw_version.zig");
const gresource = @import("../build/gresource.zig");
const Common = @import("../class.zig").Common;

/// Debug warning banner. It will be based on adw.Banner if we're using Adwaita
/// 1.3 or newer. Otherwise it will use a gtk.Label.
pub const DebugWarning = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = if (adw_version.supportsBanner()) adw.Bin else gtk.Box;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyDebugWarning",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
    });

    fn init(self: *Self, _: *Class) callconv(.c) void {
        gtk.Widget.initTemplate(self.as(gtk.Widget));
    }

    const C = Common(Self, null);
    pub const as = C.as;
    pub const ref = C.ref;
    pub const unref = C.unref;
    const private = C.private;
... (21 lines truncated)
</file>

<file path="src/apprt/gtk/class/dialog.zig">
const std = @import("std");
const adw = @import("adw");
const gobject = @import("gobject");
const gtk = @import("gtk");

const adw_version = @import("../adw_version.zig");
const Common = @import("../class.zig").Common;

const log = std.log.scoped(.gtk_ghostty_dialog);

/// Dialog is a simple abstraction over the `adw.AlertDialog` and
/// `adw.MessageDialog` widgets, chosen at comptime based on the linked
/// Adwaita version.
///
/// Once we drop support for Adwaita <= 1.2, this can be fully removed
/// and we can use `adw.AlertDialog` directly.
pub const Dialog = extern struct {
    const Self = @This();
    parent_instance: Parent,

    pub const Parent = if (adw_version.supportsDialogs())
        adw.AlertDialog
    else
        adw.MessageDialog;

    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyDialog",
        .classInit = &Class.init,
        .parent_class = &Class.parent,
    });
... (62 lines truncated)
</file>

<file path="src/apprt/gtk/class/global_shortcuts.zig">
const std = @import("std");
const assert = @import("../../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const global = @import("../../../global.zig");

const Binding = @import("../../../input.zig").Binding;
const key = @import("../key.zig");
const Common = @import("../class.zig").Common;
const Application = @import("application.zig").Application;
const Config = @import("config.zig").Config;

const log = std.log.scoped(.gtk_ghostty_global_shortcuts);

pub const GlobalShortcuts = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = gobject.Object;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyGlobalShortcuts",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

    pub const properties = struct {
        pub const config = struct {
... (669 lines truncated)
</file>

<file path="src/apprt/gtk/class/imgui_widget.zig">
const std = @import("std");
const assert = @import("../../../quirks.zig").inlineAssert;

const cimgui = @import("dcimgui");
const gl = @import("opengl");
const adw = @import("adw");
const gdk = @import("gdk");
const gobject = @import("gobject");
const gtk = @import("gtk");
const global = @import("../../../global.zig");

const input = @import("../../../input.zig");
const gresource = @import("../build/gresource.zig");

const key = @import("../key.zig");
const Common = @import("../class.zig").Common;

const log = std.log.scoped(.gtk_ghostty_imgui_widget);

/// A widget for embedding a Dear ImGui application.
///
/// It'd be a lot cleaner to use inheritance here but zig-gobject doesn't
/// currently have a way to define virtual methods, so we have to use
/// composition and signals instead.
pub const ImguiWidget = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.Bin;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyImguiWidget",
... (528 lines truncated)
</file>

<file path="src/apprt/gtk/class/inspector_widget.zig">
const std = @import("std");

const gobject = @import("gobject");
const gtk = @import("gtk");

const gresource = @import("../build/gresource.zig");
const Inspector = @import("../../../inspector/Inspector.zig");

const Common = @import("../class.zig").Common;
const Surface = @import("surface.zig").Surface;
const ImguiWidget = @import("imgui_widget.zig").ImguiWidget;

const log = std.log.scoped(.gtk_ghostty_inspector_widget);

/// Widget for displaying the Ghostty inspector.
pub const InspectorWidget = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = ImguiWidget;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyInspectorWidget",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

    pub const properties = struct {
        pub const surface = struct {
            pub const name = "surface";
... (216 lines truncated)
</file>

<file path="src/apprt/gtk/class/inspector_window.zig">
const std = @import("std");
const build_config = @import("../../../build_config.zig");

const adw = @import("adw");
const gobject = @import("gobject");
const gtk = @import("gtk");

const gresource = @import("../build/gresource.zig");

const Common = @import("../class.zig").Common;
const Surface = @import("surface.zig").Surface;
const DebugWarning = @import("debug_warning.zig").DebugWarning;
const InspectorWidget = @import("inspector_widget.zig").InspectorWidget;
const WeakRef = @import("../weak_ref.zig").WeakRef;

const log = std.log.scoped(.gtk_ghostty_inspector_window);

/// Window for displaying the Ghostty inspector.
pub const InspectorWindow = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.ApplicationWindow;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyInspectorWindow",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

... (188 lines truncated)
</file>

<file path="src/apprt/gtk/class/key_state_overlay.zig">
const std = @import("std");
const adw = @import("adw");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const ext = @import("../ext.zig");
const gresource = @import("../build/gresource.zig");
const Application = @import("application.zig").Application;
const Common = @import("../class.zig").Common;

const log = std.log.scoped(.gtk_ghostty_key_state_overlay);

/// An overlay that displays the current key table stack and pending key sequence.
/// This helps users understand what key bindings are active and what keys they've
/// pressed in a multi-key sequence.
pub const KeyStateOverlay = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.Bin;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyKeyStateOverlay",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

    pub const properties = struct {
        pub const tables = struct {
... (313 lines truncated)
</file>

<file path="src/apprt/gtk/class/Overrides.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

const glib = @import("glib");

const cli = @import("../../../cli.zig");
const configpkg = @import("../../../config.zig");

const log = std.log.scoped(.gtk_ghostty_overrides);

const Overrides = @This();
const ParseError = Allocator.Error || error{ValueRequired};

command: ?configpkg.Command,
shell_integration: ?configpkg.Config.ShellIntegration,
working_directory: ?[:0]const u8,
title: ?[:0]const u8,

pub const none: Overrides = .{
    .command = null,
    .shell_integration = null,
    .working_directory = null,
    .title = null,
};

pub fn parse(arena_alloc: Allocator, arguments_it: *glib.VariantIter) ParseError!Overrides {
    var args: std.ArrayList([:0]const u8) = .empty;

    var working_directory: ?[:0]const u8 = null;
    var title: ?[:0]const u8 = null;
... (95 lines truncated)
</file>

<file path="src/apprt/gtk/class/render_surface.zig">
const std = @import("std");

const glib = @import("glib");
const gobject = @import("gobject");
const gdk = @import("gdk");
const gtk = @import("gtk");

const global = @import("../../../global.zig");
const Application = @import("application.zig").Application;
const Common = @import("../class.zig").Common;
const scale_util = @import("../scale.zig");
const CoreSurface = @import("../../../Surface.zig");
const rendererpkg = @import("../../../renderer.zig");
const ExportedFrame = rendererpkg.Renderer.ExportedFrame;
const Dmabuf = @import("../../../renderer/Dmabuf.zig");
const Planes = Dmabuf.Planes;

const log = std.log.scoped(.gtk_render_surface);

/// A widget that displays the rendered output of the Ghostty renderer.
///
/// In the past, Ghostty relied on GTK's builtin `GLArea` to display the
/// rendered output within the GTK-based UI, but this had numerous
/// debilitating limitations.
///
/// Its most significant limitation is that GTK's render lifecycle lives
/// **exclusively on the main UI thread**, from initialization to drawing the
/// rendered framebuffers. This is not only inefficient but also error-prone,
/// as we offload our render work to a dedicated render thread which has
/// to be careful not to access the renderer at the same time as the main
... (432 lines truncated)
</file>

<file path="src/apprt/gtk/class/resize_overlay.zig">
const std = @import("std");
const adw = @import("adw");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const gresource = @import("../build/gresource.zig");
const Common = @import("../class.zig").Common;

const log = std.log.scoped(.gtk_ghostty_resize_overlay);

/// The overlay that shows the current size while a surface is resizing.
/// This can be used generically to show pretty much anything with a
/// disappearing overlay, but we have no other use at this point so it
/// is named specifically for what it does.
///
/// General usage:
///
///   1. Add it to an overlay
///   2. Set the label with `setLabel`
///   3. Schedule to show it with `schedule`
///
/// Set any properties to change the behavior.
pub const ResizeOverlay = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.Bin;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyResizeOverlay",
        .instanceInit = &init,
... (309 lines truncated)
</file>

<file path="src/apprt/gtk/class/search_overlay.zig">
const std = @import("std");
const adw = @import("adw");
const glib = @import("glib");
const gobject = @import("gobject");
const gdk = @import("gdk");
const gtk = @import("gtk");

const gresource = @import("../build/gresource.zig");
const Common = @import("../class.zig").Common;

const log = std.log.scoped(.gtk_ghostty_search_overlay);

/// The overlay that shows the current size while a surface is resizing.
/// This can be used generically to show pretty much anything with a
/// disappearing overlay, but we have no other use at this point so it
/// is named specifically for what it does.
///
/// General usage:
///
///   1. Add it to an overlay
///   2. Set the label with `setLabel`
///   3. Schedule to show it with `schedule`
///
/// Set any properties to change the behavior.
pub const SearchOverlay = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.Bin;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttySearchOverlay",
... (464 lines truncated)
</file>

<file path="src/apprt/gtk/class/split_tree.zig">
const std = @import("std");
const assert = @import("../../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const adw = @import("adw");
const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const configpkg = @import("../../../config.zig");
const apprt = @import("../../../apprt.zig");
const ext = @import("../ext.zig");
const gresource = @import("../build/gresource.zig");
const Common = @import("../class.zig").Common;
const WeakRef = @import("../weak_ref.zig").WeakRef;
const Application = @import("application.zig").Application;
const CloseConfirmationDialog = @import("close_confirmation_dialog.zig").CloseConfirmationDialog;
const Surface = @import("surface.zig").Surface;
const SurfaceScrolledWindow = @import("surface_scrolled_window.zig").SurfaceScrolledWindow;
const Overrides = @import("Overrides.zig");

const log = std.log.scoped(.gtk_ghostty_split_tree);

pub const SplitTree = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = gtk.Box;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttySplitTree",
        .instanceInit = &init,
... (1481 lines truncated)
</file>

<file path="src/apprt/gtk/class/surface_child_exited.zig">
const std = @import("std");
const adw = @import("adw");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const adw_version = @import("../adw_version.zig");
const apprt = @import("../../../apprt.zig");
const gresource = @import("../build/gresource.zig");
const i18n = @import("../../../os/main.zig").i18n;
const Common = @import("../class.zig").Common;

const log = std.log.scoped(.gtk_ghostty_surface_child_exited);

pub const SurfaceChildExited = if (adw_version.supportsBanner())
    SurfaceChildExitedBanner
else
    SurfaceChildExitedNoop;

/// Child exited overlay based on adw.Banner introduced in
/// Adwaita 1.3.
const SurfaceChildExitedBanner = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.Bin;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttySurfaceChildExited",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
... (235 lines truncated)
</file>

<file path="src/apprt/gtk/class/surface_scrolled_window.zig">
const std = @import("std");
const adw = @import("adw");
const gobject = @import("gobject");
const gtk = @import("gtk");
const gtk_version = @import("../gtk_version.zig");

const gresource = @import("../build/gresource.zig");
const Common = @import("../class.zig").Common;
const Surface = @import("surface.zig").Surface;
const Config = @import("config.zig").Config;

const log = std.log.scoped(.gtk_ghostty_surface_scrolled_window);

/// A wrapper widget that embeds a Surface inside a GtkScrolledWindow.
/// This provides scrollbar functionality for the terminal surface.
/// The surface property can be set during initialization or changed
/// dynamically via the surface property.
pub const SurfaceScrolledWindow = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.Bin;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhostttySurfaceScrolledWindow",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

    pub const properties = struct {
... (204 lines truncated)
</file>

<file path="src/apprt/gtk/class/surface.zig">
const std = @import("std");
const assert = @import("../../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const adw = @import("adw");
const gdk = @import("gdk");
const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const apprt = @import("../../../apprt.zig");
const build_config = @import("../../../build_config.zig");
const configpkg = @import("../../../config.zig");
const datastruct = @import("../../../datastruct/main.zig");
const font = @import("../../../font/main.zig");
const input = @import("../../../input.zig");
const internal_os = @import("../../../os/main.zig");
const renderer = @import("../../../renderer.zig");
const terminal = @import("../../../terminal/main.zig");
const CoreSurface = @import("../../../Surface.zig");
const gresource = @import("../build/gresource.zig");
const ext = @import("../ext.zig");
const gsettings = @import("../gsettings.zig");
const gtk_key = @import("../key.zig");
const ApprtSurface = @import("../Surface.zig");
const Common = @import("../class.zig").Common;
const Application = @import("application.zig").Application;
const Config = @import("config.zig").Config;
const ResizeOverlay = @import("resize_overlay.zig").ResizeOverlay;
const SearchOverlay = @import("search_overlay.zig").SearchOverlay;
... (4391 lines truncated)
</file>

<file path="src/apprt/gtk/class/tab.zig">
const std = @import("std");
const adw = @import("adw");
const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const configpkg = @import("../../../config.zig");
const apprt = @import("../../../apprt.zig");
const CoreSurface = @import("../../../Surface.zig");
const ext = @import("../ext.zig");
const gresource = @import("../build/gresource.zig");
const Common = @import("../class.zig").Common;
const Config = @import("config.zig").Config;
const Application = @import("application.zig").Application;
const SplitTree = @import("split_tree.zig").SplitTree;
const Surface = @import("surface.zig").Surface;
const TitleDialog = @import("title_dialog.zig").TitleDialog;
const Overrides = @import("Overrides.zig");

const log = std.log.scoped(.gtk_ghostty_window);

pub const Tab = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = gtk.Box;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyTab",
        .instanceInit = &init,
        .classInit = &Class.init,
... (559 lines truncated)
</file>

<file path="src/apprt/gtk/class/title_dialog.zig">
const std = @import("std");
const adw = @import("adw");
const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const gresource = @import("../build/gresource.zig");
const i18n = @import("../../../os/main.zig").i18n;
const ext = @import("../ext.zig");
const Common = @import("../class.zig").Common;
const Dialog = @import("dialog.zig").Dialog;

const log = std.log.scoped(.gtk_ghostty_title_dialog);

pub const TitleDialog = extern struct {
    const Self = @This();
    parent_instance: Parent,
    pub const Parent = adw.AlertDialog;
    pub const getGObjectType = gobject.ext.defineClass(Self, .{
        .name = "GhosttyTitleDialog",
        .instanceInit = &init,
        .classInit = &Class.init,
        .parent_class = &Class.parent,
        .private = .{ .Type = Private, .offset = &Private.offset },
    });

    pub const properties = struct {
        pub const target = struct {
            pub const name = "target";
... (208 lines truncated)
</file>

<file path="src/apprt/gtk/class/window.zig">
const std = @import("std");
const build_config = @import("../../../build_config.zig");
const assert = @import("../../../quirks.zig").inlineAssert;
const adw = @import("adw");
const gdk = @import("gdk");
const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const i18n = @import("../../../os/main.zig").i18n;
const apprt = @import("../../../apprt.zig");
const configpkg = @import("../../../config.zig");
const TitlebarStyle = configpkg.Config.GtkTitlebarStyle;
const input = @import("../../../input.zig");
const CoreSurface = @import("../../../Surface.zig");
const ext = @import("../ext.zig");
const gtk_version = @import("../gtk_version.zig");
const adw_version = @import("../adw_version.zig");
const gresource = @import("../build/gresource.zig");
const winprotopkg = @import("../winproto.zig");
const Common = @import("../class.zig").Common;
const Config = @import("config.zig").Config;
const Application = @import("application.zig").Application;
const CloseConfirmationDialog = @import("close_confirmation_dialog.zig").CloseConfirmationDialog;
const SplitTree = @import("split_tree.zig").SplitTree;
const Surface = @import("surface.zig").Surface;
const Tab = @import("tab.zig").Tab;
const DebugWarning = @import("debug_warning.zig").DebugWarning;
const CommandPalette = @import("command_palette.zig").CommandPalette;
... (2357 lines truncated)
</file>

<file path="src/apprt/gtk/ext/actions.zig">
const std = @import("std");

const assert = @import("../../../quirks.zig").inlineAssert;
const testing = std.testing;

const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const gValueHolds = @import("../ext.zig").gValueHolds;

/// Check that an action name is valid.
///
/// Reimplementation of `g_action_name_is_valid()` so that it can be
/// used at comptime.
///
/// See:
/// https://docs.gtk.org/gio/type_func.Action.name_is_valid.html
fn gActionNameIsValid(name: [:0]const u8) bool {
    if (name.len == 0) return false;

    for (name) |c| switch (c) {
        '-' => continue,
        '.' => continue,
        '0'...'9' => continue,
        'a'...'z' => continue,
        'A'...'Z' => continue,
        else => return false,
    };
... (173 lines truncated)
</file>

<file path="src/apprt/gtk/ext/slice.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const glib = @import("glib");
const gobject = @import("gobject");

/// A boxed type that holds a list of string slices.
pub const StringList = struct {
    arena: ArenaAllocator,
    strings: []const [:0]const u8,

    pub fn create(
        alloc: Allocator,
        strings: []const [:0]const u8,
    ) Allocator.Error!*StringList {
        var arena: ArenaAllocator = .init(alloc);
        errdefer arena.deinit();
        const arena_alloc = arena.allocator();
        var stored = try arena_alloc.alloc([:0]const u8, strings.len);
        for (strings, 0..) |s, i| stored[i] = try arena_alloc.dupeZ(u8, s);

        const ptr = try alloc.create(StringList);
        errdefer alloc.destroy(ptr);
        ptr.* = .{ .arena = arena, .strings = stored };

        return ptr;
    }

    pub fn deinit(self: *StringList) void {
        self.arena.deinit();
... (82 lines truncated)
</file>

<file path="src/apprt/gtk/ipc/DBus.zig">
//! DBus helper for IPC
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;

const gio = @import("gio");
const glib = @import("glib");
const global = @import("../../../global.zig");

const apprt = @import("../../../apprt.zig");
const ApprtApp = @import("../App.zig");

/// The target for this IPC.
target: apprt.ipc.Target,

/// Connection to the DBus session bus.
dbus: *gio.DBusConnection,

/// The bus name of the Ghostty instance that we are calling.
bus_name: [:0]const u8,

/// The object path of the Ghostty instance that we are calling.
object_path: [:0]const u8,

/// Used to build the DBus payload.
payload_builder: *glib.VariantBuilder,

/// Used to build the parameters for the IPC.
parameters_builder: *glib.VariantBuilder,
... (170 lines truncated)
</file>

<file path="src/apprt/gtk/ipc/new_tab.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

const glib = @import("glib");

const apprt = @import("../../../apprt.zig");
const DBus = @import("DBus.zig");

// Use a D-Bus method call to open a new tab on GTK.
// See: https://wiki.gnome.org/Projects/GLib/GApplication/DBusAPI
//
// `ghostty +new-tab` is equivalent to the following command (on a release build):
//
// ```
// gdbus call --session --dest com.mitchellh.ghostty --object-path /com/mitchellh/ghostty --method org.gtk.Actions.Activate new-tab '[<@(tas) (0, [])>]' []
// ```
//
// `ghostty +new-tab -e echo hello` would be equivalent to the following command (on a release build):
//
// ```
// gdbus call --session --dest com.mitchellh.ghostty --object-path /com/mitchellh/ghostty --method org.gtk.Actions.Activate new-tab '[<@(tas) (0, ["-e" "echo" "hello"])>]' []
// ```
pub fn newTab(alloc: Allocator, target: apprt.ipc.Target, value: apprt.ipc.Action.NewTab) (Allocator.Error || std.Io.Writer.Error || apprt.ipc.Errors)!bool {
    var dbus = try DBus.init(alloc, target, "new-tab");
    defer dbus.deinit(alloc);

    const tas_variant_type = glib.VariantType.new("(tas)");
    defer tas_variant_type.free();

    var parameter: glib.VariantBuilder = undefined;
... (42 lines truncated)
</file>

<file path="src/apprt/gtk/ipc/new_window.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

const glib = @import("glib");

const apprt = @import("../../../apprt.zig");
const DBus = @import("DBus.zig");

// Use a D-Bus method call to open a new window on GTK.
// See: https://wiki.gnome.org/Projects/GLib/GApplication/DBusAPI
//
// `ghostty +new-window` is equivalent to the following command (on a release build):
//
// ```
// gdbus call --session --dest com.mitchellh.ghostty --object-path /com/mitchellh/ghostty --method org.gtk.Actions.Activate new-window [] []
// ```
//
// `ghostty +new-window -e echo hello` would be equivalent to the following command (on a release build):
//
// ```
// gdbus call --session --dest com.mitchellh.ghostty --object-path /com/mitchellh/ghostty --method org.gtk.Actions.Activate new-window-command '[<@as ["-e" "echo" "hello"]>]' []
// ```
pub fn newWindow(alloc: Allocator, target: apprt.ipc.Target, value: apprt.ipc.Action.NewWindow) (Allocator.Error || std.Io.Writer.Error || apprt.ipc.Errors)!bool {
    var dbus = try DBus.init(
        alloc,
        target,
        if (value.arguments == null)
            "new-window"
        else
            "new-window-command",
... (33 lines truncated)
</file>

<file path="src/apprt/gtk/ipc/toggle_quick_terminal.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

const apprt = @import("../../../apprt.zig");
const DBus = @import("DBus.zig");

/// Use a D-Bus method call to toggle the quick terminal on GTK.
///
/// `ghostty +toggle-quick-terminal` is equivalent to the following command
/// (on a release build):
///
/// ```sh
/// gdbus call --session \
///   --dest com.mitchellh.ghostty \
///   --object-path /com/mitchellh/ghostty \
///   --method org.gtk.Actions.Activate \
///   toggle-quick-terminal [] []
/// ```
pub fn toggleQuickTerminal(alloc: Allocator, target: apprt.ipc.Target) (Allocator.Error || std.Io.Writer.Error || apprt.ipc.Errors)!bool {
    var dbus = try DBus.init(alloc, target, "toggle-quick-terminal");
    defer dbus.deinit(alloc);
    try dbus.send();
    return true;
}
</file>

<file path="src/apprt/gtk/portal/OpenURI.zig">
//! Use DBus to call the XDG Desktop Portal to open an URI.
//! See: https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.OpenURI.html#org-freedesktop-portal-openuri-openuri
const OpenURI = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;

const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const global = @import("../../../global.zig");

const App = @import("../App.zig");
const portal = @import("../portal.zig");
const apprt = @import("../../../apprt.zig");

const log = std.log.scoped(.openuri);

/// The GTK app that we "belong" to.
app: *App,

/// Connection to the D-Bus session bus that we'll use for all of our messaging.
dbus: ?*gio.DBusConnection = null,

/// Mutex to protect modification of the entries map or the cleanup timer.
mutex: std.Io.Mutex = .init,

/// Map to store data about any in-flight calls to the portal.
entries: std.AutoArrayHashMapUnmanaged(usize, *Entry) = .empty,
... (533 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.0/clipboard-confirmation-dialog.blp">
using Gtk 4.0;
// This is unused but if we remove it we get a blueprint-compiler error.
using Adw 1;

template $GhosttyClipboardConfirmationDialog: $GhosttyDialog {
  styles [
    "clipboard-confirmation-dialog",
  ]

  notify::blur => $notify_blur();
  notify::request => $notify_request();
  heading: _("Authorize Clipboard Access");
  // Not localized because this is a placeholder users never see.
  body: "If you see this text, there is a bug in Ghostty. Please report it.";

  responses [
    cancel: _("Deny") suggested,
    ok: _("Allow") destructive,
  ]

  default-response: "cancel";
  close-response: "cancel";

  extra-child: ListBox {
    selection-mode: none;

    Overlay {
      styles [
        "osd",
        "clipboard-overlay",
... (57 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.2/close-confirmation-dialog.blp">
using Gtk 4.0;
// This is unused but if we remove it we get a blueprint-compiler error.
using Adw 1;

template $GhosttyCloseConfirmationDialog: $GhosttyDialog {
  responses [
    cancel: _("Cancel"),
    close: _("Close") destructive,
  ]

  close-response: "cancel";
}
</file>

<file path="src/apprt/gtk/ui/1.2/config-errors-dialog.blp">
using Gtk 4.0;
// This is unused but if we remove it we get a blueprint-compiler error.
using Adw 1;

template $GhosttyConfigErrorsDialog: $GhosttyDialog {
  heading: _("Configuration Errors");
  body: _(
    "One or more configuration errors were found. Please review the errors below, and either reload your configuration or ignore these errors."
  );

  responses [
    ignore: _("Ignore"),
    reload: _("Reload Configuration") suggested,
  ]

  extra-child: ScrolledWindow {
    min-content-width: 500;
    min-content-height: 100;

    TextView {
      editable: false;
      cursor-visible: false;
      top-margin: 8;
      bottom-margin: 8;
      left-margin: 8;
      right-margin: 8;
      buffer: bind (template.config as <$GhosttyConfig>).diagnostics-buffer;
    }
  };
}
... (1 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.2/debug-warning.blp">
using Gtk 4.0;

template $GhosttyDebugWarning: Gtk.Box {
  orientation: vertical;

  Gtk.Label {
    label: _("⚠️ You're running a debug build of Ghostty! Performance will be degraded.");
    margin-top: 10;
    margin-bottom: 10;
  }
}
</file>

<file path="src/apprt/gtk/ui/1.2/key-state-overlay.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttyKeyStateOverlay: Adw.Bin {
  visible: bind $has_state(template.has-tables, template.has-sequence) as <bool>;
  valign-target: end;
  halign: center;
  valign: bind template.valign-target;

  GestureDrag {
    button: 1;
    propagation-phase: capture;
    drag-end => $on_drag_end();
  }

  Adw.Bin {
    Box container {
      styles [
        "background",
        "key-state-overlay",
      ]

      orientation: horizontal;
      spacing: 6;

      Image {
        icon-name: "input-keyboard-symbolic";
        pixel-size: 16;
      }

... (29 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.2/resize-overlay.blp">
using Gtk 4.0;
using Adw 1;
// We can't inherit directly from Label because its an opaque
// type in zig-gobject.
template $GhosttyResizeOverlay: Adw.Bin {
  visible: false;
  can-focus: false;
  can-target: false;
  focusable: false;
  focus-on-click: false;
  duration: 750;
  first-delay: 250;
  overlay-halign: center;
  overlay-valign: center;
  // See surface.blp for why we need to wrap this.
  Adw.Bin {
    Label label {
      styles [
        "background",
        "resize-overlay",
      ]

      can-focus: false;
      can-target: false;
      focusable: false;
      focus-on-click: false;
      selectable: false;
      justify: center;
      halign: bind template.overlay-halign;
      valign: bind template.overlay-valign;
... (4 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.2/search-overlay.blp">
using Gtk 4.0;
using Gdk 4.0;
using Adw 1;

template $GhosttySearchOverlay: Adw.Bin {
  visible: bind template.active;
  halign-target: end;
  valign-target: start;
  halign: bind template.halign-target;
  valign: bind template.valign-target;

  GestureDrag {
    button: 1;
    propagation-phase: capture;
    drag-end => $on_drag_end();
  }

  Adw.Bin {
    Box container {
      styles [
        "background",
        "search-overlay",
      ]

      orientation: horizontal;
      spacing: 6;

      SearchEntry search_entry {
        placeholder-text: _("Find…");
        width-chars: 20;
... (70 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.2/surface.blp">
using Gtk 4.0;
using Adw 1;

Adw.StatusPage error_page {
  icon-name: "computer-fail-symbolic";
  title: _("Oh, no.");
  description: _("Unable to acquire an OpenGL context for rendering.");

  child: LinkButton {
    label: "https://ghostty.org/docs/help/gtk-opengl-context";
    uri: "https://ghostty.org/docs/help/gtk-opengl-context";
  };
}

Overlay terminal_page {
  focusable: false;
  focus-on-click: false;

  child: Box {
    hexpand: true;
    vexpand: true;

    $GhosttyRenderSurface render_surface {
      realize => $render_surface_realize();
      unrealize => $render_surface_unrealize();
      map => $render_surface_map();
      unmap => $render_surface_unmap();
      resize => $render_surface_resize();
      hexpand: true;
      vexpand: true;
... (410 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.3/debug-warning.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttyDebugWarning: Adw.Bin {
  Adw.Banner {
    title: _("⚠️ You're running a debug build of Ghostty! Performance will be degraded.");
    revealed: true;
  }
}
</file>

<file path="src/apprt/gtk/ui/1.3/surface-child-exited.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttySurfaceChildExited: Adw.Bin {
  styles [
    "child-exited",
  ]

  notify::data => $notify_data();

  Adw.Bin {
    Adw.Banner banner {
      button-clicked => $clicked();
      revealed: true;
      // Not localized on purpose because it should never be seen.
      title: "This is a bug in Ghostty. Please report it.";
      button-label: _("Close");
      halign: fill;
      valign: end;
    }
  }
}
</file>

<file path="src/apprt/gtk/ui/1.4/clipboard-confirmation-dialog.blp">
using Gtk 4.0;
// This is unused but if we remove it we get a blueprint-compiler error.
using Adw 1;

template $GhosttyClipboardConfirmationDialog: $GhosttyDialog {
  styles [
    "clipboard-confirmation-dialog",
  ]

  notify::blur => $notify_blur();
  notify::request => $notify_request();
  heading: _("Authorize Clipboard Access");
  // Not localized because this is a placeholder users never see.
  body: "If you see this text, there is a bug in Ghostty. Please report it.";

  responses [
    cancel: _("Deny") suggested,
    ok: _("Allow") destructive,
  ]

  default-response: "cancel";
  close-response: "cancel";

  extra-child: ListBox {
    selection-mode: none;

    Overlay {
      styles [
        "osd",
        "clipboard-overlay",
... (67 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.5/command-palette.blp">
using Gtk 4.0;
using Gio 2.0;
using Adw 1;

Adw.Dialog dialog {
  content-width: 700;
  closed => $closed();

  Adw.ToolbarView {
    top-bar-style: flat;

    [top]
    Adw.HeaderBar {
      [title]
      Gtk.SearchEntry search {
        hexpand: true;
        placeholder-text: _("Execute a command…");
        stop-search => $search_stopped();
        activate => $search_activated();

        styles [
          "command-palette-search",
        ]
      }
    }

    Gtk.ScrolledWindow {
      min-content-height: 300;

      Gtk.ListView view {
... (81 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.5/imgui-widget.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttyImguiWidget: Adw.Bin {
  styles [
    "imgui",
  ]

  Adw.Bin {
    Gtk.GLArea gl_area {
      auto-render: true;
      // needs to be focusable so that we can receive events
      focusable: true;
      focus-on-click: true;
      // Match GTK's shared context, which may use desktop GL or GLES.
      allowed-apis: gl | gles;
      realize => $realize();
      unrealize => $unrealize();
      resize => $resize();
      render => $render();

      EventControllerFocus {
        enter => $focus_enter();
        leave => $focus_leave();
      }

      EventControllerKey {
        key-pressed => $key_pressed();
        key-released => $key_released();
      }
... (23 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.5/inspector-widget.blp">
using Gtk 4.0;

template $GhosttyInspectorWidget: $GhosttyImguiWidget {
  styles [
    "inspector",
  ]

  hexpand: true;
  vexpand: true;
}
</file>

<file path="src/apprt/gtk/ui/1.5/inspector-window.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttyInspectorWindow: Adw.ApplicationWindow {
  title: _("Ghostty: Terminal Inspector");
  icon-name: "com.mitchellh.ghostty";
  default-width: 1000;
  default-height: 600;

  styles [
    "inspector",
  ]

  content: Adw.ToolbarView {
    [top]
    Adw.HeaderBar {
      title-widget: Adw.WindowTitle {
        title: bind template.title;
      };
    }

    Gtk.Box {
      orientation: vertical;
      spacing: 0;
      hexpand: true;
      vexpand: true;

      $GhosttyDebugWarning {
        visible: bind template.debug;
      }
... (9 lines truncated)
</file>

<file path="src/apprt/gtk/ui/1.5/split-tree-split.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttySplitTreeSplit: Adw.Bin {
  styles [
    "split",
  ]

  // The double-nesting is required due to a GTK bug where you can't
  // bind the first child of a builder layout. If you do, you get a double
  // dispose. Easiest way to see that is simply remove this and see the
  // GTK critical errors (and sometimes crashes).
  Adw.Bin {
    Paned paned {
      notify::max-position => $notify_max_position();
      notify::position => $notify_position();
    }
  }
}
</file>

<file path="src/apprt/gtk/ui/1.5/split-tree.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttySplitTree: Box {
  notify::tree => $notify_tree();
  orientation: vertical;

  Adw.Bin tree_bin {
    visible: bind template.has-surfaces;
    hexpand: true;
    vexpand: true;
  }

  // This could be a lot more visually pleasing but in practice this doesn't
  // ever happen at the time of writing this comment. A surface-less split
  // tree always closes its parent.
  Label {
    visible: bind template.has-surfaces inverted;
    // Purposely not localized currently because this shouldn't really
    // ever appear. When we have a situation it does appear, we may want
    // to change the styling and text so I don't want to burden localizers
    // to handle this yet.
    label: "No surfaces.";
  }
}
</file>

<file path="src/apprt/gtk/ui/1.5/surface-scrolled-window.blp">
using Gtk 4.0;
using Adw 1;

template $GhostttySurfaceScrolledWindow: Adw.Bin {
  notify::surface => $notify_surface();
  // The double-nesting is required due to a GTK bug where you can't
  // bind the first child of a builder layout. If you do, you get a double
  // dispose. Easiest way to see that is simply remove this and see the
  // GTK critical errors (and sometimes crashes).
  Adw.Bin {
    Gtk.ScrolledWindow scrolled_window {
      hscrollbar-policy: never;
      vscrollbar-policy: bind $scrollbar_policy(template.config) as <Gtk.PolicyType>;
    }
  }
}
</file>

<file path="src/apprt/gtk/ui/1.5/tab.blp">
using Gtk 4.0;

template $GhosttyTab: Box {
  styles [
    "tab",
  ]

  orientation: vertical;
  hexpand: true;
  vexpand: true;
  title: bind $computed_title(
    template.config,
    split_tree.active-surface as <$GhosttySurface>.title,
    split_tree.active-surface as <$GhosttySurface>.title-override,
    template.title-override,
    split_tree.is-zoomed,
    split_tree.active-surface as <$GhosttySurface>.bell-ringing
    ) as <string>;
  tooltip: bind split_tree.active-surface as <$GhosttySurface>.pwd;

  $GhosttySplitTree split_tree {
    notify::active-surface => $notify_active_surface();
    notify::tree => $notify_tree();
  }
}
</file>

<file path="src/apprt/gtk/ui/1.5/title-dialog.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttyTitleDialog: Adw.AlertDialog {
  body: _("Leave blank to restore the default title.");

  responses [
    cancel: _("Cancel"),
    ok: _("OK") suggested,
  ]

  default-response: "ok";
  focus-widget: entry;

  extra-child: Entry entry {
    activates-default: true;
  };
}
</file>

<file path="src/apprt/gtk/ui/1.5/window.blp">
using Gtk 4.0;
using Adw 1;

template $GhosttyWindow: Adw.ApplicationWindow {
  styles [
    "window",
  ]

  close-request => $close_request();
  realize => $realize();
  notify::config => $notify_config();
  notify::fullscreened => $notify_fullscreened();
  notify::is-active => $notify_is_active();
  notify::maximized => $notify_maximized();
  notify::quick-terminal => $notify_quick_terminal();
  notify::scale-factor => $notify_scale_factor();
  default-width: 800;
  default-height: 600;
  // GTK4 grabs F10 input by default to focus the menubar icon. We want
  // to disable this so that terminal programs can capture F10 (such as htop)
  handle-menubar-accel: false;

  content: Adw.TabOverview tab_overview {
    create-tab => $overview_create_tab();
    notify::open => $overview_notify_open();
    view: tab_view;
    enable-new-tab: true;
    // Disable the title buttons (close, maximize, minimize, ...)
    // *inside* the tab overview if CSDs are disabled.
    // We do spare the search button, though.
... (313 lines truncated)
</file>

<file path="src/apprt/gtk/winproto/wayland/protocols/vicinae-hotkey-v1.xml">
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="vicinae_hotkey_v1">
  <copyright>
    Copyright © 2026 Aurelien Brabant
    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.
  </copyright>
  <description summary="client-managed global hotkeys">
    This protocol lets a client choose, and freely reconfigure, its own
    global hotkeys: it requests a specific key combination and the compositor
    accepts it or rejects it with a reason. The compositor remains the eventual
    arbiter (it may deny a request, revoke a binding at any time, or apply
    whatever policy it likes), but within that the application manages its own
    bindings, including changing them at runtime, with no out-of-band user
    configuration and no persisted compositor state.
    A hotkey is a key combination that fires regardless of which surface holds
... (236 lines truncated)
</file>

<file path="src/apprt/gtk/winproto/wayland/Globals.zig">
const Globals = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;

const wayland = @import("wayland");
const wl = wayland.client.wl;
const ext = wayland.client.ext;
const kde = wayland.client.kde;
const org = wayland.client.org;
const vicinae = wayland.client.vicinae;
const xdg = wayland.client.xdg;

const log = std.log.scoped(.winproto_wayland_globals);

alloc: Allocator,
state: State,
map: std.EnumMap(Tag, Binding),

/// Used in the initial roundtrip to determine whether more
/// roundtrips are required to fetch the initial state.
needs_roundtrip: bool = false,

const Binding = struct {
    // All globals can be casted into a wl.Proxy object.
    proxy: *wl.Proxy,
    name: u32,
};

pub const Tag = enum {
... (226 lines truncated)
</file>

<file path="src/apprt/gtk/winproto/wayland/Hotkeys.zig">
//! Global shortcuts backed by the vicinae-hotkey Wayland protocol.
const Hotkeys = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;

const wayland = @import("wayland");
const vicinae = wayland.client.vicinae;

const Config = @import("../../../../config.zig").Config;
const Binding = @import("../../../../input.zig").Binding;
const key = @import("../../key.zig");
const GlobalShortcuts = @import("../../class/global_shortcuts.zig").GlobalShortcuts;

const log = std.log.scoped(.winproto_wayland_hotkeys);

alloc: Allocator,
app_id: [:0]const u8,
entries: std.ArrayList(Entry) = .empty,

const Entry = struct {
    /// Null once the binding was denied or revoked.
    hotkey: ?*vicinae.HotkeyV1,
    trigger: Binding.Trigger,
    action: Binding.Action,
    shortcuts: *GlobalShortcuts,

    fn deinit(self: *Entry) void {
        if (self.hotkey) |hotkey| hotkey.destroy();
    }
... (136 lines truncated)
</file>

<file path="src/apprt/gtk/winproto/BlurRegion.zig">
const BlurRegion = @This();
const std = @import("std");
const Allocator = std.mem.Allocator;

const gobject = @import("gobject");
const gdk = @import("gdk");
const gtk = @import("gtk");

const Window = @import("../winproto.zig").Window;
const ApprtWindow = @import("../class/window.zig").Window;

slices: std.ArrayList(Slice),

/// A rectangular slice of the blur region.
// Marked `extern` since we want to be able to use this in X11 directly.
pub const Slice = extern struct {
    x: Pos,
    y: Pos,
    width: Pos,
    height: Pos,
};

// X11 compatibility. Ideally this should just be an `i32` like Wayland,
// but XLib sucks
const Pos = c_long;

pub const empty: BlurRegion = .{
    .slices = .empty,
};

... (158 lines truncated)
</file>

<file path="src/apprt/gtk/winproto/noop.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

const gdk = @import("gdk");

const Config = @import("../../../config.zig").Config;
const input = @import("../../../input.zig");
const ApprtWindow = @import("../class/window.zig").Window;
const GlobalShortcuts = @import("../class/global_shortcuts.zig").GlobalShortcuts;

const log = std.log.scoped(.winproto_noop);

pub const App = struct {
    pub fn init(
        _: Allocator,
        _: *gdk.Display,
        _: [:0]const u8,
        _: *const Config,
    ) !?App {
        return null;
    }

    pub fn deinit(self: *App) void {
        _ = self;
    }

    pub fn eventMods(
        _: *App,
        _: ?*gdk.Device,
        _: gdk.ModifierType,
... (55 lines truncated)
</file>

<file path="src/apprt/gtk/winproto/wayland.zig">
//! Wayland protocol implementation for the Ghostty GTK apprt.
const std = @import("std");
const Allocator = std.mem.Allocator;

const gdk = @import("gdk");
const gdk_wayland = @import("gdk_wayland");
const gobject = @import("gobject");
const gtk = @import("gtk");
const layer_shell = @import("gtk4-layer-shell");

const wayland = @import("wayland");
const wl = wayland.client.wl;
const ext = wayland.client.ext;
const kde = wayland.client.kde;
const org = wayland.client.org;
const xdg = wayland.client.xdg;

const Config = @import("../../../config.zig").Config;
const Globals = @import("wayland/Globals.zig");
const Hotkeys = @import("wayland/Hotkeys.zig");
const input = @import("../../../input.zig");
const ApprtWindow = @import("../class/window.zig").Window;
const GlobalShortcuts = @import("../class/global_shortcuts.zig").GlobalShortcuts;
const BlurRegion = @import("BlurRegion.zig");
const gtk_version = @import("../gtk_version.zig");

const log = std.log.scoped(.winproto_wayland);

/// Wayland state that contains application-wide Wayland objects (e.g. wl_display).
pub const App = struct {
... (486 lines truncated)
</file>

<file path="src/apprt/gtk/winproto/x11.zig">
//! X11 window protocol implementation for the Ghostty GTK apprt.
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;

const gdk = @import("gdk");
const gdk_x11 = @import("gdk_x11");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");
const xlib = @import("xlib");

pub const c = @import("x11_c");

const input = @import("../../../input.zig");
const Config = @import("../../../config.zig").Config;
const ApprtWindow = @import("../class/window.zig").Window;
const GlobalShortcuts = @import("../class/global_shortcuts.zig").GlobalShortcuts;
const BlurRegion = @import("BlurRegion.zig");

const log = std.log.scoped(.gtk_x11);

pub const App = struct {
    display: *xlib.Display,
    base_event_code: c_int,
    atoms: Atoms,

    pub fn init(
        _: Allocator,
        gdk_display: *gdk.Display,
... (476 lines truncated)
</file>

<file path="src/apprt/gtk/adw_version.zig">
const std = @import("std");

// Until the gobject bindings are built at the same time we are building
// Ghostty, we need to import `adwaita.h` directly to ensure that the version
// macros match the version of `libadwaita` that we are building/linking
// against.
const adw_c = @import("adw_c");

const adw = @import("adw");

const log = std.log.scoped(.gtk);

pub const comptime_version: std.SemanticVersion = .{
    .major = adw_c.ADW_MAJOR_VERSION,
    .minor = adw_c.ADW_MINOR_VERSION,
    .patch = adw_c.ADW_MICRO_VERSION,
};

pub fn getRuntimeVersion() std.SemanticVersion {
    return .{
        .major = adw.getMajorVersion(),
        .minor = adw.getMinorVersion(),
        .patch = adw.getMicroVersion(),
    };
}

pub fn logVersion() void {
    log.info("libadwaita version build={f} runtime={f}", .{
        comptime_version,
        getRuntimeVersion(),
... (91 lines truncated)
</file>

<file path="src/apprt/gtk/App.zig">
/// This is the main entrypoint to the apprt for Ghostty. Ghostty will
/// initialize this in main to start the application..
const App = @This();

const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const apprt = @import("../../apprt.zig");
const configpkg = @import("../../config.zig");
const Config = configpkg.Config;
const CoreApp = @import("../../App.zig");

const Application = @import("class/application.zig").Application;
const Surface = @import("Surface.zig");
const ipcNewWindow = @import("ipc/new_window.zig").newWindow;
const ipcNewTab = @import("ipc/new_tab.zig").newTab;
const ipcToggleQuickTerminal = @import("ipc/toggle_quick_terminal.zig").toggleQuickTerminal;

const log = std.log.scoped(.gtk);

/// GTK application ID
pub const application_id = @import("build/info.zig").application_id;

/// GTK object path
pub const object_path = @import("build/info.zig").object_path;

/// The GObject Application instance
app: *Application,

pub fn init(
... (63 lines truncated)
</file>

<file path="src/apprt/gtk/cgroup.zig">
/// Contains all the logic for putting individual surfaces into
/// transient systemd scopes.
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../../quirks.zig").inlineAssert;

const gio = @import("gio");
const glib = @import("glib");

const internal_os = @import("../../os/main.zig");

const log = std.log.scoped(.gtk_systemd_cgroup);

pub const Options = struct {
    memory_high: ?u64 = null,
    tasks_max: ?u64 = null,
};

pub fn fmtScope(buf: []u8, pid: u32) [:0]const u8 {
    const fmt = "app-ghostty-surface-transient-{}.scope";

    assert(buf.len >= fmt.len - 2 + std.math.log10_int(@as(usize, std.math.maxInt(@TypeOf(pid)))) + 1);

    return std.fmt.bufPrintZ(buf, fmt, .{pid}) catch unreachable;
}

/// Create a transient systemd scope unit for the given process and
/// move the process into it.
pub fn createScope(
    dbus: *gio.DBusConnection,
... (86 lines truncated)
</file>

<file path="src/apprt/gtk/class.zig">
//! This files contains all the GObject classes for the GTK apprt
//! along with helpers to work with them.

const std = @import("std");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

const ext = @import("ext.zig");
pub const Application = @import("class/application.zig").Application;
pub const Window = @import("class/window.zig").Window;
pub const Config = @import("class/config.zig").Config;
pub const Surface = @import("class/surface.zig").Surface;
pub const RenderSurface = @import("class/render_surface.zig").RenderSurface;

/// Common methods for all GObject classes we create.
pub fn Common(
    comptime Self: type,
    comptime Private: ?type,
) type {
    return struct {
        /// Upcast our type to a parent type or interface. This will fail at
        /// compile time if the cast isn't 100% safe. For unsafe casts,
        /// use `gobject.ext.cast` instead. We don't have a helper for that
        /// because its uncommon and unsafe behavior should be noisier.
        pub fn as(self: *Self, comptime T: type) *T {
            return gobject.ext.as(T, self);
        }

        /// Increase the reference count of the object.
... (347 lines truncated)
</file>

<file path="src/apprt/gtk/ext.zig">
//! Extensions/helpers for GTK objects, following a similar naming
//! style to zig-gobject. These should, wherever possible, be Zig-friendly
//! wrappers around existing GTK functionality, rather than complex new
//! helpers.

const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const testing = std.testing;

const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");

pub const actions = @import("ext/actions.zig");
const slice = @import("ext/slice.zig");
pub const StringList = slice.StringList;

/// Wrapper around `gobject.boxedCopy` to copy a boxed type `T`.
pub fn boxedCopy(comptime T: type, ptr: *const T) *T {
    const copy = gobject.boxedCopy(T.getGObjectType(), ptr);
    return @ptrCast(@alignCast(copy));
}

/// Wrapper around `gobject.boxedFree` to free a boxed type `T`.
pub fn boxedFree(comptime T: type, ptr: ?*T) void {
    if (ptr) |p| gobject.boxedFree(
        T.getGObjectType(),
        p,
    );
}
... (41 lines truncated)
</file>

<file path="src/apprt/gtk/flatpak.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const build_config = @import("../../build_config.zig");
const internal_os = @import("../../os/main.zig");
const glib = @import("glib");

pub fn resourcesDir(alloc: Allocator) !internal_os.ResourcesDir {
    if (comptime build_config.flatpak) {
        // Only consult Flatpak runtime data for host case.
        if (internal_os.isFlatpak()) {
            var result: internal_os.ResourcesDir = .{
                .app_path = try alloc.dupe(u8, "/app/share/ghostty"),
            };
            errdefer alloc.free(result.app_path.?);

            const keyfile = glib.KeyFile.new();
            defer keyfile.unref();

            if (keyfile.loadFromFile("/.flatpak-info", .{}, null) == 0) return result;
            const app_dir = std.mem.span(keyfile.getString("Instance", "app-path", null)) orelse return result;
            defer glib.free(app_dir.ptr);

            result.host_path = try std.fs.path.join(alloc, &[_][]const u8{ app_dir, "share", "ghostty" });
            return result;
        }
    }

    return try internal_os.resourcesDir(alloc);
}
</file>

<file path="src/apprt/gtk/gsettings.zig">
const std = @import("std");
const gtk = @import("gtk");
const gobject = @import("gobject");

/// GTK Settings keys with well-defined types.
pub const Key = enum {
    @"gtk-enable-primary-paste",
    @"gtk-xft-dpi",
    @"gtk-font-name",

    fn Type(comptime self: Key) type {
        return switch (self) {
            .@"gtk-enable-primary-paste" => bool,
            .@"gtk-xft-dpi" => c_int,
            .@"gtk-font-name" => []const u8,
        };
    }

    fn GValueType(comptime self: Key) type {
        return switch (self.Type()) {
            bool => c_int,
            c_int => c_int,
            []const u8 => ?[*:0]const u8,
            else => @compileError("Unsupported type for GTK settings"),
        };
    }

    /// Returns true if this setting type requires memory allocation.
    /// Types that do not need allocation must be explicitly marked.
    fn requiresAllocation(comptime self: Key) bool {
... (72 lines truncated)
</file>

<file path="src/apprt/gtk/gtk_version.zig">
const std = @import("std");

// Until the gobject bindings are built at the same time we are building
// Ghostty, we need to import `gtk/gtk.h` directly to ensure that the version
// macros match the version of `gtk4` that we are building/linking against.
const gtk_c = @import("gtk_c");

const gtk = @import("gtk");

const log = std.log.scoped(.gtk);

pub const comptime_version: std.SemanticVersion = .{
    .major = gtk_c.GTK_MAJOR_VERSION,
    .minor = gtk_c.GTK_MINOR_VERSION,
    .patch = gtk_c.GTK_MICRO_VERSION,
};

pub fn getRuntimeVersion() std.SemanticVersion {
    return .{
        .major = gtk.getMajorVersion(),
        .minor = gtk.getMinorVersion(),
        .patch = gtk.getMicroVersion(),
    };
}

pub fn logVersion() void {
    log.info("GTK version build={f} runtime={f}", .{
        comptime_version,
        getRuntimeVersion(),
    });
... (109 lines truncated)
</file>

<file path="src/apprt/gtk/key.zig">
const std = @import("std");

const gdk = @import("gdk");
const glib = @import("glib");
const gtk = @import("gtk");

const input = @import("../../input.zig");
const winproto = @import("winproto.zig");

/// Returns a GTK accelerator string from a trigger.
pub fn accelFromTrigger(
    buf: []u8,
    trigger: input.Binding.Trigger,
) error{WriteFailed}!?[:0]const u8 {
    var writer: std.Io.Writer = .fixed(buf);

    // Modifiers
    if (trigger.mods.shift) try writer.writeAll("<Shift>");
    if (trigger.mods.ctrl) try writer.writeAll("<Ctrl>");
    if (trigger.mods.alt) try writer.writeAll("<Alt>");
    if (trigger.mods.super) try writer.writeAll("<Super>");

    // Write our key
    if (!try writeTriggerKey(&writer, trigger)) return null;

    // We need to make the string null terminated.
    try writer.writeByte(0);
    const slice = writer.buffered();
    return slice[0 .. slice.len - 1 :0];
}
... (626 lines truncated)
</file>

<file path="src/apprt/gtk/media.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;

const log = std.log.scoped(.gtk_media);

const gio = @import("gio");
const glib = @import("glib");
const gobject = @import("gobject");
const gtk = @import("gtk");
const global = @import("../../global.zig");

pub fn fromFilename(path: [:0]const u8) ?*gtk.MediaFile {
    assert(std.fs.path.isAbsolute(path));
    std.Io.Dir.accessAbsolute(
        global.io(),
        path,
        .{ .read = true },
    ) catch |err| {
        log.warn("unable to access {s}: {t}", .{ path, err });
        return null;
    };
    return gtk.MediaFile.newForFilename(path);
}

pub fn fromResource(path: [:0]const u8) ?*gtk.MediaFile {
    assert(std.fs.path.isAbsolute(path));
    var gerr: ?*glib.Error = null;

    const found = gio.resourcesGetInfo(path, .{}, null, null, &gerr);
    if (gerr) |err| {
... (133 lines truncated)
</file>

<file path="src/apprt/gtk/portal.zig">
const std = @import("std");

const gio = @import("gio");
const global = @import("../../global.zig");

const Allocator = std.mem.Allocator;

pub const OpenURI = @import("portal/OpenURI.zig");
pub const token_hex_len = @sizeOf(usize) * 2;
pub const TokenBuffer = [token_hex_len + 1]u8;
const token_format = std.fmt.comptimePrint("{{x:0>{}}}", .{token_hex_len});

/// Generate a token suitable for use in requests to the XDG Desktop Portal
pub fn generateToken() usize {
    const rng_impl: std.Random.IoSource = .{ .io = global.io() };
    return rng_impl.interface().int(usize);
}

/// Format a request token consistently for use in portal object paths and payloads.
pub fn formatToken(buf: *TokenBuffer, token: usize) [:0]const u8 {
    return std.fmt.bufPrintZ(buf, token_format, .{token}) catch unreachable;
}

/// Get the XDG portal request path for the current Ghostty instance.
///
/// See https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html
/// for the protocol of the Request interface.
pub fn getRequestPath(alloc: Allocator, dbus: *gio.DBusConnection, token: usize) (Allocator.Error || error{NoDBusUniqueName})![:0]const u8 {
    // Get the unique name from D-Bus and strip the leading `:`
    const unique_name = std.mem.span(
... (78 lines truncated)
</file>

<file path="src/apprt/gtk/post_fork.zig">
const std = @import("std");

const gio = @import("gio");
const glib = @import("glib");
const global = @import("../../global.zig");

const log = std.log.scoped(.gtk_post_fork);

const configpkg = @import("../../config.zig");
const internal_os = @import("../../os/main.zig");
const Command = @import("../../Command.zig");
const cgroup = @import("./cgroup.zig");

const Application = @import("class/application.zig").Application;

pub const PostForkInfo = struct {
    gtk_single_instance: configpkg.Config.GtkSingleInstance,
    linux_cgroup: configpkg.Config.LinuxCgroup,
    linux_cgroup_hard_fail: bool,
    linux_cgroup_memory_limit: ?u64,
    linux_cgroup_processes_limit: ?u64,

    pub fn init(cfg: *const configpkg.Config) PostForkInfo {
        return .{
            .gtk_single_instance = cfg.@"gtk-single-instance",
            .linux_cgroup = cfg.@"linux-cgroup",
            .linux_cgroup_hard_fail = cfg.@"linux-cgroup-hard-fail",
            .linux_cgroup_memory_limit = cfg.@"linux-cgroup-memory-limit",
            .linux_cgroup_processes_limit = cfg.@"linux-cgroup-processes-limit",
        };
... (91 lines truncated)
</file>

<file path="src/apprt/gtk/pre_exec.zig">
const std = @import("std");

const log = std.log.scoped(.gtk_pre_exec);

const configpkg = @import("../../config.zig");
const global = @import("../../global.zig");

const internal_os = @import("../../os/main.zig");
const Command = @import("../../Command.zig");
const cgroup = @import("./cgroup.zig");

pub const PreExecInfo = struct {
    gtk_single_instance: configpkg.Config.GtkSingleInstance,
    linux_cgroup: configpkg.Config.LinuxCgroup,
    linux_cgroup_hard_fail: bool,

    pub fn init(cfg: *const configpkg.Config) PreExecInfo {
        return .{
            .gtk_single_instance = cfg.@"gtk-single-instance",
            .linux_cgroup = cfg.@"linux-cgroup",
            .linux_cgroup_hard_fail = cfg.@"linux-cgroup-hard-fail",
        };
    }
};

/// If we are expecting to be moved to a transient systemd scope, wait to see if
/// that happens by checking for the correct name of the current cgroup. Wait at
/// most 250ms so that we don't overly delay the soft-fail scenario.
///
/// If we are configured to hard fail, log an error message and return an error
... (51 lines truncated)
</file>

<file path="src/apprt/gtk/scale.zig">
const std = @import("std");
const gobject = @import("gobject");
const graphene = @import("graphene");
const gtk = @import("gtk");

pub const DeviceSize = struct {
    width: u32,
    height: u32,
};

pub const CssPoint = struct {
    x: f64,
    y: f64,
};

/// Scale, GdkSurface-space origin, and snapped device size for one widget.
pub const Layout = struct {
    scale: f64,
    origin: CssPoint,
    size: DeviceSize,

    /// CSS offset that moves widget (0,0) onto the nearest device pixel.
    pub fn snapOrigin(self: Layout) CssPoint {
        return .{
            .x = snapOffset(self.origin.x, self.scale),
            .y = snapOffset(self.origin.y, self.scale),
        };
    }
};

... (157 lines truncated)
</file>

<file path="src/apprt/gtk/Surface.zig">
const Self = @This();

const std = @import("std");
const apprt = @import("../../apprt.zig");
const configpkg = @import("../../config.zig");
const CoreSurface = @import("../../Surface.zig");
const ApprtApp = @import("App.zig");
const Application = @import("class/application.zig").Application;
const Surface = @import("class/surface.zig").Surface;

/// The GObject Surface
surface: *Surface,

pub fn deinit(self: *Self) void {
    _ = self;
}

/// Returns the GObject surface for this apprt surface. This is a function
/// so we can add some extra logic if we ever have to here.
pub fn gobj(self: *Self) *Surface {
    return self.surface;
}

pub fn core(self: *Self) *CoreSurface {
    // This asserts the non-optional because libghostty should only
    // be calling this for initialized surfaces.
    return self.surface.core().?;
}

pub fn rtApp(self: *Self) *ApprtApp {
... (75 lines truncated)
</file>

<file path="src/apprt/gtk/weak_ref.zig">
const std = @import("std");
const gtk = @import("gtk");
const gobject = @import("gobject");

/// A lightweight wrapper around gobject.WeakRef to make it type-safe
/// to hold a single type of value.
pub fn WeakRef(comptime T: type) type {
    return struct {
        const Self = @This();

        ref: gobject.WeakRef = std.mem.zeroes(gobject.WeakRef),

        pub const empty: Self = .{};

        /// Set the weak reference to the given object. This will not
        /// increase the reference count of the object.
        pub fn set(self: *Self, v_: ?*T) void {
            if (v_) |v| {
                self.ref.set(v.as(gobject.Object));
            } else {
                self.ref.set(null);
            }
        }

        /// Release this weak reference.
        ///
        /// You MUST call this before the memory holding this struct is freed,
        /// which in practice means from the owner's `dispose`. The target keeps
        /// a pointer to this `GWeakRef` so that it can clear it when the target
        /// is finalized; if this memory is gone by then, the target walks into
... (32 lines truncated)
</file>

<file path="src/apprt/gtk/winproto.zig">
const std = @import("std");
const build_options = @import("build_options");
const Allocator = std.mem.Allocator;

const gdk = @import("gdk");

const Config = @import("../../config.zig").Config;
const input = @import("../../input.zig");
const key = @import("key.zig");
const ApprtWindow = @import("class/window.zig").Window;
const GlobalShortcuts = @import("class/global_shortcuts.zig").GlobalShortcuts;

pub const noop = @import("winproto/noop.zig");
pub const x11 = @import("winproto/x11.zig");
pub const wayland = @import("winproto/wayland.zig");

pub const Protocol = enum {
    none,
    wayland,
    x11,
};

/// App-state for the underlying windowing protocol. There should be one
/// instance of this struct per application.
pub const App = union(Protocol) {
    none: noop.App,
    wayland: if (build_options.wayland) wayland.App else noop.App,
    x11: if (build_options.x11) x11.App else noop.App,

    pub fn init(
... (147 lines truncated)
</file>

<file path="src/apprt/action.zig">
const std = @import("std");
const build_config = @import("../build_config.zig");
const assert = @import("../quirks.zig").inlineAssert;
const apprt = @import("../apprt.zig");
const configpkg = @import("../config.zig");
const input = @import("../input.zig");
const renderer = @import("../renderer.zig");
const terminal = @import("../terminal/main.zig");
const CoreSurface = @import("../Surface.zig");
const lib = @import("../lib/main.zig");
const compat_testing = @import("../lib/compat/testing.zig");

/// The target for an action. This is generally the thing that had focus
/// while the action was made but the concept of "focus" is not guaranteed
/// since actions can also be triggered by timers, scripts, etc.
pub const Target = union(Key) {
    app,
    surface: *CoreSurface,

    // Sync with: ghostty_target_tag_e
    pub const Key = enum(c_int) {
        app,
        surface,

        test "ghostty.h Target.Key" {
            try lib.checkGhosttyHEnum(Key, "GHOSTTY_TARGET_");
        }
    };

    // Sync with: ghostty_target_u
... (1055 lines truncated)
</file>

<file path="src/apprt/browser.zig">
const internal_os = @import("../os/main.zig");
pub const resourcesDir = internal_os.resourcesDir;
pub const App = struct {};
pub const Window = struct {};
</file>

<file path="src/apprt/embedded.zig">
//! Application runtime for the embedded version of Ghostty. The embedded
//! version is when Ghostty is embedded within a parent host application,
//! rather than owning the application lifecycle itself. This is used for
//! example for the macOS build of Ghostty so that we can use a native
//! Swift+XCode-based application.

const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const objc = @import("objc");
const apprt = @import("../apprt.zig");
const font = @import("../font/main.zig");
const global = @import("../global.zig");
const input = @import("../input.zig");
const internal_os = @import("../os/main.zig");
const renderer = @import("../renderer.zig");
const terminal = @import("../terminal/main.zig");
const CoreApp = @import("../App.zig");
const CoreInspector = @import("../inspector/main.zig").Inspector;
const CoreSurface = @import("../Surface.zig");
const configpkg = @import("../config.zig");
const Config = configpkg.Config;
const String = @import("../main_c.zig").String;

const log = std.log.scoped(.embedded_window);

pub const resourcesDir = internal_os.resourcesDir;

pub const App = struct {
... (2496 lines truncated)
</file>

<file path="src/apprt/gtk.zig">
// The required comptime API for any apprt.
pub const App = @import("gtk/App.zig");
pub const Surface = @import("gtk/Surface.zig");
pub const resourcesDir = @import("gtk/flatpak.zig").resourcesDir;

// The exported API, custom for the apprt.
pub const class = @import("gtk/class.zig");
pub const WeakRef = @import("gtk/weak_ref.zig").WeakRef;
pub const pre_exec = @import("gtk/pre_exec.zig");
pub const post_fork = @import("gtk/post_fork.zig");

test {
    @import("std").testing.refAllDecls(@This());
    _ = @import("gtk/ext.zig");
    _ = @import("gtk/key.zig");
    _ = @import("gtk/portal.zig");
    _ = @import("gtk/scale.zig");
}
</file>

<file path="src/apprt/ipc.zig">
//! Inter-process Communication to a running Ghostty instance from a separate
//! process.
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../quirks.zig").inlineAssert;
const lib = @import("../lib/main.zig");

pub const Errors = error{
    /// The IPC failed. If a function returns this error, it's expected that
    /// an a more specific error message will have been written to stderr (or
    /// otherwise shown to the user in an appropriate way).
    IPCFailed,
};

pub const Target = union(Key) {
    /// Open up a new window in a custom instance of Ghostty.
    class: [:0]const u8,

    /// Detect which instance to open a new window in.
    detect,

    // Sync with: ghostty_ipc_target_tag_e
    pub const Key = enum(c_int) {
        class,
        detect,

        test "ghostty.h Target.Key" {
            try lib.checkGhosttyHEnum(Key, "GHOSTTY_IPC_TARGET_");
        }
    };
... (223 lines truncated)
</file>

<file path="src/apprt/none.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

const internal_os = @import("../os/main.zig");
const apprt = @import("../apprt.zig");
pub const resourcesDir = internal_os.resourcesDir;

pub const App = struct {
    /// Always return false as there is no apprt to communicate with.
    pub fn performIpc(
        _: Allocator,
        _: apprt.ipc.Target,
        comptime action: apprt.ipc.Action.Key,
        _: apprt.ipc.Action.Value(action),
    ) !bool {
        return false;
    }
};
pub const Surface = struct {};
</file>

<file path="src/apprt/runtime.zig">
const std = @import("std");

/// Runtime is the runtime to use for Ghostty. All runtimes do not provide
/// equivalent feature sets.
pub const Runtime = enum {
    /// Will not produce an executable at all when `zig build` is called.
    /// This is only useful if you're only interested in the lib only (macOS).
    none,

    /// GTK4. Rich windowed application. This uses a full GObject-based
    /// approach to building the application.
    gtk,

    pub fn default(target: std.Target) Runtime {
        return switch (target.os.tag) {
            // The Linux and FreeBSD default is GTK because it is a full
            // featured application.
            .linux, .freebsd => .gtk,
            // Otherwise, we do NONE so we don't create an exe and we create
            // libghostty. On macOS, Xcode is used to build the app that links
            // to libghostty.
            else => .none,
        };
    }
};

test {
    _ = Runtime;
}
</file>

<file path="src/apprt/structs.zig">
const std = @import("std");
const build_config = @import("../build_config.zig");
const terminal = @import("../terminal/main.zig");

/// ContentScale is the ratio between the current DPI and the platform's
/// default DPI. This is used to determine how much certain rendered elements
/// need to be scaled up or down.
pub const ContentScale = struct {
    x: f32,
    y: f32,
};

/// The size of the surface in pixels.
pub const SurfaceSize = struct {
    width: u32,
    height: u32,

    pub fn eql(self: *const SurfaceSize, other: *const SurfaceSize) bool {
        return self.width == other.width and self.height == other.height;
    }
};

/// The position of the cursor in pixels.
pub const CursorPos = struct {
    x: f32,
    y: f32,
};

/// Input Method Editor (IME) position.
pub const IMEPos = struct {
... (216 lines truncated)
</file>

<file path="src/apprt/surface.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

const apprt = @import("../apprt.zig");
const build_config = @import("../build_config.zig");
const App = @import("../App.zig");
const Surface = @import("../Surface.zig");
const renderer = @import("../renderer.zig");
const terminal = @import("../terminal/main.zig");
const Config = @import("../config.zig").Config;
const MessageData = @import("../datastruct/main.zig").MessageData;

/// The message types that can be sent to a single surface.
pub const Message = union(enum) {
    /// Represents a write request. Magic number comes from the max size
    /// we want this union to be.
    pub const WriteReq = MessageData(u8, 255);

    /// A fixed-size desktop notification payload sent to the app thread.
    pub const DesktopNotification = struct {
        /// Desktop notification title.
        title: [63:0]u8,

        /// Desktop notification body.
        body: [255:0]u8,

        pub fn init(title: []const u8, body: []const u8) DesktopNotification {
            var result: DesktopNotification = undefined;
            copyUtf8Z(result.title.len, &result.title, title);
            copyUtf8Z(result.body.len, &result.body, body);
... (295 lines truncated)
</file>

<file path="src/benchmark/AGENTS.md">
# Benchmarking

The benchmark tools are split into two roles:

- `ghostty-gen` generates synthetic input data.
- `ghostty-bench` consumes existing input data and runs a benchmark.

## Workflow

- For timing comparisons, generate data first and benchmark it later.
- Do not pipe `ghostty-gen` directly into `ghostty-bench` when comparing
  performance. That mixes generation cost into the measurement and makes
  branch-to-branch comparisons noisy.
- Reuse the exact same generated files when comparing revisions.
- Prefer deterministic generation inputs such as fixed seeds when the
  generator supports them.
- Keep large generated benchmark corpora outside the repository unless the
  change explicitly requires checked-in test data.

## Running Benchmarks

- Prefer `hyperfine` to compare benchmark timings.
- Benchmark the `ghostty-bench` command line, not the generator.
- Use `ghostty-bench ... --data <path>` with pre-generated files.
- Run multiple warmups and repeated measurements so branch comparisons are
  based on medians instead of single runs.
- When comparing branches, keep all benchmark inputs and CLI flags the same,
  including terminal dimensions.
- Never run multiple benchmarks in parallel on the same machine, as they will
  interfere with each other and produce unreliable results.
... (19 lines truncated)
</file>

<file path="src/benchmark/ApcParser.zig">
//! This benchmark tests the throughput of APC sequence parsing
//! through the terminal stream: VT state machine dispatch, APC
//! protocol identification, and the protocol command parsers
//! (e.g. Kitty graphics). Completed commands are parsed and then
//! discarded; command execution (image decoding, storage) is not
//! included so this isolates the parsing path.
const ApcParser = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const terminalpkg = @import("../terminal/main.zig");
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.@"apc-parser-bench");

opts: Options,
stream: Stream,

/// The file, opened in the setup function.
data_f: ?std.Io.File = null,

pub const Options = struct {
    /// The data to read as a filepath. If this is "-" then
    /// we will read stdin. If this is unset, then we will
    /// do nothing (benchmark is a noop). It'd be more unixy to
    /// use stdin by default but I find that a hanging CLI command
    /// with no interaction is a bit annoying.
... (118 lines truncated)
</file>

<file path="src/benchmark/Benchmark.zig">
//! A single benchmark case.
const Benchmark = @This();

const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const macos = @import("macos");
const build_config = @import("../build_config.zig");
const global = @import("../global.zig");

ptr: *anyopaque,
vtable: VTable,

/// Create a new benchmark from a pointer and a vtable.
///
/// This usually is only called by benchmark implementations, not
/// benchmark users.
pub fn init(
    pointer: anytype,
    vtable: VTable,
) Benchmark {
    const Ptr = @TypeOf(pointer);
    assert(@typeInfo(Ptr) == .pointer); // Must be a pointer
    assert(@typeInfo(Ptr).pointer.size == .one); // Must be a single-item pointer
    assert(@typeInfo(@typeInfo(Ptr).pointer.child) == .@"struct"); // Must point to a struct
    return .{ .ptr = pointer, .vtable = vtable };
}

/// Run the benchmark.
pub fn run(
... (152 lines truncated)
</file>

<file path="src/benchmark/CApi.zig">
const std = @import("std");
const cli = @import("cli.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.benchmark);

/// Run the Ghostty benchmark CLI with the given action and arguments.
export fn ghostty_benchmark_cli(
    action_name_: [*:0]const u8,
    args: [*:0]const u8,
) bool {
    const action_name = std.mem.sliceTo(action_name_, 0);
    const action: cli.Action = std.meta.stringToEnum(
        cli.Action,
        action_name,
    ) orelse {
        log.warn("unknown action={s}", .{action_name});
        return false;
    };

    cli.mainAction(
        global.alloc(),
        action,
        .{ .string = std.mem.sliceTo(args, 0) },
    ) catch |err| {
        log.warn("failed to run action={s} err={}", .{
            @tagName(action),
            err,
        });
        return false;
... (5 lines truncated)
</file>

<file path="src/benchmark/cli.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const cli = @import("../cli.zig");
const global = @import("../global.zig");

/// The available actions for the CLI. This is the list of available
/// benchmarks. View docs for each individual one in the predictably
/// named files.
pub const Action = enum {
    @"apc-parser",
    @"codepoint-width",
    @"grapheme-break",
    @"hyperlink-map",
    @"page-compression",
    @"scrollback-compression",
    @"screen-clone",
    @"terminal-formatter",
    @"terminal-parser",
    @"terminal-resize",
    @"terminal-snapshot",
    @"terminal-stream",
    @"is-symbol",
    @"osc-parser",

    /// Returns the struct associated with the action. The struct
    /// should have a few decls:
    ///
    ///   - `const Options`: The CLI options for the action.
    ///   - `fn create`: Create a new instance of the action from options.
    ///   - `fn benchmark`: Returns a `Benchmark` instance for the action.
... (87 lines truncated)
</file>

<file path="src/benchmark/CodepointWidth.zig">
//! This benchmark tests the throughput of codepoint width calculation.
//! This is a common operation in terminal character printing and the
//! motivating factor to write this benchmark was discovering that our
//! codepoint width function was 30% of the runtime of every character
//! print.
const CodepointWidth = @This();

const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const UTF8Decoder = @import("../terminal/UTF8Decoder.zig");
const simd = @import("../simd/main.zig");
const table = @import("../unicode/main.zig").table;
const global = @import("../global.zig");

const log = std.log.scoped(.@"terminal-stream-bench");

opts: Options,

/// The file, opened in the setup function.
data_f: ?std.Io.File = null,

pub const Options = struct {
    /// The type of codepoint width calculation to use.
    mode: Mode = .noop,

    /// The data to read as a filepath. If this is "-" then
... (179 lines truncated)
</file>

<file path="src/benchmark/GraphemeBreak.zig">
//! This benchmark tests the throughput of grapheme break calculation.
//! This is a common operation in terminal character printing for terminals
//! that support grapheme clustering.
const GraphemeBreak = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const UTF8Decoder = @import("../terminal/UTF8Decoder.zig");
const unicode = @import("../unicode/main.zig");
const uucode = @import("uucode");
const global = @import("../global.zig");

const log = std.log.scoped(.@"terminal-stream-bench");

opts: Options,

/// The file, opened in the setup function.
data_f: ?std.Io.File = null,

pub const Options = struct {
    /// The type of codepoint width calculation to use.
    mode: Mode = .table,

    /// The data to read as a filepath. If this is "-" then
    /// we will read stdin. If this is unset, then we will
    /// do nothing (benchmark is a noop). It'd be more unixy to
    /// use stdin by default but I find that a hanging CLI command
... (124 lines truncated)
</file>

<file path="src/benchmark/HyperlinkMap.zig">
//! Benchmark hyperlink cell-map lookups and remove/insert churn.
//!
//! Hyperlink cells are stored in a fixed-capacity, open-addressed hash map.
//! The `churn` mode models terminal output that repeatedly replaces cells in
//! a page whose hyperlink map is already close to full. This is particularly
//! useful for catching probe-length cliffs at high load factors.
const HyperlinkMap = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const terminal = @import("../terminal/main.zig");
const hyperlink = @import("../terminal/hyperlink.zig");
const Benchmark = @import("Benchmark.zig");

const log = std.log.scoped(.@"hyperlink-map-bench");

opts: Options,
page: terminal.Page,
link_id: hyperlink.Id,
entry_count: usize,

pub const Options = struct {
    /// Requested hyperlink working-set size. Must be a power of two and at
    /// least 16. The map may reserve additional probe headroom.
    entries: u16 = 4096,

    /// Percentage of the map populated before the timed operation.
    /// Values above 100 are treated as 100.
    @"load-percent": u8 = 100,

... (126 lines truncated)
</file>

<file path="src/benchmark/IsSymbol.zig">
//! This benchmark tests the throughput of grapheme break calculation.
//! This is a common operation in terminal character printing for terminals
//! that support grapheme clustering.
const IsSymbol = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const UTF8Decoder = @import("../terminal/UTF8Decoder.zig");
const uucode = @import("uucode");
const symbols_table = @import("../unicode/symbols_table.zig").table;
const global = @import("../global.zig");

const log = std.log.scoped(.@"is-symbol-bench");

opts: Options,

/// The file, opened in the setup function.
data_f: ?std.Io.File = null,

pub const Options = struct {
    /// Which test to run.
    mode: Mode = .uucode,

    /// The data to read as a filepath. If this is "-" then
    /// we will read stdin. If this is unset, then we will
    /// do nothing (benchmark is a noop). It'd be more unixy to
    /// use stdin by default but I find that a hanging CLI command
... (123 lines truncated)
</file>

<file path="src/benchmark/main.zig">
pub const cli = @import("cli.zig");
pub const Benchmark = @import("Benchmark.zig");
pub const CApi = @import("CApi.zig");
pub const TerminalStream = @import("TerminalStream.zig");
pub const CodepointWidth = @import("CodepointWidth.zig");
pub const GraphemeBreak = @import("GraphemeBreak.zig");
pub const HyperlinkMap = @import("HyperlinkMap.zig");
pub const ScreenClone = @import("ScreenClone.zig");
pub const TerminalFormatter = @import("TerminalFormatter.zig");
pub const TerminalParser = @import("TerminalParser.zig");
pub const TerminalResize = @import("TerminalResize.zig");
pub const TerminalSnapshot = @import("TerminalSnapshot.zig");
pub const IsSymbol = @import("IsSymbol.zig");
pub const PageCompression = @import("PageCompression.zig");
pub const ScrollbackCompression = @import("ScrollbackCompression.zig");

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/benchmark/options.zig">
//! This file contains helpers for CLI options.

const std = @import("std");
const global = @import("../global.zig");

/// Returns the data file for the given path in a way that is consistent
/// across our CLI. If the path is not set then no file is returned.
/// If the path is "-", then we will return stdin. If the path is
/// a file then we will open and return the handle.
pub fn dataFile(path_: ?[]const u8) !?std.Io.File {
    const path = path_ orelse return null;

    // Stdin
    if (std.mem.eql(u8, path, "-")) return .stdin();

    // Normal file
    const file = try std.Io.Dir.cwd().openFile(global.io(), path, .{});
    errdefer file.close(global.io());

    return file;
}
</file>

<file path="src/benchmark/OscParser.zig">
//! This benchmark tests the throughput of the OSC parser.
const OscParser = @This();

const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const Parser = @import("../terminal/osc.zig").Parser;
const log = std.log.scoped(.@"osc-parser-bench");
const global = @import("../global.zig");

opts: Options,

/// The file, opened in the setup function.
data_f: ?std.Io.File = null,

parser: Parser,

pub const Options = struct {
    /// The data to read as a filepath. If this is "-" then
    /// we will read stdin. If this is unset, then we will
    /// do nothing (benchmark is a noop). It'd be more unixy to
    /// use stdin by default but I find that a hanging CLI command
    /// with no interaction is a bit annoying.
    data: ?[]const u8 = null,

    /// The most bytes to keep from each OSC sequence whose number the
    /// parser does not implement. Zero, the default, discards them like
... (96 lines truncated)
</file>

<file path="src/benchmark/PageCompression.zig">
//! Benchmarks raw LZ4 compression and decompression on page-sized byte
//! buffers.
//!
//! This benchmark is intentionally independent of terminal page ownership and
//! lifecycle. It treats its input as opaque bytes and calls only the standalone
//! LZ4 block codec. In particular, it does not compress pages owned by a live
//! terminal or measure the scheduling and state transitions used by automatic
//! scrollback compression.
//!
//! ## Input
//!
//! `--data` names a pre-generated raw byte corpus. The corpus is divided into
//! `--page-size` byte chunks, with a final short chunk retained when the file
//! size is not an exact multiple. The default page size is 400 KiB, matching a
//! standard terminal page in ReleaseFast builds on the current target.
//!
//! A raw dump of actual page backing memory is the most representative input:
//! it includes cells, rows, styles, graphemes, hyperlinks, allocator metadata,
//! and unused capacity exactly as the codec would see them. Keep such corpora
//! outside the repository and reuse the same file when comparing branches.
//! Arbitrary files are accepted too, but their compression ratios should not be
//! interpreted as terminal scrollback ratios.
//!
//! ## Modes
//!
//! * `noop` walks the input chunks without invoking the codec. This measures the
//!   benchmark loop's minimum overhead.
//! * `compress` compresses every input chunk into a reusable output buffer.
//! * `store` additionally copies each useful result into an exact-sized
//!   allocation. It retains the most recent `--retained-pages` blocks so that
... (492 lines truncated)
</file>

<file path="src/benchmark/ScreenClone.zig">
//! This benchmark tests the performance of the Screen.clone
//! function. This is useful because it is one of the primary lock
//! holders that impact IO performance when the renderer is active.
//! We do this very frequently.
const ScreenClone = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const terminalpkg = @import("../terminal/main.zig");
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const Terminal = terminalpkg.Terminal;
const global = @import("../global.zig");

const log = std.log.scoped(.@"terminal-stream-bench");

opts: Options,
terminal: Terminal,

pub const Options = struct {
    /// The type of codepoint width calculation to use.
    mode: Mode = .clone,

    /// Multiplier on the number of iterations each step runs. This is
    /// useful to make a benchmark run long enough for profiling.
    loops: u32 = 1,

    /// The size of the terminal. This affects benchmarking when
    /// dealing with soft line wrapping and the memory impact
... (426 lines truncated)
</file>

<file path="src/benchmark/ScrollbackCompression.zig">
//! Benchmarks cold-history compression and restoration on pages owned by a
//! live terminal.
//!
//! Unlike `page-compression`, which measures the standalone codec against raw
//! byte chunks, this benchmark first parses a VT corpus into a real `Terminal`.
//! Its timed operations therefore include the PageList state transition,
//! exact-sized encoded allocation, retained-mapping reclamation, and transparent
//! restoration through `PageList.Node.page`.
//!
//! ## Input
//!
//! `--data` names a pre-generated VT byte stream. Parsing happens during setup
//! and is not part of the benchmark's timed region. Use the same saved corpus,
//! terminal dimensions, and scrollback limit when comparing revisions. In
//! particular, do not pipe a generator into this benchmark: generation and
//! pipe scheduling add noise which can overwhelm the operation being measured.
//!
//! The benchmark always operates on the primary screen's PageList. This keeps
//! the result focused on scrollback even if malformed or incomplete input
//! leaves the terminal in its alternate screen at end of file. `--max-scrollback`
//! is expressed in bytes and defaults to 10 MB.
//!
//! ## Modes
//!
//! * `noop` parses the corpus but performs no timed PageList operation. This is
//!   the common process and setup baseline for the other modes.
//! * `compress` times one complete `compress` invocation.
//! * `incremental` reaches the same final representation through
//!   `compress(.drain)`. It drains the candidate-bounded steps and final
//!   no-work verification pass in the timed region, making cursor and repeated
... (315 lines truncated)
</file>

<file path="src/benchmark/TerminalFormatter.zig">
//! Benchmarks the terminal formatter (`terminal/formatter.zig`).
//!
//! The formatter is the hot path for clipboard copy (plain/VT/HTML),
//! `write_screen_file`, `selectionString`, terminal search window
//! encoding, and the libghostty-vt formatter C API. This benchmark
//! measures formatting terminal contents that were built during setup
//! (outside the timed region) from a pre-generated VT stream.
//!
//! ## Input
//!
//! `--data` names a pre-generated VT byte stream (for example from
//! `ghostty-gen styled`). The stream is fed to a terminal of the
//! requested dimensions with unlimited scrollback during setup. The
//! resulting screen contents (scrollback included) are what each step
//! formats.
//!
//! ## Modes
//!
//! * `noop` performs no formatting and establishes loop/setup overhead.
//!   Subtract this from `format` timings when using hyperfine.
//! * `format` formats the configured region once per loop into a
//!   reusable buffer. Buffer growth happens on the first iteration only.
//! * `report` formats once and prints content/output sizes. It is for
//!   computing throughput (cells/s, bytes/s), not timing comparisons.
//!
//! ## Examples
//!
//! Build benchmarks in ReleaseFast mode:
//!
//!     zig build -Demit-bench -Doptimize=ReleaseFast -Demit-macos-app=false
... (453 lines truncated)
</file>

<file path="src/benchmark/TerminalParser.zig">
//! This benchmark tests the throughput of the terminal escape code parser.
const TerminalParser = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const terminalpkg = @import("../terminal/main.zig");
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.@"terminal-stream-bench");

opts: Options,

/// The file, opened in the setup function.
data_f: ?std.Io.File = null,

pub const Options = struct {
    /// The data to read as a filepath. If this is "-" then
    /// we will read stdin. If this is unset, then we will
    /// do nothing (benchmark is a noop). It'd be more unixy to
    /// use stdin by default but I find that a hanging CLI command
    /// with no interaction is a bit annoying.
    data: ?[]const u8 = null,
};

pub fn create(
    alloc: Allocator,
    opts: Options,
... (86 lines truncated)
</file>

<file path="src/benchmark/TerminalResize.zig">
//! This benchmark tests the performance of Terminal.resize, with a
//! primary focus on column resizes that reflow soft-wrapped text.
//! Resize happens on the IO thread while holding the terminal lock,
//! so a slow resize directly translates into dropped input and a
//! frozen-feeling UI while the user drags the window edge (which
//! produces a rapid stream of resizes).
//!
//! The terminal is populated once during setup (synthetic fill and/or
//! a data file replayed through the VT stream) and then each step
//! ping-pongs the terminal between two sizes. A full cycle returns the
//! terminal to its original dimensions so the state reaches a steady
//! state after the first cycle and every iteration performs
//! equivalent work.
const TerminalResize = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const terminalpkg = @import("../terminal/main.zig");
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const Terminal = terminalpkg.Terminal;
const global = @import("../global.zig");

const log = std.log.scoped(.@"terminal-resize-bench");

opts: Options,
alloc: Allocator,
terminal: Terminal,

... (328 lines truncated)
</file>

<file path="src/benchmark/TerminalSnapshot.zig">
//! Benchmarks the terminal binary snapshot codecs (`terminal/snapshot`).
//!
//! Encoding and decoding a snapshot are the hot paths for terminal
//! persistence and handoff, so both directions are measured against the
//! same terminal state.
//!
//! ## Input
//!
//! `--data` names a pre-generated VT byte stream (for example from
//! `ghostty-gen ascii`). The stream is fed to a terminal of the requested
//! dimensions during setup, outside the timed region. The resulting screen
//! and scrollback contents are what each step encodes or decodes.
//!
//! ## Modes
//!
//! * `noop` performs no codec work and establishes loop overhead.
//! * `encode` encodes one complete snapshot per loop into a reusable
//!   buffer. Buffer growth happens on the first iteration only.
//! * `decode` restores one complete snapshot per loop from bytes prepared
//!   during setup. The restored terminal is destroyed inside the step, so
//!   this measures the complete restore lifecycle.
//! * `decode-ready` restores only the renderable prefix per loop using the
//!   incremental decoder and stops at READY, skipping history. Compared
//!   against `decode`, this is the time-to-interactive win of applying
//!   history off the critical path.
//! * `report` encodes once and prints total and per-record-tag sizes. It
//!   is for inspecting the wire shape, not timing comparisons.
//!
//! ## Examples
//!
... (321 lines truncated)
</file>

<file path="src/benchmark/TerminalStream.zig">
//! This benchmark tests the performance of the terminal stream
//! handler from input to terminal state update. This is useful to
//! test general throughput of VT parsing and handling.
//!
//! This uses the full readonly terminal stream handler
//! (terminal.TerminalStream) so every escape sequence updates real
//! terminal state (styles, cursor movement, erases, modes, etc.).
//! This closely mirrors the work done by the real IO thread.
//!
//! For more isolated measurements see the terminal-parser and
//! osc-parser benchmarks.
const TerminalStream = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const terminalpkg = @import("../terminal/main.zig");
const Benchmark = @import("Benchmark.zig");
const options = @import("options.zig");
const Terminal = terminalpkg.Terminal;
const Stream = terminalpkg.TerminalStream;
const global = @import("../global.zig");

const log = std.log.scoped(.@"terminal-stream-bench");

opts: Options,
terminal: Terminal,
stream: Stream,

/// The file, opened in the setup function.
... (161 lines truncated)
</file>

<file path="src/cli/ssh-cache/DiskCache.zig">
/// An SSH terminfo entry cache that stores its cache data on
/// disk. The cache only stores metadata (hostname, terminfo value,
/// etc.) and does not store any sensitive data.
const DiskCache = @This();

const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const internal_os = @import("../../os/main.zig");
const xdg = internal_os.xdg;
const Entry = @import("Entry.zig");
const global = @import("../../global.zig");

// 512KB - sufficient for approximately 10k entries
const MAX_CACHE_SIZE = 512 * 1024;

/// Path to a file where the cache is stored.
path: []const u8,

/// Returns the default path for the cache for a given program.
///
/// On all platforms, this is `${XDG_STATE_HOME}/ghostty/ssh_cache`.
///
/// The returned value is allocated and must be freed by the caller.
pub fn defaultPath(
    alloc: Allocator,
    program: []const u8,
) ![]const u8 {
    var environ_map = try global.environMap();
... (865 lines truncated)
</file>

<file path="src/cli/ssh-cache/Entry.zig">
/// A single entry within our SSH entry cache. Our SSH entry cache
/// stores which hosts we've sent our terminfo to so that we don't have
/// to send it again. It doesn't store any sensitive information.
const Entry = @This();

const std = @import("std");

hostname: []const u8,
timestamp: i64,
terminfo_version: []const u8,

pub fn parse(line: []const u8) ?Entry {
    const trimmed = std.mem.trim(u8, line, " \t\r\n");
    if (trimmed.len == 0) return null;

    // Parse format: hostname|timestamp|terminfo_version
    var iter = std.mem.tokenizeScalar(u8, trimmed, '|');
    const hostname = iter.next() orelse return null;
    const timestamp_str = iter.next() orelse return null;
    const terminfo_version = iter.next() orelse "xterm-ghostty";
    const timestamp = std.fmt.parseInt(i64, timestamp_str, 10) catch |err| {
        std.log.warn(
            "Invalid timestamp in cache entry: {s} err={}",
            .{ timestamp_str, err },
        );
        return null;
    };

    return .{
        .hostname = hostname,
... (72 lines truncated)
</file>

<file path="src/cli/action.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

pub const DetectError = error{
    /// Multiple actions were detected. You can specify at most one
    /// action on the CLI otherwise the behavior desired is ambiguous.
    MultipleActions,

    /// An unknown action was specified.
    InvalidAction,
};

/// Detect the action from CLI args.
pub fn detectArgs(comptime E: type, alloc: Allocator, args: std.process.Args) !?E {
    var iter = try args.iterateAllocator(alloc);
    defer iter.deinit();
    return try detectIter(E, &iter);
}

/// Detect the action from any iterator. Each iterator value should yield
/// a CLI argument such as "--foo".
///
/// The comptime type E must be an enum with the available actions.
/// If the type E has a decl `detectSpecialCase`, then it will be called
/// for each argument to allow handling of special cases. The function
/// signature for `detectSpecialCase` should be:
///
///   fn detectSpecialCase(arg: []const u8) ?SpecialCase(E)
///
pub fn detectIter(
... (248 lines truncated)
</file>

<file path="src/cli/args.zig">
const std = @import("std");
const mem = std.mem;
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const diags = @import("diagnostics.zig");
const internal_os = @import("../os/main.zig");
const Diagnostic = diags.Diagnostic;
const DiagnosticList = diags.DiagnosticList;
const CommaSplitter = @import("CommaSplitter.zig");

const log = std.log.scoped(.cli);

// TODO:
//   - Only `--long=value` format is accepted. Do we want to allow
//     `--long value`? Not currently allowed.

// For trimming
pub const whitespace = " \t";

/// The base errors for arg parsing. Additional errors can be returned due
/// to type-specific parsing but these are always possible.
pub const Error = error{
    ValueRequired,
    InvalidField,
    InvalidValue,
};

/// Parse the command line arguments from iter into dst.
///
... (1627 lines truncated)
</file>

<file path="src/cli/boo.zig">
const std = @import("std");
const builtin = @import("builtin");
const args = @import("args.zig");
const Action = @import("ghostty.zig").Action;
const Allocator = std.mem.Allocator;
const global = @import("../global.zig");
const vaxis = @import("vaxis");

const framedata = @import("framedata").compressed;

const vxfw = vaxis.vxfw;

pub const Options = struct {
    pub fn deinit(self: Options) void {
        _ = self;
    }

    /// Enables `-h` and `--help` to work.
    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
    }
};

const Boo = struct {
    frame: u8,
    framerate: u32, // 30 fps
    // We know the size of this at compile time, but we heap allocate the slice to prevent the
    // binary from increasing too much in size
    buffer: [frame_width * frame_height]vaxis.Cell = undefined,
... (211 lines truncated)
</file>

<file path="src/cli/CommaSplitter.zig">
//! Iterator to split a string into fields by commas, taking into account
//! quotes and escapes.
//!
//! Supports the same escapes as in Zig literal strings.
//!
//! Quotes must begin and end with a double quote (`"`). It is an error to not
//! end a quote that was begun. To include a double quote inside a quote (or to
//! not have a double quote start a quoted section) escape it with a backslash.
//!
//! Single quotes (`'`) are not special, they do not begin a quoted block.
//!
//! Zig multiline string literals are NOT supported.
//!
//! Quotes and escapes are not stripped or decoded, that must be handled as a
//! separate step!
//!
//! On Windows, backslash is only treated as an escape character inside quoted
//! strings. Outside quotes, backslash is a literal character (path separator).
const CommaSplitter = @This();

const builtin = @import("builtin");

/// Whether backslash acts as an escape character outside quoted strings.
/// On Windows, backslash is the path separator so it is always literal
/// outside quotes.
const escape_outside_quotes = builtin.os.tag != .windows;

pub const Error = error{
    UnclosedQuote,
    UnfinishedEscape,
... (454 lines truncated)
</file>

<file path="src/cli/crash_report.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const args = @import("args.zig");
const Action = @import("ghostty.zig").Action;
const Config = @import("../config.zig").Config;
const crash = @import("../crash/main.zig");
const global = @import("../global.zig");

pub const Options = struct {
    pub fn deinit(self: Options) void {
        _ = self;
    }

    /// Enables "-h" and "--help" to work.
    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
    }
};

/// The `crash-report` command is used to inspect and send crash reports.
///
/// When executed without any arguments, this will list existing crash reports.
///
/// This command currently only supports listing crash reports. Viewing
/// and sending crash reports is unimplemented and will be added in the future.
pub fn run(alloc_gpa: Allocator) !u8 {
    // Use an arena for the whole command to avoid manual memory management.
    var arena = std.heap.ArenaAllocator.init(alloc_gpa);
    defer arena.deinit();
... (69 lines truncated)
</file>

<file path="src/cli/diagnostics.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const build_config = @import("../build_config.zig");

/// A diagnostic message from parsing. This is used to provide additional
/// human-friendly warnings and errors about the parsed data.
///
/// All of the memory for the diagnostic is allocated from the arena
/// associated with the config structure. If an arena isn't available
/// then diagnostics are not supported.
pub const Diagnostic = struct {
    location: Location = .none,
    key: [:0]const u8 = "",
    message: [:0]const u8,

    /// Write the full user-friendly diagnostic message to the writer.
    pub fn format(self: *const Diagnostic, writer: *std.Io.Writer) !void {
        switch (self.location) {
            .none => {},
            .cli => |index| try writer.print("cli:{}:", .{index}),
            .file => |file| try writer.print(
                "{s}:{}:",
                .{ file.path, file.line },
            ),
        }

        if (self.key.len > 0) {
            try writer.print("{s}: ", .{self.key});
... (168 lines truncated)
</file>

<file path="src/cli/edit_config.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const args = @import("args.zig");
const Allocator = std.mem.Allocator;
const Action = @import("ghostty.zig").Action;
const configpkg = @import("../config.zig");
const internal_os = @import("../os/main.zig");
const Config = configpkg.Config;
const global = @import("../global.zig");

pub const Options = struct {
    pub fn deinit(self: Options) void {
        _ = self;
    }

    /// Enables `-h` and `--help` to work.
    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
    }
};

/// The `edit-config` command opens the Ghostty configuration file in the
/// editor specified by the `$VISUAL` or `$EDITOR` environment variables.
///
/// IMPORTANT: This command will not reload the configuration after
/// editing. You will need to manually reload the configuration using the
/// application menu, configured keybind, or by restarting Ghostty. We
/// plan to auto-reload in the future, but Ghostty isn't capable of
... (133 lines truncated)
</file>

<file path="src/cli/explain_config.zig">
const std = @import("std");
const args = @import("args.zig");
const Allocator = std.mem.Allocator;
const Action = @import("ghostty.zig").Action;
const help_strings = @import("help_strings");
const Config = @import("../config/Config.zig");
const ConfigKey = @import("../config/key.zig").Key;
const KeybindAction = @import("../input/Binding.zig").Action;
const Pager = @import("Pager.zig");
const global = @import("../global.zig");

pub const Options = struct {
    /// The config option to explain. For example:
    ///
    ///   ghostty +explain-config --option=font-size
    option: ?[]const u8 = null,

    /// The keybind action to explain. For example:
    ///
    ///   ghostty +explain-config --keybind=copy_to_clipboard
    keybind: ?[]const u8 = null,

    pub fn deinit(self: Options) void {
        _ = self;
    }

    /// Enables `-h` and `--help` to work.
    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
... (123 lines truncated)
</file>

<file path="src/cli/ghostty.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const help_strings = @import("help_strings");
const actionpkg = @import("action.zig");
const SpecialCase = actionpkg.SpecialCase;

const list_fonts = @import("list_fonts.zig");
const help = @import("help.zig");
const version = @import("version.zig");
const list_keybinds = @import("list_keybinds.zig");
const list_themes = @import("list_themes.zig");
const list_colors = @import("list_colors.zig");
const list_actions = @import("list_actions.zig");
const ssh = @import("ssh.zig");
const ssh_cache = @import("ssh_cache.zig");
const edit_config = @import("edit_config.zig");
const show_config = @import("show_config.zig");
const explain_config = @import("explain_config.zig");
const validate_config = @import("validate_config.zig");
const crash_report = @import("crash_report.zig");
const show_face = @import("show_face.zig");
const boo = @import("boo.zig");
const new_window = @import("new_window.zig");
const new_tab = @import("new_tab.zig");
const toggle_quick_terminal = @import("toggle_quick_terminal.zig");
const global = @import("../global.zig");

/// Special commands that can be invoked via CLI flags. These are all
/// invoked by using `+<action>` as a CLI flag. The only exception is
/// "version" which can be invoked additionally with `--version`.
... (301 lines truncated)
</file>

<file path="src/cli/help.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const args = @import("args.zig");
const Action = @import("ghostty.zig").Action;
const global = @import("../global.zig");

// Note that this options struct doesn't implement the `help` decl like other
// actions. That is because the help command is special and wants to handle its
// own logic around help detection.
pub const Options = struct {
    /// This must be registered so that it isn't an error to pass `--help`
    help: bool = false,

    pub fn deinit(self: Options) void {
        _ = self;
    }
};

/// The `help` command shows general help about Ghostty. Recognized as either
/// `-h`, `--help`, or like other actions `+help`.
///
/// You can also specify `--help` or `-h` along with any action such as
/// `+list-themes` to see help for a specific action.
pub fn run(alloc: Allocator) !u8 {
    var opts: Options = .{};
    defer opts.deinit();

    {
        var iter = try args.argsIterator(alloc, global.args());
        defer iter.deinit();
... (50 lines truncated)
</file>

<file path="src/cli/list_actions.zig">
const std = @import("std");
const args = @import("args.zig");
const Action = @import("ghostty.zig").Action;
const Allocator = std.mem.Allocator;
const helpgen_actions = @import("../input/helpgen_actions.zig");
const global = @import("../global.zig");

pub const Options = struct {
    /// If `true`, print out documentation about the action associated with the
    /// keybinds.
    docs: bool = false,

    pub fn deinit(self: Options) void {
        _ = self;
    }

    /// Enables `-h` and `--help` to work.
    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
    }
};

/// The `list-actions` command is used to list all the available keybind
/// actions for Ghostty. These are distinct from the CLI Actions which can
/// be listed via `+help`
///
/// Flags:
///
///   * `--docs`: will print out the documentation for each action.
... (24 lines truncated)
</file>

<file path="src/cli/list_colors.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const Action = @import("ghostty.zig").Action;
const args = @import("args.zig");
const x11_color = @import("../terminal/main.zig").x11_color;
const vaxis = @import("vaxis");
const tui = @import("tui.zig");
const global = @import("../global.zig");

pub const Options = struct {
    pub fn deinit(self: Options) void {
        _ = self;
    }

    /// If `true`, print without formatting even if printing to a tty
    plain: bool = false,

    /// Enables "-h" and "--help" to work.
    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
    }
};

/// The `list-colors` command is used to list all the named RGB colors in
/// Ghostty.
///
/// Flags:
///
... (183 lines truncated)
</file>

<file path="src/cli/list_fonts.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const Action = @import("ghostty.zig").Action;
const args = @import("args.zig");
const font = @import("../font/main.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.list_fonts);

pub const Options = struct {
    /// This is set by the CLI parser for deinit.
    _arena: ?ArenaAllocator = null,

    /// The font family to search for. If this is set, then only fonts
    /// matching this family will be listed.
    family: ?[:0]const u8 = null,

    /// The style name to search for.
    style: ?[:0]const u8 = null,

    /// Font styles to search for. If this is set, then only fonts that
    /// match the given styles will be listed.
    bold: bool = false,
    italic: bool = false,

    pub fn deinit(self: *Options) void {
        if (self._arena) |arena| arena.deinit();
        self.* = undefined;
    }
... (141 lines truncated)
</file>

<file path="src/cli/list_keybinds.zig">
const std = @import("std");
const builtin = @import("builtin");
const args = @import("args.zig");
const Action = @import("ghostty.zig").Action;
const Arena = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;
const configpkg = @import("../config.zig");
const Config = configpkg.Config;
const vaxis = @import("vaxis");
const input = @import("../input.zig");
const tui = @import("tui.zig");
const Binding = input.Binding;
const global = @import("../global.zig");

pub const Options = struct {
    /// If `true`, print out the default keybinds instead of the ones configured
    /// in the config file.
    default: bool = false,

    /// If `true`, print out documentation about the action associated with the
    /// keybinds.
    docs: bool = false,

    /// If `true`, print without formatting even if printing to a tty
    plain: bool = false,

    pub fn deinit(self: Options) void {
        _ = self;
    }

... (410 lines truncated)
</file>

<file path="src/cli/list_themes.zig">
const std = @import("std");
const args = @import("args.zig");
const Action = @import("ghostty.zig").Action;
const Config = @import("../config/Config.zig");
const configpkg = @import("../config.zig");
const themepkg = @import("../config/theme.zig");
const tui = @import("tui.zig");
const global = @import("../global.zig");

const vaxis = @import("vaxis");
const zf = @import("zf");

// When the number of filtered themes is less than or equal to this threshold,
// the window position will be reset to 0 to show all results from the top.
// This ensures better visibility for small result sets while maintaining
// scroll position for larger lists.
const SMALL_LIST_THRESHOLD = 10;

const ColorScheme = enum { all, dark, light };

pub const Options = struct {
    /// If true, print the full path to the theme.
    path: bool = false,

    /// If true, force a plain list of themes.
    plain: bool = false,

    /// Specifies the color scheme of the themes to include in the list.
    color: ColorScheme = .all,

... (1783 lines truncated)
</file>

<file path="src/cli/lorem_ipsum.txt">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras hendrerit aliquet
turpis non dictum. Mauris pulvinar nisl sit amet dui cursus tempus. Pellentesque
ut dui justo. Etiam quis magna sagittis nisi pretium consequat vitae ut nisl.
Sed at metus id odio pulvinar sodales. Vestibulum sollicitudin, sem id tristique
vestibulum, neque ante dictum tortor, in convallis mi enim ac lorem. Suspendisse
orci ex, ullamcorper sed leo vitae, mattis egestas nisl. Morbi id est vel
ipsum mollis convallis vel at mauris. Duis vehicula facilisis placerat. Aliquam
venenatis auctor ipsum vel elementum. Proin ac tincidunt lacus. Sed facilisis
tellus ullamcorper bibendum lobortis. Pellentesque porta, lacus quis efficitur
pulvinar, sem mi varius ante, sed finibus diam ante et risus.

Morbi ut sollicitudin justo. Nulla mattis mi ac mauris tincidunt tempor. Morbi
vel gravida erat. Ut eu risus quis nisi facilisis aliquet varius id orci.
Pellentesque tortor diam, porttitor nec urna nec, convallis consectetur dui.
Vestibulum et hendrerit ipsum. Morbi pharetra dictum turpis in elementum. Ut
nec volutpat nunc, at venenatis leo. Morbi eget nulla luctus, tincidunt dui vel,
cursus urna. Maecenas ac pellentesque nisi. Quisque ut lorem porta, eleifend
metus id, pellentesque tellus.

Vivamus gravida convallis felis, at hendrerit dolor. Vestibulum tincidunt id
augue quis hendrerit. Praesent venenatis elit quis posuere gravida. Praesent
at massa a purus maximus tempus. Proin dui leo, feugiat et erat ac, tincidunt
aliquam risus. Aenean rutrum hendrerit turpis, sit amet consectetur justo porta
non. Sed auctor justo elit, sed mollis odio ullamcorper nec. Pellentesque ac
hendrerit tortor. Praesent quis viverra dui, sit amet imperdiet magna.

Mauris iaculis maximus felis, aliquet vehicula neque sagittis nec. Duis
convallis purus enim, vel scelerisque purus dignissim eu. Donec congue sapien
a neque rhoncus, sit amet accumsan libero tincidunt. Proin vitae placerat urna.
Donec dolor sapien, fringilla sed semper sit amet, sollicitudin sit amet orci.
... (16 lines truncated)
</file>

<file path="src/cli/new_tab.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const Action = @import("../cli.zig").ghostty.Action;
const apprt = @import("../apprt.zig");
const args = @import("args.zig");
const diagnostics = @import("diagnostics.zig");
const homedir = @import("../os/homedir.zig");
const internal_os = @import("../os/main.zig");
const global = @import("../global.zig");

pub const Options = struct {
    /// We store an I/O implementation to make maintenance easier.
    _io: std.Io,

    /// This is set by the CLI parser for deinit.
    _arena: ?ArenaAllocator = null,

    /// If set, open up a new tab in a custom instance of Ghostty.
    class: ?[:0]const u8 = null,

    /// The surface to target.
    @"surface-id": ?u64 = null,

    /// Did the user specify a `--working-directory` argument on the command line?
    _working_directory_seen: bool = false,

    /// All of the arguments after `+new-tab`. They will be sent to Ghosttty
    /// for processing.
    _arguments: std.ArrayList([:0]const u8) = .empty,
... (248 lines truncated)
</file>

<file path="src/cli/new_window.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const Action = @import("../cli.zig").ghostty.Action;
const apprt = @import("../apprt.zig");
const args = @import("args.zig");
const diagnostics = @import("diagnostics.zig");
const homedir = @import("../os/homedir.zig");
const global = @import("../global.zig");

pub const Options = struct {
    /// We store an I/O implementation to make maintenance easier.
    _io: std.Io,

    /// This is set by the CLI parser for deinit.
    _arena: ?ArenaAllocator = null,

    /// If set, open up a new window in a custom instance of Ghostty.
    class: ?[:0]const u8 = null,

    /// Did the user specify a `--working-directory` argument on the command line?
    _working_directory_seen: bool = false,

    /// All of the arguments after `+new-window`. They will be sent to Ghosttty
    /// for processing.
    _arguments: std.ArrayList([:0]const u8) = .empty,

    /// Enable arg parsing diagnostics so that we don't get an error if
    /// there is a "normal" config setting on the cli.
    _diagnostics: diagnostics.DiagnosticList = .{},
... (234 lines truncated)
</file>

<file path="src/cli/Pager.zig">
//! A pager wraps output to an external pager program (like `less`) when
//! stdout is a TTY. The pager command is resolved as:
//!
//!   `$GHOSTTY_PAGER` > `$PAGER` > `less`
//!
//! Setting either env var to an empty string disables paging.
//! If stdout is not a TTY, writes go directly to stdout.
const Pager = @This();
const builtin = @import("builtin");
const std = @import("std");
const Allocator = std.mem.Allocator;
const internal_os = @import("../os/main.zig");
const global = @import("../global.zig");

/// The pager child process, if one was spawned.
child: ?std.process.Child = null,

/// The buffered file writer used for both the pager pipe and direct
/// stdout paths.
file_writer: std.Io.File.Writer = undefined,

/// Initialize the pager. If stdout is a TTY, this spawns the pager
/// process. Otherwise, output goes directly to stdout.
pub fn init() Pager {
    return .{ .child = initPager() };
}

/// Writes to the pager process if available; otherwise, stdout.
pub fn writer(self: *Pager, buffer: []u8) *std.Io.Writer {
    if (self.child) |child| {
... (65 lines truncated)
</file>

<file path="src/cli/README.md">
# Subcommand Actions

This is the cli specific code. It contains cli actions and tui definitions and
argument parsing.

This README is meant as developer documentation and not as user documentation.
For user documentation, see the main README or [ghostty.org](https://ghostty.org/docs).

## Updating documentation

Each cli action is defined in it's own file. Documentation for each action is defined
in the doc comment associated with the `run` function. For example the `run` function
in `list_keybinds.zig` contains the help text for `ghostty +list-keybinds`.
</file>

<file path="src/cli/show_config.zig">
const std = @import("std");
const args = @import("args.zig");
const Allocator = std.mem.Allocator;
const Action = @import("ghostty.zig").Action;
const configpkg = @import("../config.zig");
const Config = configpkg.Config;
const Pager = @import("Pager.zig");
const global = @import("../global.zig");

pub const Options = struct {
    /// If true, do not load the user configuration, only load the defaults.
    default: bool = false,

    /// Only show the options that have been changed from the default.
    /// This has no effect if `--default` is specified.
    @"changes-only": bool = true,

    /// If true print the documentation above each option as a comment,
    /// if available.
    docs: bool = false,

    /// Disable automatic paging of output.
    @"no-pager": bool = false,

    pub fn deinit(self: Options) void {
        _ = self;
    }

    /// Enables `-h` and `--help` to work.
    pub fn help(self: Options) !void {
... (64 lines truncated)
</file>

<file path="src/cli/show_face.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const Action = @import("ghostty.zig").Action;
const args = @import("args.zig");
const diagnostics = @import("diagnostics.zig");
const font = @import("../font/main.zig");
const configpkg = @import("../config.zig");
const Config = configpkg.Config;
const global = @import("../global.zig");

pub const Options = struct {
    /// This is set by the CLI parser for deinit.
    _arena: ?ArenaAllocator = null,

    /// The codepoint to search for.
    cp: ?u21 = null,

    /// Search for all of the codepoints in the string.
    string: ?[]const u8 = null,

    /// Font style to search for.
    style: font.Style = .regular,

    /// If specified, force text or emoji presentation.
    presentation: ?font.Presentation = null,

    // Enable arg parsing diagnostics so that we don't get an error if
    // there is a "normal" config setting on the cli.
    _diagnostics: diagnostics.DiagnosticList = .{},
... (211 lines truncated)
</file>

<file path="src/cli/ssh_cache.zig">
const std = @import("std");
const fs = std.fs;
const Allocator = std.mem.Allocator;
const args = @import("args.zig");
const global = @import("../global.zig");
const Action = @import("ghostty.zig").Action;
const Duration = @import("../config.zig").Config.Duration;
const terminfopkg = @import("../terminfo/main.zig");
pub const Entry = @import("ssh-cache/Entry.zig");
pub const DiskCache = @import("ssh-cache/DiskCache.zig");

pub const Options = struct {
    clear: bool = false,
    add: ?[]const u8 = null,
    remove: ?[]const u8 = null,
    prune: ?Duration = null,

    pub fn deinit(self: *Options) void {
        _ = self;
    }

    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
    }
};

/// Manage the SSH terminfo cache for automatic remote host setup.
///
/// The `+ssh` action installs Ghostty's terminfo on remote hosts and records
... (565 lines truncated)
</file>

<file path="src/cli/ssh.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const cli_args = @import("args.zig");
const diagnostics = @import("diagnostics.zig");
const Action = @import("ghostty.zig").Action;
const DiskCache = @import("ssh_cache.zig").DiskCache;
const internal_os = @import("../os/main.zig");
const terminfopkg = @import("../terminfo/main.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.ssh);

const usage =
    \\Usage: ghostty +ssh [flags] [--] <ssh args...>
    \\
    \\Flags:
    \\  --forward-env[=bool]  Enable TERM / SendEnv forwarding. Default: true.
    \\  --terminfo[=bool]     Install Ghostty terminfo on first connect. Default: true.
    \\  --cache[=bool]        Use the terminfo install cache. Default: true.
    \\  --ssh=<path>          Path to the ssh binary. Default: first `ssh` on PATH.
    \\  --verbose             Print +ssh status lines to stderr.
    \\  --help                Show full help.
    \\
    \\ssh flags and the destination go after +ssh's own flags (or after `--`).
    \\
;

pub const Options = struct {
... (698 lines truncated)
</file>

<file path="src/cli/toggle_quick_terminal.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const Action = @import("../cli.zig").ghostty.Action;
const apprt = @import("../apprt.zig");
const global = @import("../global.zig");

pub const Options = struct {
    /// If set, connect to a custom instance of Ghostty.
    class: ?[:0]const u8 = null,

    pub fn deinit(self: *Options) void {
        self.* = undefined;
    }

    /// Enables "-h" and "--help" to work.
    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
    }
};

/// The `+toggle-quick-terminal` command will use native platform IPC to toggle
/// the quick terminal in a running instance of Ghostty.
///
/// If the `--class` flag is not set, the command will try and connect to the
/// default running Ghostty instance. Otherwise it will contact a Ghostty
/// instance configured with the given `class`.
///
/// On GTK, D-Bus activation must be properly configured. Ghostty does not need
/// to be running, as D-Bus will handle launching a new instance if it is not
... (34 lines truncated)
</file>

<file path="src/cli/tui.zig">
const builtin = @import("builtin");

pub const can_pretty_print = switch (builtin.os.tag) {
    .ios, .tvos, .watchos => false,
    else => true,
};
</file>

<file path="src/cli/validate_config.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const args = @import("args.zig");
const Action = @import("ghostty.zig").Action;
const Config = @import("../config.zig").Config;
const global = @import("../global.zig");

pub const Options = struct {
    /// The path of the config file to validate. If this isn't specified,
    /// then the default config file paths will be validated.
    @"config-file": ?[:0]const u8 = null,

    pub fn deinit(self: Options) void {
        _ = self;
    }

    /// Enables "-h" and "--help" to work.
    pub fn help(self: Options) !void {
        _ = self;
        return Action.help_error;
    }
};

/// The `validate-config` command is used to validate a Ghostty config file.
///
/// When executed without any arguments, this will load the config from the default
/// location.
///
/// Flags:
///
... (54 lines truncated)
</file>

<file path="src/cli/version.zig">
const std = @import("std");
const build_options = @import("build_options");
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const build_config = @import("../build_config.zig");
const internal_os = @import("../os/main.zig");
const xev = @import("../global.zig").xev;
const renderer = @import("../renderer.zig");
const global = @import("../global.zig");

const gtk_version = @import("../apprt/gtk/gtk_version.zig");
const adw_version = @import("../apprt/gtk/adw_version.zig");

pub const Options = struct {};

/// The `version` command is used to display information about Ghostty. Recognized as
/// either `+version` or `--version`.
pub fn run(alloc: Allocator) !u8 {
    var buffer: [1024]u8 = undefined;
    const stdout_file: std.Io.File = .stdout();
    var stdout_writer = stdout_file.writer(global.io(), &buffer);

    var environ_map = try global.environMap();
    defer environ_map.deinit();

    const stdout = &stdout_writer.interface;
    const tty = try stdout_file.isTty(global.io());

    if (tty) if (build_config.version.build) |commit_hash| {
        try stdout.print(
... (51 lines truncated)
</file>

<file path="src/config/testdata/theme_dark">
background = #EEEEEE
</file>

<file path="src/config/testdata/theme_light">
background = #FFFFFF
</file>

<file path="src/config/testdata/theme_simple">
# A simple theme
background = #123ABC
</file>

<file path="src/config/c_get.zig">
const std = @import("std");

const key = @import("key.zig");
const Config = @import("Config.zig");
const Color = Config.Color;
const Key = key.Key;
const Value = key.Value;

/// Get a value from the config by key into the given pointer. This is
/// specifically for C-compatible APIs. If you're using Zig, just access
/// the configuration directly.
///
/// The return value is false if the given key is not supported by the
/// C API yet. This is a fixable problem so if it is important to support
/// some key, please open an issue.
pub fn get(config: *const Config, k: Key, ptr_raw: *anyopaque) bool {
    @setEvalBranchQuota(10_000);
    switch (k) {
        inline else => |tag| {
            const value = fieldByKey(config, tag);
            return getValue(ptr_raw, value);
        },
    }
}

/// Get the value anytype and put it into the pointer. Returns false if
/// the type is not supported by the C API yet or the value is null.
fn getValue(ptr_raw: *anyopaque, value: anytype) bool {
    switch (@TypeOf(value)) {
        ?[:0]const u8 => {
... (211 lines truncated)
</file>

<file path="src/config/CApi.zig">
const builtin = @import("builtin");
const std = @import("std");
const inputpkg = @import("../input.zig");
const global = @import("../global.zig");
const String = @import("../main_c.zig").String;

const Config = @import("Config.zig");
const c_get = @import("c_get.zig");
const edit = @import("edit.zig");
const Key = @import("key.zig").Key;

const log = std.log.scoped(.config);

/// Create a new configuration filled with the initial default values.
export fn ghostty_config_new() ?*Config {
    const result = global.alloc().create(Config) catch |err| {
        log.err("error allocating config err={}", .{err});
        return null;
    };

    result.* = Config.default(global.alloc()) catch |err| {
        log.err("error creating config err={}", .{err});
        global.alloc().destroy(result);
        return null;
    };

    return result;
}

export fn ghostty_config_free(ptr: ?*Config) void {
... (251 lines truncated)
</file>

<file path="src/config/ClipboardCodepointMap.zig">
/// ClipboardCodepointMap is a map of codepoints to replacement values
/// for clipboard operations. When copying text to clipboard, matching
/// codepoints will be replaced with their mapped values.
const ClipboardCodepointMap = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;

// To ease our usage later, we map it directly to formatter entries.
pub const Entry = @import("../terminal/formatter.zig").CodepointMap;
pub const Replacement = Entry.Replacement;

/// The list of entries. We use a multiarraylist for cache-friendly lookups.
///
/// Note: we do a linear search because we expect to always have very
/// few entries, so the overhead of a binary search is not worth it.
list: std.MultiArrayList(Entry) = .{},

pub fn deinit(self: *ClipboardCodepointMap, alloc: Allocator) void {
    self.list.deinit(alloc);
}

/// Deep copy of the struct. The given allocator is expected to
/// be an arena allocator of some sort since the struct itself
/// doesn't support fine-grained deallocation of fields.
pub fn clone(self: *const ClipboardCodepointMap, alloc: Allocator) !ClipboardCodepointMap {
    var list = try self.list.clone(alloc);
    for (list.items(.replacement)) |*r| switch (r.*) {
        .string => |s| r.string = try alloc.dupe(u8, s),
... (15 lines truncated)
</file>

<file path="src/config/command.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const formatterpkg = @import("formatter.zig");

/// A command to execute (argv0 and args).
///
/// A command is specified as a simple string such as "nvim a b c".
/// By default, we expect the downstream to do some sort of shell expansion
/// on this string.
///
/// If a command is already expanded and the user does NOT want to do
/// shell expansion (because this usually requires a round trip into
/// /bin/sh or equivalent), specify a `direct:`-prefix. e.g.
/// `direct:nvim a b c`.
///
/// The whitespace before or around the prefix is ignored. For example,
/// `  direct:nvim a b c` and `direct: nvim a b c` are equivalent.
///
/// If the command is not absolute, it'll be looked up via the PATH.
/// For the shell-expansion case, we let the shell do this. For the
/// direct case, we do this directly.
pub const Command = union(enum) {
    const Self = @This();

    /// Execute a command directly, e.g. via `exec`. The format here
    /// is already structured to be ready to passed directly to `exec`
    /// with index zero being the command to execute.
    ///
    /// Index zero is not guaranteed to be an absolute path, and may require
... (301 lines truncated)
</file>

<file path="src/config/conditional.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;

/// Conditionals in Ghostty configuration are based on a static, typed
/// state of the world instead of a dynamic key-value set. This simplifies
/// the implementation, allows for better type checking, and enables a
/// typed C API.
pub const State = struct {
    /// The theme of the underlying OS desktop environment.
    theme: Theme = .light,

    /// The target OS of the current build.
    os: std.Target.Os.Tag = builtin.target.os.tag,

    pub const Theme = enum { light, dark };

    /// Tests the conditional against the state and returns true if it matches.
    pub fn match(self: State, cond: Conditional) bool {
        switch (cond.key) {
            inline else => |tag| {
                // The raw value of the state field.
                const raw = @field(self, @tagName(tag));

                // Since all values are enums currently then we can just
                // do this. If we introduce non-enum state values then this
                // will be a compile error and we should fix here.
                const value: []const u8 = @tagName(raw);

                return switch (cond.op) {
... (63 lines truncated)
</file>

<file path="src/config/config-template">
# This is the configuration file for Ghostty.
#
# This template file has been automatically created at the following
# path since Ghostty couldn't find any existing config files on your system:
#
#   {[path]s}
#
# The template does not set any default options, since Ghostty ships
# with sensible defaults for all options.
# Note that you should not paste the output of `ghostty +show-config
# --default` into your config: some default options actually conflict with each other
# when explicitly set in a configuration file. Instead, only set the
# options you actually need.
#
# Run `ghostty +show-config --default --docs` to view a list of
# all available config options and their default values.
#
# Additionally, each config option is also explained in detail
# on Ghostty's website, at https://ghostty.org/docs/config.
#
# Ghostty can reload the configuration while running by using the menu
# options or the bound key (default: Command + Shift + comma on macOS and
# Control + Shift + comma on other platforms). Not all config options can be
# reloaded while running; some only apply to new windows and others may require
# a full restart to take effect.

# Config syntax crash course
# ==========================
# # The config file consists of simple key-value pairs,
# # separated by equals signs.
... (23 lines truncated)
</file>

<file path="src/config/Config.zig">
/// Config is the main config struct. These fields map directly to the
/// CLI flag names hence we use a lot of `@""` syntax to support hyphens.

// Pandoc is used to automatically generate manual pages and other forms of
// documentation, so documentation comments on fields in the Config struct
// should use Pandoc's flavor of Markdown.
//
// For a reference to Pandoc's Markdown see their [online
// manual.](https://pandoc.org/MANUAL.html#pandocs-markdown)

const Config = @This();

const std = @import("std");
const builtin = @import("builtin");
const build_config = @import("../build_config.zig");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const global = @import("../global.zig");
const deepEqual = @import("../datastruct/comparison.zig").deepEqual;
const fontpkg = @import("../font/main.zig");
const inputpkg = @import("../input.zig");
const internal_os = @import("../os/main.zig");
const cli = @import("../cli.zig");

const conditional = @import("conditional.zig");
const Conditional = conditional.Conditional;
const file_load = @import("file_load.zig");
const formatterpkg = @import("formatter.zig");
const themepkg = @import("theme.zig");
... (11349 lines truncated)
</file>

<file path="src/config/edit.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const file_load = @import("file_load.zig");
const global = @import("../global.zig");

/// The path to the configuration that should be opened for editing.
///
/// On Linux, this will use the file at the XDG config path. This is the
/// only valid path for Linux so we don't need to check for other paths.
///
/// On macOS, both XDG and AppSupport paths are valid. Because Ghostty
/// prioritizes AppSupport over XDG, we will use AppSupport if it exists,
/// followed by XDG if it exists, and finally AppSupport if neither exist.
/// For the existence check, we also prefer non-empty files over empty
/// files.
///
/// The returned value is allocated using the provided allocator.
pub fn openPath(alloc_gpa: Allocator) ![:0]const u8 {
    // Use an arena to make memory management easier in here.
    var arena = ArenaAllocator.init(alloc_gpa);
    defer arena.deinit();
    const alloc_arena = arena.allocator();

    // Get the path we should open
    const config_path = try configPath(alloc_arena);

    if (!config_path.exists) {
... (107 lines truncated)
</file>

<file path="src/config/ErrorList.zig">
const ErrorList = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;

pub const Error = struct {
    message: [:0]const u8,
};

/// The list of errors. This will use the arena allocator associated
/// with the config structure (or whatever allocated used to call ErrorList
/// functions).
list: std.ArrayListUnmanaged(Error) = .{},

/// True if there are no errors.
pub fn empty(self: ErrorList) bool {
    return self.list.items.len == 0;
}

/// Add a new error to the list.
pub fn add(self: *ErrorList, alloc: Allocator, err: Error) !void {
    try self.list.append(alloc, err);
}
</file>

<file path="src/config/file_load.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const internal_os = @import("../os/main.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.config);

/// Default path for the XDG home configuration file. Returned value
/// must be freed by the caller.
pub fn defaultXdgPath(alloc: Allocator) ![]const u8 {
    var environ_map = try global.environMap();
    defer environ_map.deinit();
    return try internal_os.xdg.config(
        global.io(),
        alloc,
        &environ_map,
        .{ .subdir = "ghostty/config.ghostty" },
    );
}

/// Ghostty <1.3.0 default path for the XDG home configuration file.
/// Returned value must be freed by the caller.
pub fn legacyDefaultXdgPath(alloc: Allocator) ![]const u8 {
    var environ_map = try global.environMap();
    defer environ_map.deinit();
    return try internal_os.xdg.config(
        global.io(),
        alloc,
... (147 lines truncated)
</file>

<file path="src/config/formatter_file.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const Config = @import("Config.zig");
const Key = @import("key.zig").Key;
const help_strings = @import("help_strings");
const formatter = @import("formatter.zig");

// IMPORTANT: This is in a separate file from formatter.zig because it
// puts a build-time dependency on Config.zig which brings in too much
// into libghostty-vt tests which reference some formattable types.

/// FileFormatter is a formatter implementation that outputs the
/// config in a file-like format. This uses more generous whitespace,
/// can include comments, etc.
pub const FileFormatter = struct {
    alloc: Allocator,
    config: *const Config,

    /// Include comments for documentation of each key
    docs: bool = false,

    /// Only include changed values from the default.
    changed: bool = false,

    /// Implements std.fmt so it can be used directly with std.fmt.
    pub fn format(
        self: FileFormatter,
        writer: *std.Io.Writer,
    ) std.Io.Writer.Error!void {
        @setEvalBranchQuota(10_000);
... (81 lines truncated)
</file>

<file path="src/config/formatter.zig">
const formatter = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const Key = @import("key.zig").Key;

/// Returns a single entry formatter for the given field name and writer.
pub fn entryFormatter(
    name: []const u8,
    writer: *std.Io.Writer,
) EntryFormatter {
    return .{ .name = name, .writer = writer };
}

/// The entry formatter type for a given writer.
pub const EntryFormatter = struct {
    name: []const u8,
    writer: *std.Io.Writer,

    pub fn formatEntry(
        self: @This(),
        comptime T: type,
        value: T,
    ) !void {
        return formatter.formatEntry(
            T,
            self.name,
            value,
            self.writer,
        );
... (203 lines truncated)
</file>

<file path="src/config/io.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const string = @import("string.zig");
const formatterpkg = @import("formatter.zig");
const cli = @import("../cli.zig");

/// ReadableIO is some kind of IO source that is readable.
///
/// It can be either a direct string or a filepath. The filepath will
/// be deferred and read later, so it won't be checked for existence
/// or readability at configuration time. This allows using a path that
/// might be produced in an intermediate state.
pub const ReadableIO = union(enum) {
    const Self = @This();

    raw: [:0]const u8,
    path: [:0]const u8,

    pub fn parseCLI(
        self: *Self,
        alloc: Allocator,
        input_: ?[]const u8,
    ) !void {
        const input = input_ orelse return error.ValueRequired;
        if (input.len == 0) return error.ValueRequired;

        // We create a buffer only to do string parsing and validate
        // it works. We store the value as raw so that our formatting
... (225 lines truncated)
</file>

<file path="src/config/key.zig">
const std = @import("std");
const Config = @import("Config.zig");

/// Key is an enum of all the available configuration keys. This is used
/// when paired with diff to determine what fields have changed in a config,
/// amongst other things.
pub const Key = key: {
    const field_infos = std.meta.fields(Config);
    var names: [field_infos.len][]const u8 = undefined;
    var raw_values: [field_infos.len]comptime_int = undefined;
    var i: usize = 0;
    for (field_infos, &names, &raw_values) |field, *name, *raw| {
        // Ignore fields starting with "_" since they're internal and
        // not copied ever.
        if (field.name[0] == '_') continue;

        name.* = field.name;
        raw.* = i;
        i += 1;
    }

    const TagInt = std.math.IntFittingRange(0, field_infos.len - 1);
    var values: [i]TagInt = undefined;
    for (raw_values[0..i], &values) |raw, *val| {
        val.* = raw;
    }

    break :key @Enum(TagInt, .exhaustive, names[0..i], &values);
};

... (25 lines truncated)
</file>

<file path="src/config/limit.zig">
const std = @import("std");
const formatterpkg = @import("formatter.zig");

/// A configurable integer limit with a declared default and support for the
/// special value `unlimited`.
///
/// Unlimited is stored as the maximum value of the integer type so the value
/// remains directly comparable without optional unwrapping.
pub fn Limit(comptime T: type, comptime default_value: T) type {
    comptime std.debug.assert(@typeInfo(T) == .int);

    return struct {
        const Self = @This();

        value: T = default_value,

        /// The limit initialized with its declared default value.
        pub const default: Self = .{};

        /// Parses an integer limit or the special value "unlimited".
        pub fn parseCLI(input_: ?[]const u8) !Self {
            const input = input_ orelse return error.ValueRequired;
            if (std.mem.eql(u8, input, "unlimited")) {
                return .{ .value = std.math.maxInt(T) };
            }

            return .{
                .value = std.fmt.parseInt(T, input, 0) catch
                    return error.InvalidValue,
            };
... (86 lines truncated)
</file>

<file path="src/config/path.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;

const cli = @import("../cli.zig");
const internal_os = @import("../os/main.zig");
const formatterpkg = @import("formatter.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.config);

pub const ParseError = error{ValueRequired} || Allocator.Error;

/// Path is like a string that represents a path value. The difference is that
/// when loading the configuration the value for this will be automatically
/// expanded relative to the path of the config file (or the home directory).
pub const Path = union(enum) {
    /// No error if the file does not exist.
    optional: [:0]const u8,

    /// The file is required to exist.
    required: [:0]const u8,

    pub fn len(self: Path) usize {
        return switch (self) {
            inline else => |path| path.len,
        };
    }
... (491 lines truncated)
</file>

<file path="src/config/RepeatableStringMap.zig">
/// RepeatableStringMap is a key/value that can be repeated to accumulate a
/// string map. This isn't called "StringMap" because I find that sometimes
/// leads to confusion that it _accepts_ a map such as JSON dict.
const RepeatableStringMap = @This();
const std = @import("std");
const Allocator = std.mem.Allocator;

const formatterpkg = @import("formatter.zig");

const Map = std.ArrayHashMapUnmanaged(
    [:0]const u8,
    [:0]const u8,
    std.array_hash_map.StringContext,
    true,
);

// Allocator for the list is the arena for the parent config.
map: Map = .{},

pub fn parseCLI(
    self: *RepeatableStringMap,
    alloc: Allocator,
    input: ?[]const u8,
) !void {
    const value = input orelse return error.ValueRequired;

    // Empty value resets the list. We don't need to free our values because
    // the allocator used is always an arena.
    if (value.len == 0) {
        self.map.clearRetainingCapacity();
... (169 lines truncated)
</file>

<file path="src/config/string.zig">
const std = @import("std");

/// Parse a string literal into a byte array. The string can contain
/// any valid Zig string literal escape sequences.
///
/// The output buffer never needs to be larger than the input buffer.
/// The buffers may alias.
pub fn parse(out: []u8, bytes: []const u8) ![]u8 {
    var dst_i: usize = 0;
    var src_i: usize = 0;
    while (src_i < bytes.len) {
        if (dst_i >= out.len) return error.OutOfMemory;

        // If this byte is not beginning an escape sequence we copy.
        const b = bytes[src_i];
        if (b != '\\') {
            out[dst_i] = b;
            dst_i += 1;
            src_i += 1;
            continue;
        }

        // Zig's \xNN syntax represents a single byte, while the other
        // escape sequences represent Unicode codepoints.
        const is_byte_escape = src_i + 1 < bytes.len and
            bytes[src_i + 1] == 'x';

        // Parse the escape sequence
        switch (std.zig.string_literal.parseEscapeSequence(
            bytes,
... (133 lines truncated)
</file>

<file path="src/config/theme.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const internal_os = @import("../os/main.zig");
const cli = @import("../cli.zig");
const global = @import("../global.zig");

/// Location of possible themes. The order of this enum matters because it
/// defines the priority of theme search (from top to bottom).
pub const Location = enum {
    user, // XDG config dir
    resources, // Ghostty resources dir

    /// Returns the directory for the given theme based on this location type.
    ///
    /// This will return null with no error if the directory type doesn't exist
    /// or is invalid for any reason. For example, it is perfectly valid to
    /// install and run Ghostty without the resources directory.
    ///
    /// Due to the way allocations are handled, an Arena allocator (or another
    /// similar allocator implementation) should be used. It may not be safe to
    /// free the returned allocations.
    pub fn dir(
        self: Location,
        arena_alloc: Allocator,
    ) error{ OutOfMemory, Unexpected }!?[]const u8 {
        var environ_map = try global.environMap();
        defer environ_map.deinit();
        return switch (self) {
            .user => user: {
... (252 lines truncated)
</file>

<file path="src/config/url.zig">
const std = @import("std");
const oni = @import("oniguruma");

/// Default URL/path regex. This is used to detect URLs and file paths in
/// terminal output.
///
/// This is here in the config package because one day the matchers will be
/// configurable and this will be a default.
///
/// For scheme URLs, this regex is liberal in what it accepts after the scheme,
/// with exceptions for URLs ending with . or ). Although such URLs are
/// perfectly valid, it is common for text to contain URLs surrounded by
/// parentheses (such as in Markdown links) or at the end of sentences.
/// Therefore, this regex excludes them as follows:
///
/// 1. Do not match regexes ending with .
/// 2. Do not match regexes ending with ), except for ones which contain a (
///    without a subsequent )
///
/// Rule 2 means that we handle the following two cases:
///
///   "https://en.wikipedia.org/wiki/Rust_(video_game)" (include parens)
///   "(https://example.com)" (do not include the parens)
///
/// There are many complicated cases where these heuristics break down, but
/// handling them well requires a non-regex approach.
const url_schemes =
    \\https?://|mailto:|ftp://|file:|ssh:|git://|ssh://|tel:|magnet:|ipfs://|ipns://|gemini://|gopher://|news:
;

... (488 lines truncated)
</file>

<file path="src/config/Wasm.zig">
const std = @import("std");
const wasm = @import("../os/wasm.zig");
const cli = @import("../cli.zig");
const alloc = wasm.alloc;

const Config = @import("Config.zig");

const log = std.log.scoped(.config);

/// Create a new configuration filled with the initial default values.
export fn config_new() ?*Config {
    const result = alloc.create(Config) catch |err| {
        log.err("error allocating config err={}", .{err});
        return null;
    };

    result.* = Config.default(alloc) catch |err| {
        log.err("error creating config err={}", .{err});
        return null;
    };

    return result;
}

export fn config_free(ptr: ?*Config) void {
    if (ptr) |v| {
        v.deinit();
        alloc.destroy(v);
    }
}
... (25 lines truncated)
</file>

<file path="src/crash/dir.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const internal_os = @import("../os/main.zig");

/// Returns a Dir for the default directory. The Dir.path field must be
/// freed with the given allocator.
pub fn defaultDir(io: std.Io, alloc: Allocator, environ_map: *const std.process.Environ.Map) !Dir {
    const crash_dir = try internal_os.xdg.state(io, alloc, environ_map, .{ .subdir = "ghostty/crash" });
    errdefer alloc.free(crash_dir);
    return .{ .path = crash_dir };
}

pub const Dir = struct {
    /// The directory where crash reports are stored. This memory is owned
    /// by the caller.
    path: []const u8,

    /// Returns an iterator over the crash reports in this directory. This
    /// iterator must be freed with `ReportIterator.deinit`. The iterator
    /// may have no reports.
    pub fn iterator(self: *const Dir, io: std.Io) !ReportIterator {
        var dir = std.Io.Dir.openDirAbsolute(
            io,
            self.path,
            .{ .iterate = true },
        ) catch return .{};
        errdefer dir.close(io);

        return .{
            .dir = dir,
... (37 lines truncated)
</file>

<file path="src/crash/main.zig">
//! The crash package contains all the logic around crash handling,
//! whether that's setting up the system to catch crashes (Sentry client),
//! introspecting crash reports, writing crash reports to disk, etc.

const dir = @import("dir.zig");
const sentry_envelope = @import("sentry_envelope.zig");

pub const sentry = @import("sentry.zig");
pub const Envelope = sentry_envelope.Envelope;
pub const defaultDir = dir.defaultDir;
pub const Dir = dir.Dir;
pub const ReportIterator = dir.ReportIterator;
pub const Report = dir.Report;

// The main init/deinit functions for global state.
pub const init = sentry.init;
pub const deinit = sentry.deinit;

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/crash/sentry_envelope.zig">
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;

const log = std.log.scoped(.sentry_envelope);

/// The Sentry Envelope format: https://develop.sentry.dev/sdk/envelopes/
///
/// The envelope is our primary crash report format since use the Sentry
/// client. It is designed and created by Sentry but is an open format
/// in that it is publicly documented and can be used by any system. This
/// lets us utilize the Sentry client for crash capture but also gives us
/// the opportunity to migrate to another system if we need to, and doesn't
/// force any user or developer to use Sentry the SaaS if they don't want
/// to.
///
/// This struct implements reading the envelope format (writing is not needed
/// currently but can be added later). It is incomplete; I only implemented
/// what I needed at the time.
pub const Envelope = struct {
    /// The arena that the envelope is allocated in. All items are welcome
    /// to use this allocator for their data, which is freed on deinit.
    arena: std.heap.ArenaAllocator,

    /// The headers of the envelope decoded into a json ObjectMap.
    headers: std.json.ObjectMap,

    /// The items in the envelope in the order they're encoded.
    items: std.ArrayList(Item),

... (568 lines truncated)
</file>

<file path="src/crash/sentry.zig">
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const build_config = @import("../build_config.zig");
const build_options = @import("build_options");
const sentry = if (build_options.sentry) @import("sentry");
const internal_os = @import("../os/main.zig");
const crash = @import("main.zig");
const Surface = @import("../Surface.zig");

const log = std.log.scoped(.sentry);

/// The global state for the Sentry SDK. This is unavoidable since crash
/// handling is a global process-wide thing.
var init_thread: ?std.Thread = null;

/// Directory memory, holds the cache and state dirs persistently. This
/// prevents any sort of crashes due to initialization races.
var dir_mem: [std.fs.max_path_bytes * 2]u8 = undefined;

/// Holds the XDG cache dir.
var cache_dir_: ?[]const u8 = null;

/// Holds the XDG state dir.
var state_dir_: ?[]const u8 = null;

/// Thread-local state that can be set by thread main functions so that
/// crashes have more context.
///
... (344 lines truncated)
</file>

<file path="src/datastruct/blocking_queue.zig">
//! Blocking queue implementation aimed primarily for message passing
//! between threads.

const std = @import("std");
const Allocator = std.mem.Allocator;
const compat_thread = @import("../lib/compat/thread.zig");

/// Returns a blocking queue implementation for type T.
///
/// This is tailor made for ghostty usage so it isn't meant to be maximally
/// generic, but I'm happy to make it more generic over time. Traits of this
/// queue that are specific to our usage:
///
///   - Fixed size. We expect our queue to quickly drain and also not be
///     too large so we prefer a fixed size queue for now.
///   - No blocking pop. We use an external event loop mechanism such as
///     eventfd to notify our waiter that there is no data available so
///     we don't need to implement a blocking pop.
///   - Drain function. Most queues usually pop one at a time. We have
///     a mechanism for draining since on every IO loop our TTY drains
///     the full queue so we can get rid of the overhead of a ton of
///     locks and bounds checking and do a one-time drain.
///
/// One key usage pattern is that our blocking queues are single producer
/// single consumer (SPSC). This should let us do some interesting optimizations
/// in the future. At the time of writing this, the blocking queue implementation
/// is purposely naive to build something quickly, but we should benchmark
/// and make this more optimized as necessary.
pub fn BlockingQueue(
    comptime T: type,
... (232 lines truncated)
</file>

<file path="src/datastruct/cache_table.zig">
const fastmem = @import("../fastmem.zig");

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;

/// An associative data structure used for efficiently storing and
/// retrieving values which are able to be recomputed if necessary.
///
/// This structure is effectively a hash table with fixed-sized buckets.
///
/// When inserting an item in to a full bucket, the least recently used
/// item is replaced.
///
/// To achieve this, when an item is accessed, it's moved to the end of
/// the bucket, and the rest of the items are moved over to fill the gap.
///
/// This should provide very good query performance and keep frequently
/// accessed items cached indefinitely.
///
/// Parameters:
///
/// `Context`
///   A type containing methods to define CacheTable behaviors.
///   - `fn hash(*Context, K) u64`    - Return a hash for a key.
///   - `fn eql(*Context, K, K) bool` - Check two keys for equality.
///
///   - `fn evicted(*Context, K, V) void` - [OPTIONAL] Eviction callback.
///     If present, called whenever an item is evicted from the cache.
///
/// `bucket_count`
... (152 lines truncated)
</file>

<file path="src/datastruct/circ_buf.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const fastmem = @import("../fastmem.zig");

/// Returns a circular buffer containing type T.
pub fn CircBuf(comptime T: type, comptime default: T) type {
    return struct {
        const Self = @This();

        // Implementation note: there's a lot of unsafe addition of usize
        // here in this implementation that can technically overflow. If someone
        // wants to fix this and make it overflow safe (use subtractions for
        // checks prior to additions) then I welcome it. In reality, we'd
        // have to be a really, really large terminal screen to even worry
        // about this so I'm punting it.

        storage: []T,
        head: usize,
        tail: usize,

        // We could remove this and just use math with head/tail to figure
        // it out, but our usage of circular buffers stores so much data that
        // this minor overhead is not worth optimizing out.
        full: bool,

        pub const Iterator = struct {
            buf: Self,
            idx: usize,
            direction: Direction,
... (892 lines truncated)
</file>

<file path="src/datastruct/comparison.zig">
// The contents of this file is largely based on testing.zig from the Zig 0.15.1
// stdlib, distributed under the MIT license, copyright (c) Zig contributors
const std = @import("std");
const testing = std.testing;

/// A deep equality comparison function that works for most types. We
/// add types as necessary. It defers to `equal` decls on types that support
/// decls.
pub fn deepEqual(comptime T: type, old: T, new: T) bool {
    // Do known named types first
    switch (T) {
        inline []const u8,
        [:0]const u8,
        => return std.mem.eql(u8, old, new),

        []const [:0]const u8,
        => {
            if (old.len != new.len) return false;
            for (old, new) |a, b| {
                if (!std.mem.eql(u8, a, b)) return false;
            }

            return true;
        },

        else => {},
    }

    // Back into types of types
    switch (@typeInfo(T)) {
... (403 lines truncated)
</file>

<file path="src/datastruct/comptime_int_set.zig">
const std = @import("std");
const assert = std.debug.assert;

/// A fixed set of integers that is known at compile time and can be
/// searched quickly at runtime.
///
/// Use this when you have a table of integer IDs defined at comptime and
/// need to find which entry a runtime value belongs to. The common way to
/// write that is a loop over the table:
///
///     inline for (entries, 0..) |entry, i| {
///         if (entry.id == id) return i;
///     }
///     return null;
///
/// That loop compiles to one comparison per entry. Entries near the end
/// of the table, and values that aren't in the table at all, pay for every
/// comparison before them. This type sorts the keys at comptime and does
/// a binary search instead, so every lookup costs about log2(N)
/// comparisons no matter which key is looked up. The search has a fixed
/// number of steps and no loop, which lets the compiler emit it without
/// branches.
///
/// `indexOf` returns the position of the key in the `keys` slice you
/// passed in, not its position in the sorted order. This means you can
/// use the result to index any other table that is in the same order as
/// `keys`:
///
///     const Entry = struct { id: u16, name: []const u8 };
///     const entries = [_]Entry{
... (143 lines truncated)
</file>

<file path="src/datastruct/intrusive_linked_list.zig">
const std = @import("std");
const testing = std.testing;

/// An intrusive doubly-linked list. The type T must have a "next" and "prev"
/// field pointing to itself.
///
/// This is an adaptation of the DoublyLinkedList from the Zig standard
/// library, which is MIT licensed. I've removed functionality that I don't
/// need.
pub fn DoublyLinkedList(comptime T: type) type {
    return struct {
        const Self = @This();

        /// The type of the node in the list. This makes it easy to get the
        /// node type from the list type.
        pub const Node = T;

        first: ?*Node = null,
        last: ?*Node = null,

        /// Insert a new node after an existing one.
        ///
        /// Arguments:
        ///     node: Pointer to a node in the list.
        ///     new_node: Pointer to the new node to insert.
        pub inline fn insertAfter(list: *Self, node: *Node, new_node: *Node) void {
            new_node.prev = node;
            if (node.next) |next_node| {
                // Intermediate node.
                new_node.next = next_node;
... (152 lines truncated)
</file>

<file path="src/datastruct/limited_allocator.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

/// An allocator that rejects any single allocation or resize larger than a
/// configured byte limit. The limit applies to each request independently,
/// not to the total amount of memory currently allocated.
pub const LimitedAllocator = struct {
    child: Allocator,
    limit: usize,

    /// Set after an allocation, resize, or remap is rejected for exceeding
    /// the limit. This remains set until the caller clears it.
    limit_exceeded: bool = false,

    pub fn init(child: Allocator, limit: usize) LimitedAllocator {
        return .{
            .child = child,
            .limit = limit,
        };
    }

    pub fn allocator(self: *LimitedAllocator) Allocator {
        return .{
            .ptr = self,
            .vtable = &.{
                .alloc = alloc,
                .resize = resize,
                .remap = remap,
                .free = free,
            },
... (95 lines truncated)
</file>

<file path="src/datastruct/main.zig">
//! The datastruct package contains data structures or anything closely
//! related to data structures.

const blocking_queue = @import("blocking_queue.zig");
const cache_table = @import("cache_table.zig");
const circ_buf = @import("circ_buf.zig");
const intrusive_linked_list = @import("intrusive_linked_list.zig");
const split_tree = @import("split_tree.zig");

pub const BlockingQueue = blocking_queue.BlockingQueue;
pub const CacheTable = cache_table.CacheTable;
pub const CircBuf = circ_buf.CircBuf;
pub const ComptimeIntSet = @import("comptime_int_set.zig").ComptimeIntSet;
pub const IntrusiveDoublyLinkedList = intrusive_linked_list.DoublyLinkedList;
pub const LimitedAllocator = @import("limited_allocator.zig").LimitedAllocator;
pub const MessageData = @import("message_data.zig").MessageData;
pub const SplitTree = split_tree.SplitTree;
pub const UntouchedPool = @import("untouched_pool.zig").UntouchedPool;
pub const WasmPagePool = @import("wasm_page_pool.zig").WasmPagePool;

test {
    @import("std").testing.refAllDecls(@This());

    _ = @import("comparison.zig");
}
</file>

<file path="src/datastruct/message_data.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;

/// Creates a union that can be used to accommodate data that fit within an array,
/// are a stable pointer, or require deallocation. This is helpful for thread
/// messaging utilities.
pub fn MessageData(comptime Elem: type, comptime small_size: comptime_int) type {
    return union(enum) {
        pub const Self = @This();

        pub const Small = struct {
            pub const Max = small_size;
            pub const Array = [Max]Elem;
            pub const Len = std.math.IntFittingRange(0, small_size);
            data: Array = undefined,
            len: Len = 0,
        };

        pub const Alloc = struct {
            alloc: Allocator,
            data: []Elem,
        };

        pub const Stable = []const Elem;

        /// A small write where the data fits into this union size.
        small: Small,

        /// A stable pointer so we can just pass the slice directly through.
... (95 lines truncated)
</file>

<file path="src/datastruct/segmented_list.zig">
//! Code taken from 0.15.2 `std.segmented_list` (MIT license). See
//! lib/compat/README.md for license and details.
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const testing = std.testing;
const mem = std.mem;
const Allocator = std.mem.Allocator;

// Imagine that `fn at(self: *Self, index: usize) &T` is a customer asking for a box
// from a warehouse, based on a flat array, boxes ordered from 0 to N - 1.
// But the warehouse actually stores boxes in shelves of increasing powers of 2 sizes.
// So when the customer requests a box index, we have to translate it to shelf index
// and box index within that shelf. Illustration:
//
// customer indexes:
// shelf 0:  0
// shelf 1:  1  2
// shelf 2:  3  4  5  6
// shelf 3:  7  8  9 10 11 12 13 14
// shelf 4: 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// shelf 5: 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
// ...
//
// warehouse indexes:
// shelf 0:  0
// shelf 1:  0  1
// shelf 2:  0  1  2  3
// shelf 3:  0  1  2  3  4  5  6  7
// shelf 4:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
// shelf 5:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
... (504 lines truncated)
</file>

<file path="src/datastruct/split_tree.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const build_config = @import("../build_config.zig");
const ArenaAllocator = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;

/// SplitTree represents a tree of view types that can be divided.
///
/// Concretely for Ghostty, it represents a tree of terminal views. In
/// its basic state, there are no splits and it is a single full-sized
/// terminal. However, it can be split arbitrarily many times among two
/// axes (horizontal and vertical) to create a tree of terminal views.
///
/// This is an immutable tree structure, meaning all operations on it
/// will return a new tree with the operation applied. This allows us to
/// store versions of the tree in a history for easy undo/redo. To facilitate
/// this, the stored View type must implement reference counting; this is left
/// as an implementation detail of the View type.
///
/// The View type will be stored as a pointer within the tree and must
/// implement a number of functions to work properly:
///
///   - `fn ref(*View, Allocator) Allocator.Error!*View` - Increase a
///     reference count of the view. The Allocator will be the allocator provided
///     to the tree operation. This is allowed to copy the value if it wants to;
///     the returned value is expected to be a new reference (but that may
///     just be a copy).
///
///   - `fn unref(*View, Allocator) void` - Decrease the reference count of a
///     view. The Allocator will be the allocator provided to the tree
... (2500 lines truncated)
</file>

<file path="src/datastruct/untouched_pool.zig">
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Alignment = std.mem.Alignment;

/// A fixed-size item pool whose bookkeeping never touches item memory.
///
/// std.heap.MemoryPool keeps its free list inside the items intrusively,
/// meaning it has to touch allocated item memory. For memory that is
/// demand-paged, that write forces the OS to create a physical page
/// for nothing (to mark it free!).
///
/// This pool keeps the free list in a separate array allocated from a
/// general-purpose allocator and allocates every item individually from
/// the item allocator with the requested alignment. The pool never reads
/// or writes an item until it is needed.
///
/// Contracts:
///
///   - The pool never zeroes. Callers that need zeroed items must use an
///     item allocator that returns zeroed memory and must zero (or
///     decommit) an item before destroy().
///   - destroy() never allocates and never fails: create() reserves a
///     free-list slot for every live item before allocating a new one.
///   - The pool tracks free items only. Every item must be returned with
///     destroy() or release() before reset() or deinit(), or it leaks.
///     This is asserted in safe builds.
///
/// The tradeoff is that this isn't as fast as std.heap.MemoryPool, its
/// not as cache friendly. But benchmarks show that the cost is minimal
... (277 lines truncated)
</file>

<file path="src/datastruct/wasm_page_pool.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;

/// A memory pool of wasm-page-multiple-sized items backed directly by
/// wasm linear memory, for wasm targets only.
///
/// This is necessary for two reasons: the std.heap.MemoryPool grows 1.5x
/// at each growth point. The backing allocator for that is usually a GPA
/// which is the BrkAllocator for wasm. This grows by power-of-two
/// big-allocation slots. If you pair these together you get a massive
/// permanent linear memory growth. Native (non-wasm) targets don't care
/// because unused virtual mappings are effectively free, but this isn't
/// exactly true for Wasm runtimes.
///
/// This pool instead grows exactly @sizeOf(Item) bytes of fresh linear
/// memory per item with memory.grow (which also guarantees wasm-page
/// alignment and zeroing) and recycles freed items through a free list
/// that is container-level, i.e. shared by every pool of the same Item
/// type in the module instance. Every freed item is immediately
/// reusable by every pool, and each item costs exactly @sizeOf(Item)
/// reserved bytes, ever.
///
/// The "shared by every pool of the same Item type" is really important:
/// the normal Ghostty memory pool is per-terminal. This one is per-module.
/// The Ghostty wasm modules are not multi-threaded so this doesn't require
/// any synchronization. But this means that all terminals share one pool
/// so memory doesn't balloon like crazy that way either.
///
... (141 lines truncated)
</file>

<file path="src/extra/bash.zig">
const std = @import("std");

const Config = @import("../config/Config.zig");
const Action = @import("../cli.zig").ghostty.Action;

/// A bash completions configuration that contains all the available commands
/// and options.
///
/// Notes: bash completion support for --<key>=<value> depends on setting the completion
/// system to _not_ print a space following each successful completion (see -o nospace).
/// This results leading or tailing spaces being necessary to move onto the next match.
///
/// bash completion will read = as it's own completiong word regardless of whether or not
/// it's part of an on going completion like --<key>=. Working around this requires looking
/// backward in the command line args to pretend the = is an empty string
/// see: https://www.gnu.org/software/gnuastro/manual/html_node/Bash-TAB-completion-tutorial.html
pub const completions = comptimeGenerateBashCompletions();

fn comptimeGenerateBashCompletions() []const u8 {
    comptime {
        @setEvalBranchQuota(50000);
        var counter: std.Io.Writer.Discarding = .init(&.{});
        try writeBashCompletions(&counter.writer);

        var buf: [counter.count]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buf);
        try writeBashCompletions(&writer);
        const final = buf;
        return final[0..writer.end];
    }
... (308 lines truncated)
</file>

<file path="src/extra/fish.zig">
//! Fish completions.
const std = @import("std");

const Config = @import("../config/Config.zig");
const Action = @import("../cli.zig").ghostty.Action;
const help_strings = @import("help_strings");

/// A fish completions configuration that contains all the available commands
/// and options.
pub const completions = comptimeGenerateCompletions();

fn comptimeGenerateCompletions() []const u8 {
    comptime {
        @setEvalBranchQuota(50000);
        var counter: std.Io.Writer.Discarding = .init(&.{});
        try writeCompletions(&counter.writer);

        var buf: [counter.count]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buf);
        try writeCompletions(&writer);
        const final = buf;
        return final[0..writer.end];
    }
}

fn writeCompletions(writer: *std.Io.Writer) !void {
    {
        try writer.writeAll("set -l commands \"");
        var count: usize = 0;
        for (@typeInfo(Action).@"enum".fields) |field| {
... (173 lines truncated)
</file>

<file path="src/extra/sublime.zig">
const Config = @import("../config/Config.zig");

const Template = struct {
    const header =
        \\%YAML 1.2
        \\---
        \\# See http://www.sublimetext.com/docs/syntax.html
        \\name: Ghostty Config
        \\file_extensions:
        \\  - ghostty
        \\scope: source.ghostty
        \\
        \\contexts:
        \\  main:
        \\    # Comments
        \\    - match: '^\s*#.*$'
        \\      scope: comment.line.number-sign.ghostty
        \\
        \\    # Keywords
        \\    - match: '\b(
    ;
    const footer =
        \\)\b'
        \\      scope: keyword.other.ghostty
        \\
    ;
};

/// Check if a field is internal (starts with underscore)
fn isInternal(name: []const u8) bool {
... (21 lines truncated)
</file>

<file path="src/extra/vim.zig">
const std = @import("std");
const Config = @import("../config/Config.zig");

/// This is the associated Vim file as named by the variable.
pub const syntax = comptimeGenSyntax();
pub const ftdetect =
    \\" Vim filetype detect file
    \\" Language: Ghostty config file
    \\" Maintainer: Ghostty <https://github.com/ghostty-org/ghostty>
    \\"
    \\" THIS FILE IS AUTO-GENERATED
    \\
    \\au BufRead,BufNewFile */ghostty/config,*/*.ghostty/config,*/ghostty/themes/*,*.ghostty setf ghostty
    \\
;
pub const ftplugin =
    \\" Vim filetype plugin file
    \\" Language: Ghostty config file
    \\" Maintainer: Ghostty <https://github.com/ghostty-org/ghostty>
    \\"
    \\" THIS FILE IS AUTO-GENERATED
    \\
    \\if exists('b:did_ftplugin')
    \\  finish
    \\endif
    \\let b:did_ftplugin = 1
    \\
    \\setlocal commentstring=#\ %s
    \\setlocal iskeyword+=-
    \\
... (92 lines truncated)
</file>

<file path="src/extra/zsh.zig">
const std = @import("std");

const Config = @import("../config/Config.zig");
const Action = @import("../cli.zig").ghostty.Action;

/// A zsh completions configuration that contains all the available commands
/// and options.
pub const completions = comptimeGenerateZshCompletions();

const equals_required = "=-:::";

fn comptimeGenerateZshCompletions() []const u8 {
    comptime {
        @setEvalBranchQuota(50000);
        var counter: std.Io.Writer.Discarding = .init(&.{});
        try writeZshCompletions(&counter.writer);

        var buf: [counter.count]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buf);
        try writeZshCompletions(&writer);
        const final = buf;
        return final[0..writer.end];
    }
}

fn writeZshCompletions(writer: *std.Io.Writer) !void {
    try writer.writeAll(
        \\#compdef ghostty
        \\
        \\_fonts () {
... (202 lines truncated)
</file>

<file path="src/font/face/coretext.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const macos = @import("macos");
const harfbuzz = @import("harfbuzz");
const font = @import("../main.zig");
const opentype = @import("../opentype.zig");
const quirks = @import("../../quirks.zig");

const log = std.log.scoped(.font_face);

pub const Face = struct {
    /// Our font face
    font: *macos.text.Font,

    /// Harfbuzz font corresponding to this face. We only use this
    /// if we're using Harfbuzz.
    hb_font: if (harfbuzz_shaper) harfbuzz.Font else void,

    /// Set quirks.disableDefaultFontFeatures
    quirks_disable_default_font_features: bool = false,

    /// True if this font face should be rasterized with a synthetic bold
    /// effect. This is used for fonts that don't have a bold variant.
    synthetic_bold: ?f64 = null,

    /// If the face can possibly be colored, then this is the state
    /// used to check for color information. This is null if the font
    /// can't possibly be colored (i.e. doesn't have SVG, sbix, etc
... (1134 lines truncated)
</file>

<file path="src/font/face/freetype.zig">
//! Face represents a single font face. A single font face has a single set
//! of properties associated with it such as style, weight, etc.
//!
//! A Face isn't typically meant to be used directly. It is usually used
//! via a Family in order to store it in an Atlas.

const std = @import("std");
const builtin = @import("builtin");
const freetype = @import("freetype");
const harfbuzz = @import("harfbuzz");
const stb = @import("../../stb/main.zig");
const assert = @import("../../quirks.zig").inlineAssert;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const font = @import("../main.zig");
const Glyph = font.Glyph;
const Library = font.Library;
const opentype = @import("../opentype.zig");
const quirks = @import("../../quirks.zig");
const config = @import("../../config.zig");
const global = @import("../../global.zig");

const F26Dot6 = opentype.sfnt.F26Dot6;

const log = std.log.scoped(.font_face);

pub const Face = struct {
    comptime {
        // If we have the freetype backend, we should have load flags.
        assert(font.face.FreetypeLoadFlags != void);
... (1411 lines truncated)
</file>

<file path="src/font/face/web_canvas.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const js = @import("zig-js");
const font = @import("../main.zig");

const log = std.log.scoped(.font_face);

pub const Face = struct {
    /// See graphemes field for more details.
    const grapheme_start: u32 = 0x10FFFF + 1;
    const grapheme_end: u32 = std.math.maxInt(u32);

    /// The web canvas face makes use of an allocator when interacting
    /// with the JS environment.
    alloc: Allocator,

    /// The CSS "font" attribute, excluding size.
    font_str: []const u8,

    /// The size we currently have set.
    size: font.face.DesiredSize,

    /// The presentation for this font.
    presentation: font.Presentation,

    /// Metrics for this font face. These are useful for renderers.
    metrics: font.Metrics,

... (532 lines truncated)
</file>

<file path="src/font/opentype/glyf.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const sfnt = @import("sfnt.zig");
const compat_reader = @import("../../lib/compat/reader.zig");

/// Glyph Data Table
///
/// This takes a little bit of a different form than other tables that we
/// have parsers for. Due to the fact that this table contains arrays of
/// arbitrary length, we store a pointer (slice) to the underlying data,
/// and then have functions for getting and interpreting specific parts.
///
/// References:
/// - https://learn.microsoft.com/en-us/typography/opentype/spec/glyf
///
/// Field names are in camelCase to match names in spec.
pub const Glyf = struct {
    data: []const u8,

    /// A decoded glyph outline.
    ///
    /// The `contours` slice is the list of end point indices and
    /// `points` owns all the points. Glyf guarantees that contour
    /// points are sequential so we can just store the end and calculate
    /// the points that way. Use the helpers to make it ergonomic.
    pub const Outline = struct {
        /// List of contour end points. Calculate the full list of
        /// points using points[prev...this+1]
        contours: []const sfnt.uint16,

... (1011 lines truncated)
</file>

<file path="src/font/opentype/head.zig">
const std = @import("std");
const sfnt = @import("sfnt.zig");
const compat_reader = @import("../../lib/compat/reader.zig");

/// Font Header Table
///
/// References:
/// - https://learn.microsoft.com/en-us/typography/opentype/spec/head
///
/// Field names are in camelCase to match names in spec.
pub const Head = extern struct {
    /// Major version number of the font header table — set to 1.
    majorVersion: sfnt.uint16 align(1),

    /// Minor version number of the font header table — set to 0.
    minorVersion: sfnt.uint16 align(1),

    /// Set by font manufacturer.
    fontRevision: sfnt.Fixed align(1),

    /// To compute: set it to 0, sum the entire font as uint32, then store
    /// 0xB1B0AFBA - sum. If the font is used as a component in a font
    /// collection file, the value of this field will be invalidated by
    /// changes to the file structure and font table directory, and must
    /// be ignored.
    checksumAdjustment: sfnt.uint32 align(1),

    /// Set to 0x5F0F3CF5.
    magicNumber: sfnt.uint32 align(1),

... (150 lines truncated)
</file>

<file path="src/font/opentype/hhea.zig">
const std = @import("std");
const sfnt = @import("sfnt.zig");
const compat_reader = @import("../../lib/compat/reader.zig");

/// Horizontal Header Table
///
/// References:
/// - https://learn.microsoft.com/en-us/typography/opentype/spec/hhea
///
/// Field names are in camelCase to match names in spec.
pub const Hhea = extern struct {
    /// Major version number of the horizontal header table — set to 1.
    majorVersion: sfnt.uint16 align(1),

    /// Minor version number of the horizontal header table — set to 0.
    minorVersion: sfnt.uint16 align(1),

    /// Typographic ascent—see remarks below.
    ascender: sfnt.FWORD align(1),

    /// Typographic descent—see remarks below.
    descender: sfnt.FWORD align(1),

    /// Typographic line gap.
    ///
    /// Negative lineGap values are treated as zero
    /// in some legacy platform implementations.
    lineGap: sfnt.FWORD align(1),

    /// Maximum advance width value in 'hmtx' table.
... (86 lines truncated)
</file>

<file path="src/font/opentype/os2.zig">
const std = @import("std");
const sfnt = @import("sfnt.zig");
const compat_reader = @import("../../lib/compat/reader.zig");

pub const FSSelection = packed struct(sfnt.uint16) {
    /// Font contains italic or oblique glyphs, otherwise they are upright.
    italic: bool = false,

    /// Glyphs are underscored.
    underscore: bool = false,

    /// Glyphs have their foreground and background reversed.
    negative: bool = false,

    /// Outline (hollow) glyphs, otherwise they are solid.
    outlined: bool = false,

    /// Glyphs are overstruck.
    strikeout: bool = false,

    /// Glyphs are emboldened.
    bold: bool = false,

    /// Glyphs are in the standard weight/style for the font.
    regular: bool = false,

    /// If set, it is strongly recommended that applications use
    /// OS/2.sTypoAscender - OS/2.sTypoDescender + OS/2.sTypoLineGap
    /// as the default line spacing for this font.
    use_typo_metrics: bool = false,
... (551 lines truncated)
</file>

<file path="src/font/opentype/post.zig">
const std = @import("std");
const sfnt = @import("sfnt.zig");
const compat_reader = @import("../../lib/compat/reader.zig");

/// PostScript Table
///
/// This implementation doesn't parse the
/// extra fields in versions 2.0 and 2.5.
///
/// References:
/// - https://learn.microsoft.com/en-us/typography/opentype/spec/post
///
/// Field names are in camelCase to match names in spec.
pub const Post = extern struct {
    version: sfnt.Version16Dot16 align(1),

    /// Italic angle in counter-clockwise degrees from the vertical.
    /// Zero for upright text, negative for text that leans to the
    /// right (forward).
    italicAngle: sfnt.Fixed align(1),

    /// Suggested y-coordinate of the top of the underline.
    underlinePosition: sfnt.FWORD align(1),

    /// Suggested values for the underline thickness.
    /// In general, the underline thickness should match the thickness of
    /// the underscore character (U+005F LOW LINE), and should also match
    /// the strikeout thickness, which is specified in the OS/2 table.
    underlineThickness: sfnt.FWORD align(1),

... (53 lines truncated)
</file>

<file path="src/font/opentype/sfnt.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;

/// 8-bit unsigned integer.
pub const uint8 = u8;

/// 8-bit signed integer.
pub const int8 = i8;

/// 16-bit unsigned integer.
pub const uint16 = u16;

/// 16-bit signed integer.
pub const int16 = i16;

/// 24-bit unsigned integer.
pub const uint24 = u24;

/// 32-bit unsigned integer.
pub const uint32 = u32;

/// 32-bit signed integer.
pub const int32 = i32;

/// 32-bit signed fixed-point number (16.16)
pub const Fixed = FixedPoint(i32, 16, 16);

/// int16 that describes a quantity in font design units.
pub const FWORD = i16;
... (288 lines truncated)
</file>

<file path="src/font/opentype/svg.zig">
const std = @import("std");
const font = @import("../main.zig");
const compat_reader = @import("../../lib/compat/reader.zig");

/// SVG glyphs description table.
///
/// This struct is focused purely on the operations we need for Ghostty,
/// namely to be able to look up whether an glyph ID is present in the SVG
/// table or not. This struct isn't meant to be a general purpose SVG table
/// reader.
///
/// References:
/// - https://www.w3.org/2013/10/SVG_in_OpenType/#thesvg
/// - https://learn.microsoft.com/en-us/typography/opentype/spec/svg
pub const SVG = struct {
    /// The start and end glyph IDs (inclusive) that are present in the
    /// table. This is used to very quickly include/exclude a glyph from
    /// the table.
    start_glyph_id: u16,
    end_glyph_id: u16,

    /// All records in the table.
    records: []const [12]u8,

    pub fn init(data: []const u8) (error{SVGVersionNotSupported} || std.Io.Reader.Error)!SVG {
        var reader: std.Io.Reader = .fixed(data);

        // Version
        if (try compat_reader.readerInt(&reader, u16, .big) != 0) {
            return error.SVGVersionNotSupported;
... (92 lines truncated)
</file>

<file path="src/font/res/BSD-2-Clause.txt">
Copyright (c) 2018-2024, Frederic Cambus
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
</file>

<file path="src/font/res/MIT.txt">
MIT License

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.
</file>

<file path="src/font/res/OFL.txt">
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org


-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------

PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.

The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.

DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.

... (62 lines truncated)
</file>

<file path="src/font/res/README.md">
# Fonts and Licenses

This project uses several fonts which fall under the SIL Open Font License (OFL-1.1), MIT License, and BSD 2-Clause License:

- Code New Roman (OFL-1.1)
  - [© 2014 Sam Radian. All Rights Reserved.](https://github.com/chrissimpkins/codeface/blob/master/fonts/code-new-roman/license.txt)
- Geist Mono (OFL-1.1)
  - [Copyright (c) 2023 Vercel, in collaboration with basement.studio](https://github.com/vercel/geist-font/blob/main/LICENSE.txt)
- Inconsolata (OFL-1.1)
  - [Copyright 2006 The Inconsolata Project Authors](https://github.com/google/fonts/blob/main/ofl/inconsolata/OFL.txt)
- JetBrains Mono (OFL-1.1)
  - [Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)](https://github.com/JetBrains/JetBrainsMono/blob/master/OFL.txt)
- JuliaMono (OFL-1.1)
  - [Copyright (c) 2020 - 2023, cormullion
    with Reserved Font Name JuliaMono.](https://github.com/cormullion/juliamono/blob/master/LICENSE)
- Kawkab Mono (OFL-1.1)
  - [Copyright (c) 2015, Abdullah Arif (abdullah.a@gmail.com). Copyright 2010, 2012, 2014 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries.
    ](https://github.com/aiaf/kawkab-mono/blob/master/OFL.txt)
- Lilex (OFL-1.1)
  - [Copyright 2019 The Lilex Project Authors (https://github.com/mishamyrt/Lilex)](https://github.com/mishamyrt/Lilex/blob/master/OFL.txt)
- Monaspace Neon (OFL-1.1)
  - [Copyright (c) 2023, GitHub https://github.com/githubnext/monaspace
    with Reserved Font Name "Monaspace", including subfamilies: "Argon", "Neon", "Xenon", "Radon", and "Krypton"](https://github.com/githubnext/monaspace/blob/main/LICENSE)
- Noto Emoji (OFL-1.1)
  - [Copyright 2013 Google LLC](https://github.com/googlefonts/noto-emoji/blob/main/LICENSE)
- Cozette (MIT)
  - [Copyright (c) 2020, Slavfox](https://github.com/slavfox/Cozette/blob/main/LICENSE)
- Terminus TTF (OFL-1.1)
  - [Copyright (c) 2010-2020 Dimitar Toshkov Zhekov with Reserved Font Name "Terminus Font"](https://sourceforge.net/projects/terminus-font/)
  - [Copyright (c) 2011-2023 Tilman Blumenbach with Reserved Font Name "Terminus (TTF)"](https://files.ax86.net/terminus-ttf/)
... (10 lines truncated)
</file>

<file path="src/font/res/spleen-8x16.bdf">
STARTFONT 2.1
COMMENT /*
COMMENT  * Spleen 8x16 2.1.0
COMMENT  * Copyright (c) 2018-2024, Frederic Cambus
COMMENT  * https://www.cambus.net/
COMMENT  *
COMMENT  * Created:      2018-08-11
COMMENT  * Last Updated: 2024-01-27
COMMENT  *
COMMENT  * Spleen is released under the BSD 2-Clause license.
COMMENT  * See LICENSE file for details.
COMMENT  *
COMMENT  * SPDX-License-Identifier: BSD-2-Clause
COMMENT  */
FONT -misc-spleen-medium-r-normal--16-160-72-72-C-80-ISO10646-1
SIZE 16 72 72
FONTBOUNDINGBOX 8 16 0 -4
STARTPROPERTIES 20
FAMILY_NAME "Spleen"
WEIGHT_NAME "Medium"
FONT_VERSION "2.1.0"
FOUNDRY "misc"
SLANT "R"
SETWIDTH_NAME "Normal"
PIXEL_SIZE 16
POINT_SIZE 160
RESOLUTION_X 72
RESOLUTION_Y 72
SPACING "C"
AVERAGE_WIDTH 80
... (22299 lines truncated)
</file>

<file path="src/font/shaper/testdata/arabic.txt">
غريبه لاني عربي أبا عن جد
واتكلم الانجليزية بطلاقة اكثر من ٢٥ سنه
ومع هذا اجد العربيه افضل لان فيها الكثير من المفردات الاكثر دقه بالوصف
</file>

<file path="src/font/shaper/Cache.zig">
//! This structure caches the shaped cells for a given text run.
//!
//! At one point, shaping was the most expensive part of rendering text
//! (accounting for 96% of frame time on my machine). To speed it up, this
//! was introduced so that shaping results can be cached depending on the
//! run.
//!
//! The cache key is the text run. The text run builds its own hash value
//! based on the font, style, codepoint, etc. This just utilizes the hash that
//! the text run provides.
pub const Cache = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const font = @import("../main.zig");
const CacheTable = @import("../../datastruct/main.zig").CacheTable;

const log = std.log.scoped(.font_shaper_cache);

/// Context for cache table.
const CellCacheTableContext = struct {
    pub fn hash(self: *const CellCacheTableContext, key: u64) u64 {
        _ = self;
        return key;
    }
    pub fn eql(self: *const CellCacheTableContext, a: u64, b: u64) bool {
        _ = self;
        return a == b;
    }
};
... (77 lines truncated)
</file>

<file path="src/font/shaper/coretext.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const macos = @import("macos");
const font = @import("../main.zig");
const os = @import("../../os/main.zig");
const terminal = @import("../../terminal/main.zig");
const unicode = @import("../../unicode/main.zig");
const Feature = font.shape.Feature;
const FeatureList = font.shape.FeatureList;
const default_features = font.shape.default_features;
const Face = font.Face;
const Collection = font.Collection;
const DeferredFace = font.DeferredFace;
const Group = font.Group;
const GroupCache = font.GroupCache;
const Library = font.Library;
const SharedGrid = font.SharedGrid;
const Style = font.Style;
const Presentation = font.Presentation;
const CFReleaseThread = os.CFReleaseThread;
const global = @import("../../global.zig");

const log = std.log.scoped(.font_shaper);

/// Shaper that uses CoreText.
///
/// CoreText shaping differs in subtle ways from HarfBuzz so it may result
/// in inconsistent rendering across platforms. But it also fixes many
... (2650 lines truncated)
</file>

<file path="src/font/shaper/feature.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const compat_reader = @import("../../lib/compat/reader.zig");

const log = std.log.scoped(.font_shaper);

/// Represents an OpenType font feature setting, which consists of a tag and
/// a numeric parameter >= 0. Most features are boolean, so only parameters
/// of 0 and 1 make sense for them, but some (e.g. 'cv01'..'cv99') can take
/// parameters to choose between multiple variants of a given character or
/// characters.
///
/// Ref:
/// - https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2#features-and-lookups
/// - https://harfbuzz.github.io/shaping-opentype-features.html
pub const Feature = struct {
    tag: [4]u8,
    value: u32,

    pub fn fromString(str: []const u8) ?Feature {
        var reader: std.Io.Reader = .fixed(str);
        return .fromReader(&reader);
    }

    /// Parse a single font feature setting from a std.io.Reader, with a version
    /// of the syntax of HarfBuzz's font feature strings. Stops at end of stream
    /// or when a ',' is encountered.
    ///
    /// This parsing aims to be as error-tolerant as possible while avoiding any
... (324 lines truncated)
</file>

<file path="src/font/shaper/harfbuzz.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const harfbuzz = @import("harfbuzz");
const font = @import("../main.zig");
const terminal = @import("../../terminal/main.zig");
const unicode = @import("../../unicode/main.zig");
const Feature = font.shape.Feature;
const FeatureList = font.shape.FeatureList;
const default_features = font.shape.default_features;
const Face = font.Face;
const Collection = font.Collection;
const DeferredFace = font.DeferredFace;
const Library = font.Library;
const SharedGrid = font.SharedGrid;
const Style = font.Style;
const Presentation = font.Presentation;
const global = @import("../../global.zig");

const log = std.log.scoped(.font_shaper);

/// Shaper that uses Harfbuzz.
pub const Shaper = struct {
    /// The allocated used for the feature list, cell buf, and codepoints.
    alloc: Allocator,

    /// The buffer used for text shaping. We reuse it across multiple shaping
    /// calls to prevent allocations.
    hb_buf: harfbuzz.Buffer,

... (2207 lines truncated)
</file>

<file path="src/font/shaper/noop.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const font = @import("../main.zig");
const Face = font.Face;
const Collection = font.Collection;
const DeferredFace = font.DeferredFace;
const Group = font.Group;
const GroupCache = font.GroupCache;
const Library = font.Library;
const SharedGrid = font.SharedGrid;
const Style = font.Style;
const Presentation = font.Presentation;
const terminal = @import("../../terminal/main.zig");

const log = std.log.scoped(.font_shaper);

/// Shaper that doesn't do any shaping. Each individual codepoint is mapped
/// directly to the detected text run font's glyph index.
pub const Shaper = struct {
    /// The allocated used for the feature list and cell buf.
    alloc: Allocator,

    /// The string used for shaping the current run.
    run_state: RunState,

    /// The shared memory used for shaping results.
    cell_buf: CellBuf,

    const CellBuf = std.ArrayListUnmanaged(font.shape.Cell);
    const CodepointList = std.ArrayListUnmanaged(Codepoint);
... (114 lines truncated)
</file>

<file path="src/font/shaper/run.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const font = @import("../main.zig");
const shape = @import("../shape.zig");
const terminal = @import("../../terminal/main.zig");
const autoHash = std.hash.autoHash;
const Hasher = std.hash.Wyhash;

/// A single text run. A text run is only valid for one Shaper instance and
/// until the next run is created. A text run never goes across multiple
/// rows in a terminal, so it is guaranteed to always be one line.
pub const TextRun = struct {
    /// A unique hash for this run. This can be used to cache the shaping
    /// results. We don't provide a means to compare actual values if the
    /// hash is the same, so we should continue to improve this hash to
    /// lower the chance of hash collisions if they become a problem. If
    /// there are hash collisions, it would result in rendering issues but
    /// the core data would be correct.
    ///
    /// The hash is position-independent within the row by using relative
    /// cluster positions. This allows identical runs in different positions
    /// to share the same cache entry, improving cache efficiency.
    hash: u64,

    /// The offset in the row where this run started. This is added to the
    /// X position of the final shaped cells to get the absolute position
    /// in the row where they belong.
    offset: u16,

... (367 lines truncated)
</file>

<file path="src/font/shaper/web_canvas.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const font = @import("../main.zig");
const terminal = @import("../../terminal/main.zig");
const unicode = @import("../../unicode/main.zig");
const uucode = @import("uucode");

const log = std.log.scoped(.font_shaper);

pub const Shaper = struct {
    const RunBuf = std.MultiArrayList(struct {
        /// The codepoint for this cell. This must be used in conjunction
        /// with cluster to find the total set of codepoints for a given
        /// cell. See cluster for more information.
        codepoint: u32,

        /// Cluster is set to the X value of the cell that this codepoint
        /// is part of. Note that a cell can have multiple codepoints
        /// with zero-width joiners (ZWJ) and such. Note that terminals
        /// do NOT handle full extended grapheme clustering well so it
        /// is possible a single grapheme extends multiple clusters.
        /// For example, skin tone emoji thumbs up may show up as two
        /// clusters: one with thumbs up and the ZWJ, and a second
        /// cluster with the tone block. It is up to the shaper to handle
        /// shaping these together into a single glyph, if it wishes.
        cluster: u32,
    });

    /// The allocator used for run_buf.
... (276 lines truncated)
</file>

<file path="src/font/sprite/draw/block.zig">
//! Block Elements | U+2580...U+259F
//! https://en.wikipedia.org/wiki/Block_Elements
//!
//! ▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏
//! ▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟
//!

const std = @import("std");
const Allocator = std.mem.Allocator;

const common = @import("common.zig");
const Shade = common.Shade;
const Quads = common.Quads;
const Alignment = common.Alignment;
const fill = common.fill;

const font = @import("../../main.zig");

// Utility names for common fractions
const one_eighth: f64 = 0.125;
const one_quarter: f64 = 0.25;
const one_third: f64 = (1.0 / 3.0);
const three_eighths: f64 = 0.375;
const half: f64 = 0.5;
const five_eighths: f64 = 0.625;
const two_thirds: f64 = (2.0 / 3.0);
const three_quarters: f64 = 0.75;
const seven_eighths: f64 = 0.875;

pub fn draw2580_259F(
... (148 lines truncated)
</file>

<file path="src/font/sprite/draw/box.zig">
//! Box Drawing | U+2500...U+257F
//! https://en.wikipedia.org/wiki/Box_Drawing
//!
//! ─━│┃┄┅┆┇┈┉┊┋┌┍┎┏
//! ┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟
//! ┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯
//! ┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿
//! ╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏
//! ═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟
//! ╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯
//! ╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿
//!

const std = @import("std");
const assert = @import("../../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;

const common = @import("common.zig");
const Thickness = common.Thickness;
const Shade = common.Shade;
const Quads = common.Quads;
const Corner = common.Corner;
const Edge = common.Edge;
const Alignment = common.Alignment;
const hline = common.hline;
const vline = common.vline;
const hlineMiddle = common.hlineMiddle;
const vlineMiddle = common.vlineMiddle;

const font = @import("../../main.zig");
... (900 lines truncated)
</file>

<file path="src/font/sprite/draw/braille.zig">
//! Braille Patterns | U+2800...U+28FF
//! https://en.wikipedia.org/wiki/Braille_Patterns
//!
//! (6 dot patterns)
//! ⠀ ⠁ ⠂ ⠃ ⠄ ⠅ ⠆ ⠇ ⠈ ⠉ ⠊ ⠋ ⠌ ⠍ ⠎ ⠏
//! ⠐ ⠑ ⠒ ⠓ ⠔ ⠕ ⠖ ⠗ ⠘ ⠙ ⠚ ⠛ ⠜ ⠝ ⠞ ⠟
//! ⠠ ⠡ ⠢ ⠣ ⠤ ⠥ ⠦ ⠧ ⠨ ⠩ ⠪ ⠫ ⠬ ⠭ ⠮ ⠯
//! ⠰ ⠱ ⠲ ⠳ ⠴ ⠵ ⠶ ⠷ ⠸ ⠹ ⠺ ⠻ ⠼ ⠽ ⠾ ⠿
//!
//! (8 dot patterns)
//! ⡀ ⡁ ⡂ ⡃ ⡄ ⡅ ⡆ ⡇ ⡈ ⡉ ⡊ ⡋ ⡌ ⡍ ⡎ ⡏
//! ⡐ ⡑ ⡒ ⡓ ⡔ ⡕ ⡖ ⡗ ⡘ ⡙ ⡚ ⡛ ⡜ ⡝ ⡞ ⡟
//! ⡠ ⡡ ⡢ ⡣ ⡤ ⡥ ⡦ ⡧ ⡨ ⡩ ⡪ ⡫ ⡬ ⡭ ⡮ ⡯
//! ⡰ ⡱ ⡲ ⡳ ⡴ ⡵ ⡶ ⡷ ⡸ ⡹ ⡺ ⡻ ⡼ ⡽ ⡾ ⡿
//! ⢀ ⢁ ⢂ ⢃ ⢄ ⢅ ⢆ ⢇ ⢈ ⢉ ⢊ ⢋ ⢌ ⢍ ⢎ ⢏
//! ⢐ ⢑ ⢒ ⢓ ⢔ ⢕ ⢖ ⢗ ⢘ ⢙ ⢚ ⢛ ⢜ ⢝ ⢞ ⢟
//! ⢠ ⢡ ⢢ ⢣ ⢤ ⢥ ⢦ ⢧ ⢨ ⢩ ⢪ ⢫ ⢬ ⢭ ⢮ ⢯
//! ⢰ ⢱ ⢲ ⢳ ⢴ ⢵ ⢶ ⢷ ⢸ ⢹ ⢺ ⢻ ⢼ ⢽ ⢾ ⢿
//! ⣀ ⣁ ⣂ ⣃ ⣄ ⣅ ⣆ ⣇ ⣈ ⣉ ⣊ ⣋ ⣌ ⣍ ⣎ ⣏
//! ⣐ ⣑ ⣒ ⣓ ⣔ ⣕ ⣖ ⣗ ⣘ ⣙ ⣚ ⣛ ⣜ ⣝ ⣞ ⣟
//! ⣠ ⣡ ⣢ ⣣ ⣤ ⣥ ⣦ ⣧ ⣨ ⣩ ⣪ ⣫ ⣬ ⣭ ⣮ ⣯
//! ⣰ ⣱ ⣲ ⣳ ⣴ ⣵ ⣶ ⣷ ⣸ ⣹ ⣺ ⣻ ⣼ ⣽ ⣾ ⣿
//!

const std = @import("std");
const assert = @import("../../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;

const font = @import("../../main.zig");

... (119 lines truncated)
</file>

<file path="src/font/sprite/draw/branch.zig">
//! Branch Drawing Characters | U+F5D0...U+F60D
//!
//! Branch drawing character set, used for drawing git-like
//! graphs in the terminal. Originally implemented in Kitty.
//! Ref:
//! - https://github.com/kovidgoyal/kitty/pull/7681
//! - https://github.com/kovidgoyal/kitty/pull/7805
//! NOTE: Kitty is GPL licensed, and its code was not referenced
//!       for these characters, only the loose specification of
//!       the character set in the pull request descriptions.
//!
//!                
//!                
//!                
//!              
//!

const std = @import("std");
const Allocator = std.mem.Allocator;

const common = @import("common.zig");
const Thickness = common.Thickness;
const Shade = common.Shade;
const Edge = common.Edge;
const hlineMiddle = common.hlineMiddle;
const vlineMiddle = common.vlineMiddle;

const arc = @import("box.zig").arc;

const font = @import("../../main.zig");
... (475 lines truncated)
</file>

<file path="src/font/sprite/draw/common.zig">
//! This file contains a set of useful helper functions
//! and types for drawing our sprite font glyphs. These
//! are generally applicable to multiple sets of glyphs
//! rather than being single-use.

const std = @import("std");
const Allocator = std.mem.Allocator;

const font = @import("../../main.zig");

const log = std.log.scoped(.sprite_font);

// Utility names for common fractions
pub const one_eighth: f64 = 0.125;
pub const one_quarter: f64 = 0.25;
pub const one_third: f64 = (1.0 / 3.0);
pub const three_eighths: f64 = 0.375;
pub const half: f64 = 0.5;
pub const five_eighths: f64 = 0.625;
pub const two_thirds: f64 = (2.0 / 3.0);
pub const three_quarters: f64 = 0.75;
pub const seven_eighths: f64 = 0.875;

/// The thickness of a line.
pub const Thickness = enum {
    super_light,
    light,
    heavy,

    /// Calculate the real height of a line based on its
... (345 lines truncated)
</file>

<file path="src/font/sprite/draw/geometric_shapes.zig">
//! Geometric Shapes | U+25A0...U+25FF
//! https://en.wikipedia.org/wiki/Geometric_Shapes_(Unicode_block)
//!
//! ■ □ ▢ ▣ ▤ ▥ ▦ ▧ ▨ ▩ ▪ ▫ ▬ ▭ ▮ ▯
//! ▰ ▱ ▲ △ ▴ ▵ ▶ ▷ ▸ ▹ ► ▻ ▼ ▽ ▾ ▿
//! ◀ ◁ ◂ ◃ ◄ ◅ ◆ ◇ ◈ ◉ ◊ ○ ◌ ◍ ◎ ●
//! ◐ ◑ ◒ ◓ ◔ ◕ ◖ ◗ ◘ ◙ ◚ ◛ ◜ ◝ ◞ ◟
//! ◠ ◡ ◢ ◣ ◤ ◥ ◦ ◧ ◨ ◩ ◪ ◫ ◬ ◭ ◮ ◯
//! ◰ ◱ ◲ ◳ ◴ ◵ ◶ ◷ ◸ ◹ ◺ ◻ ◼ ◽︎◾︎◿
//!
//! Only a subset of this block is viable for sprite drawing; filling
//! out this file to have full coverage of this block is not the goal.
//!

const std = @import("std");
const Allocator = std.mem.Allocator;

const common = @import("common.zig");
const Thickness = common.Thickness;
const Corner = common.Corner;
const Shade = common.Shade;

const font = @import("../../main.zig");

/// ◢ ◣ ◤ ◥
pub fn draw25E2_25E5(
    cp: u32,
    canvas: *font.sprite.Canvas,
    width: u32,
    height: u32,
... (169 lines truncated)
</file>

<file path="src/font/sprite/draw/octants.txt">
# This is the list of all the octants for the Symbols for Legacy
# Computing block. It is used at comptime to generate the lookup
# table for drawing them since we weren't able to discern a
# mathematical pattern for them.
BLOCK OCTANT-3
BLOCK OCTANT-23
BLOCK OCTANT-123
BLOCK OCTANT-4
BLOCK OCTANT-14
BLOCK OCTANT-124
BLOCK OCTANT-34
BLOCK OCTANT-134
BLOCK OCTANT-234
BLOCK OCTANT-5
BLOCK OCTANT-15
BLOCK OCTANT-25
BLOCK OCTANT-125
BLOCK OCTANT-135
BLOCK OCTANT-235
BLOCK OCTANT-1235
BLOCK OCTANT-45
BLOCK OCTANT-145
BLOCK OCTANT-245
BLOCK OCTANT-1245
BLOCK OCTANT-345
BLOCK OCTANT-1345
BLOCK OCTANT-2345
BLOCK OCTANT-12345
BLOCK OCTANT-6
BLOCK OCTANT-16
... (205 lines truncated)
</file>

<file path="src/font/sprite/draw/powerline.zig">
//! Powerline + Powerline Extra Symbols | U+E0B0...U+E0D4
//! https://github.com/ryanoasis/powerline-extra-symbols
//!
//!                
//!                  
//!      
//!
//! We implement the more geometric glyphs here, but not the stylized ones.
//!

const std = @import("std");
const Allocator = std.mem.Allocator;

const common = @import("common.zig");
const Thickness = common.Thickness;
const Shade = common.Shade;

const box = @import("box.zig");

const font = @import("../../main.zig");
const Quad = font.sprite.Canvas.Quad;

/// 
pub fn drawE0B0(
    cp: u32,
    canvas: *font.sprite.Canvas,
    width: u32,
    height: u32,
    metrics: font.Metrics,
) !void {
... (371 lines truncated)
</file>

<file path="src/font/sprite/draw/README.md">
# This is a _special_ directory.

The files in this directory are imported by `../Face.zig` and scanned for pub
functions with names matching a specific format, which are then used to handle
drawing specified codepoints.

## IMPORTANT

When you add a new file here, you need to add the corresponding import in
`../Face.zig` for its draw functions to be picked up. I tried dynamically
listing these files to do this automatically but it was more pain than it
was worth.

## `draw*` functions

Any function named `draw<CODEPOINT>` or `draw<MIN>_<MAX>` will be used to
draw the codepoint or range of codepoints specified in the name. These are
hex-encoded values with upper case letters.

`draw*` functions are provided with these arguments:

```zig
/// The codepoint being drawn. For single-codepoint draw functions this can
/// just be discarded, but it's needed for range draw functions to determine
/// which value in the range needs to be drawn.
cp: u32,
/// The canvas on which to draw the codepoint.
////
/// This canvas has been prepared with an extra quarter of the width/height on
/// each edge, and its transform has been set so that [0, 0] is still the upper
... (26 lines truncated)
</file>

<file path="src/font/sprite/draw/special.zig">
//! This file contains glyph drawing functions for all of the
//! non-Unicode sprite glyphs, such as cursors and underlines.
//!
//! The naming convention in this file differs from the usual
//! because the draw functions for special sprites are found by
//! having names that exactly match the enum fields in Sprite.

const std = @import("std");
const Allocator = std.mem.Allocator;
const font = @import("../../main.zig");
const Sprite = font.sprite.Sprite;

pub fn underline(
    cp: u32,
    canvas: *font.sprite.Canvas,
    width: u32,
    height: u32,
    metrics: font.Metrics,
) !void {
    _ = cp;

    // We can go beyond the height of the cell a bit, but
    // we want to be sure never to exceed the height of the
    // canvas, which extends a quarter cell below the cell
    // height.
    const y = @min(
        metrics.underline_position,
        height +| canvas.padding_y -| metrics.underline_thickness,
    );

... (343 lines truncated)
</file>

<file path="src/font/sprite/draw/symbols_for_legacy_computing_supplement.zig">
//! Symbols for Legacy Computing Supplement | U+1CC00...U+1CEBF
//! https://en.wikipedia.org/wiki/Symbols_for_Legacy_Computing_Supplement
//!
//! 𜰀 𜰁 𜰂 𜰃 𜰄 𜰅 𜰆 𜰇 𜰈 𜰉 𜰊 𜰋 𜰌 𜰍 𜰎 𜰏
//! 𜰐 𜰑 𜰒 𜰓 𜰔 𜰕 𜰖 𜰗 𜰘 𜰙 𜰚 𜰛 𜰜 𜰝 𜰞 𜰟
//! 𜰠 𜰡 𜰢 𜰣 𜰤 𜰥 𜰦 𜰧 𜰨 𜰩 𜰪 𜰫 𜰬 𜰭 𜰮 𜰯
//! 𜰰 𜰱 𜰲 𜰳 𜰴 𜰵 𜰶 𜰷 𜰸 𜰹 𜰺 𜰻 𜰼 𜰽 𜰾 𜰿
//! 𜱀 𜱁 𜱂 𜱃 𜱄 𜱅 𜱆 𜱇 𜱈 𜱉 𜱊 𜱋 𜱌 𜱍 𜱎 𜱏
//! 𜱐 𜱑 𜱒 𜱓 𜱔 𜱕 𜱖 𜱗 𜱘 𜱙 𜱚 𜱛 𜱜 𜱝 𜱞 𜱟
//! 𜱠 𜱡 𜱢 𜱣 𜱤 𜱥 𜱦 𜱧 𜱨 𜱩 𜱪 𜱫 𜱬 𜱭 𜱮 𜱯
//! 𜱰 𜱱 𜱲 𜱳 𜱴 𜱵 𜱶 𜱷 𜱸 𜱹 𜱺 𜱻 𜱼 𜱽 𜱾 𜱿
//! 𜲀 𜲁 𜲂 𜲃 𜲄 𜲅 𜲆 𜲇 𜲈 𜲉 𜲊 𜲋 𜲌 𜲍 𜲎 𜲏
//! 𜲐 𜲑 𜲒 𜲓 𜲔 𜲕 𜲖 𜲗 𜲘 𜲙 𜲚 𜲛 𜲜 𜲝 𜲞 𜲟
//! 𜲠 𜲡 𜲢 𜲣 𜲤 𜲥 𜲦 𜲧 𜲨 𜲩 𜲪 𜲫 𜲬 𜲭 𜲮 𜲯
//! 𜲰 𜲱 𜲲 𜲳 𜲴 𜲵 𜲶 𜲷 𜲸 𜲹 𜲺 𜲻 𜲼 𜲽 𜲾 𜲿
//! 𜳀 𜳁 𜳂 𜳃 𜳄 𜳅 𜳆 𜳇 𜳈 𜳉 𜳊 𜳋 𜳌 𜳍 𜳎 𜳏
//! 𜳐 𜳑 𜳒 𜳓 𜳔 𜳕 𜳖 𜳗 𜳘 𜳙 𜳚 𜳛 𜳜 𜳝 𜳞 𜳟
//! 𜳠 𜳡 𜳢 𜳣 𜳤 𜳥 𜳦 𜳧 𜳨 𜳩 𜳪 𜳫 𜳬 𜳭 𜳮 𜳯
//! 𜳰 𜳱 𜳲 𜳳 𜳴 𜳵 𜳶 𜳷 𜳸 𜳹
//! 𜴀 𜴁 𜴂 𜴃 𜴄 𜴅 𜴆 𜴇 𜴈 𜴉 𜴊 𜴋 𜴌 𜴍 𜴎 𜴏
//! 𜴐 𜴑 𜴒 𜴓 𜴔 𜴕 𜴖 𜴗 𜴘 𜴙 𜴚 𜴛 𜴜 𜴝 𜴞 𜴟
//! 𜴠 𜴡 𜴢 𜴣 𜴤 𜴥 𜴦 𜴧 𜴨 𜴩 𜴪 𜴫 𜴬 𜴭 𜴮 𜴯
//! 𜴰 𜴱 𜴲 𜴳 𜴴 𜴵 𜴶 𜴷 𜴸 𜴹 𜴺 𜴻 𜴼 𜴽 𜴾 𜴿
//! 𜵀 𜵁 𜵂 𜵃 𜵄 𜵅 𜵆 𜵇 𜵈 𜵉 𜵊 𜵋 𜵌 𜵍 𜵎 𜵏
//! 𜵐 𜵑 𜵒 𜵓 𜵔 𜵕 𜵖 𜵗 𜵘 𜵙 𜵚 𜵛 𜵜 𜵝 𜵞 𜵟
//! 𜵠 𜵡 𜵢 𜵣 𜵤 𜵥 𜵦 𜵧 𜵨 𜵩 𜵪 𜵫 𜵬 𜵭 𜵮 𜵯
//! 𜵰 𜵱 𜵲 𜵳 𜵴 𜵵 𜵶 𜵷 𜵸 𜵹 𜵺 𜵻 𜵼 𜵽 𜵾 𜵿
//! 𜶀 𜶁 𜶂 𜶃 𜶄 𜶅 𜶆 𜶇 𜶈 𜶉 𜶊 𜶋 𜶌 𜶍 𜶎 𜶏
//! 𜶐 𜶑 𜶒 𜶓 𜶔 𜶕 𜶖 𜶗 𜶘 𜶙 𜶚 𜶛 𜶜 𜶝 𜶞 𜶟
//! 𜶠 𜶡 𜶢 𜶣 𜶤 𜶥 𜶦 𜶧 𜶨 𜶩 𜶪 𜶫 𜶬 𜶭 𜶮 𜶯
... (604 lines truncated)
</file>

<file path="src/font/sprite/draw/symbols_for_legacy_computing.zig">
//! Symbols for Legacy Computing | U+1FB00...U+1FBFF
//! https://en.wikipedia.org/wiki/Symbols_for_Legacy_Computing
//!
//! 🬀 🬁 🬂 🬃 🬄 🬅 🬆 🬇 🬈 🬉 🬊 🬋 🬌 🬍 🬎 🬏
//! 🬐 🬑 🬒 🬓 🬔 🬕 🬖 🬗 🬘 🬙 🬚 🬛 🬜 🬝 🬞 🬟
//! 🬠 🬡 🬢 🬣 🬤 🬥 🬦 🬧 🬨 🬩 🬪 🬫 🬬 🬭 🬮 🬯
//! 🬰 🬱 🬲 🬳 🬴 🬵 🬶 🬷 🬸 🬹 🬺 🬻 🬼 🬽 🬾 🬿
//! 🭀 🭁 🭂 🭃 🭄 🭅 🭆 🭇 🭈 🭉 🭊 🭋 🭌 🭍 🭎 🭏
//! 🭐 🭑 🭒 🭓 🭔 🭕 🭖 🭗 🭘 🭙 🭚 🭛 🭜 🭝 🭞 🭟
//! 🭠 🭡 🭢 🭣 🭤 🭥 🭦 🭧 🭨 🭩 🭪 🭫 🭬 🭭 🭮 🭯
//! 🭰 🭱 🭲 🭳 🭴 🭵 🭶 🭷 🭸 🭹 🭺 🭻 🭼 🭽 🭾 🭿
//! 🮀 🮁 🮂 🮃 🮄 🮅 🮆 🮇 🮈 🮉 🮊 🮋 🮌 🮍 🮎 🮏
//! 🮐 🮑 🮒   🮔 🮕 🮖 🮗 🮘 🮙 🮚 🮛 🮜 🮝 🮞 🮟
//! 🮠 🮡 🮢 🮣 🮤 🮥 🮦 🮧 🮨 🮩 🮪 🮫 🮬 🮭 🮮 🮯
//! 🮰 🮱 🮲 🮳 🮴 🮵 🮶 🮷 🮸 🮹 🮺 🮻 🮼 🮽 🮾 🮿
//! 🯀 🯁 🯂 🯃 🯄 🯅 🯆 🯇 🯈 🯉 🯊 🯋 🯌 🯍 🯎 🯏
//! 🯐 🯑 🯒 🯓 🯔 🯕 🯖 🯗 🯘 🯙 🯚 🯛 🯜 🯝 🯞 🯟
//! 🯠 🯡 🯢 🯣 🯤 🯥 🯦 🯧 🯨 🯩 🯪 🯫 🯬 🯭 🯮 🯯
//! 🯰 🯱 🯲 🯳 🯴 🯵 🯶 🯷 🯸 🯹
//!

const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../../../quirks.zig").inlineAssert;

const common = @import("common.zig");
const Thickness = common.Thickness;
const Alignment = common.Alignment;
const Fraction = common.Fraction;
const Corner = common.Corner;
... (1384 lines truncated)
</file>

<file path="src/font/sprite/canvas.zig">
//! This exposes primitives to draw 2D graphics and export the graphic to
//! a font atlas.
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const z2d = @import("z2d");
const font = @import("../main.zig");
const global = @import("../../global.zig");

pub fn Point(comptime T: type) type {
    return struct {
        x: T,
        y: T,
    };
}

pub fn Line(comptime T: type) type {
    return struct {
        p0: Point(T),
        p1: Point(T),
    };
}

pub fn Box(comptime T: type) type {
    return struct {
        p0: Point(T),
        p1: Point(T),

        pub fn rect(self: Box(T)) Rect(T) {
            const tl_x = @min(self.p0.x, self.p1.x);
... (416 lines truncated)
</file>

<file path="src/font/sprite/Face.zig">
//! This implements the built-in "sprite face". This font renders
//! the built-in glyphs for the terminal, such as box drawing fonts, as well
//! as specific sprites that are part of our rendering model such as
//! text decorations (underlines).
//!
//! This isn't really a "font face" so much as it is quacks like a font
//! face with regards to how it works with font.Group. We don't use any
//! dynamic dispatch so it isn't truly an interface but the functions
//! and behaviors are close enough to a system face that it makes it easy
//! to integrate with font.Group. This is desirable so that higher level
//! processes such as GroupCache, Shaper, etc. don't need to be aware of
//! special sprite handling and just treat it like a normal font face.
const Face = @This();

const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const wuffs = @import("wuffs");
const z2d = @import("z2d");
const font = @import("../main.zig");
const Sprite = font.sprite.Sprite;

const special = @import("draw/special.zig");

const log = std.log.scoped(.font_sprite);

/// Grid metrics for rendering sprites.
metrics: font.Metrics,

pub const DrawFnError =
... (639 lines truncated)
</file>

<file path="src/font/Atlas.zig">
//! Implements a texture atlas (https://en.wikipedia.org/wiki/Texture_atlas).
//!
//! The implementation is based on "A Thousand Ways to Pack the Bin - A
//! Practical Approach to Two-Dimensional Rectangle Bin Packing" by Jukka
//! Jylänki. This specific implementation is based heavily on
//! Nicolas P. Rougier's freetype-gl project as well as Jukka's C++
//! implementation: https://github.com/juj/RectangleBinPack
//!
//! Limitations that are easy to fix, but I didn't need them:
//!
//!   * Written data must be packed, no support for custom strides.
//!   * Texture is always a square, no ability to set width != height. Note
//!     that regions written INTO the atlas do not have to be square, only
//!     the full atlas texture itself.
//!
const Atlas = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const testing = std.testing;
const fastmem = @import("../fastmem.zig");
const tripwire = @import("../tripwire.zig");

const log = std.log.scoped(.atlas);

/// Data is the raw texture data.
data: []u8,

/// Width and height of the atlas texture. The current implementation is
... (860 lines truncated)
</file>

<file path="src/font/backend.zig">
const std = @import("std");

pub const Backend = enum {
    const WasmTarget = @import("../os/wasm/target.zig").Target;

    /// FreeType for font rendering with no font discovery enabled.
    freetype,

    /// FreeType for font rendering with a built-in Windows font directory
    /// scanner (C:\Windows\Fonts + %LOCALAPPDATA%\Microsoft\Windows\Fonts).
    /// Used when DirectWrite is not available; matches by family_name and
    /// SFNT name table without any external index.
    freetype_windows,

    /// Fontconfig for font discovery and FreeType for font rendering.
    fontconfig_freetype,

    /// CoreText for font discovery, rendering, and shaping (macOS).
    coretext,

    /// CoreText for font discovery, FreeType for rendering, and
    /// HarfBuzz for shaping (macOS).
    coretext_freetype,

    /// CoreText for font discovery and rendering, HarfBuzz for shaping
    coretext_harfbuzz,

    /// CoreText for font discovery and rendering, no shaping.
    coretext_noshape,

... (99 lines truncated)
</file>

<file path="src/font/CodepointMap.zig">
/// CodepointMap is a map of codepoints to a discovery descriptor of a font
/// to use for that codepoint. If the descriptor doesn't return any matching
/// font, the codepoint is rendered using the default font.
const CodepointMap = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const discovery = @import("discovery.zig");

pub const Entry = struct {
    /// Unicode codepoint range. Asserts range[0] <= range[1].
    range: [2]u21,

    /// The discovery descriptor of the font to use for this range.
    descriptor: discovery.Descriptor,
};

/// The list of entries. We use a multiarraylist because Descriptors are
/// quite large and we will very rarely match, so we'd rather pack our
/// ranges together to make everything more cache friendly for lookups.
///
/// Note: we just do a linear search because we expect to always have very
/// few entries, so the overhead of a binary search is not worth it. This is
/// possible to defeat with some pathological inputs, but there is no realistic
/// scenario where this will be a problem except people trying to fuck around.
list: std.MultiArrayList(Entry) = .{},

pub fn deinit(self: *CodepointMap, alloc: Allocator) void {
    self.list.deinit(alloc);
... (96 lines truncated)
</file>

<file path="src/font/CodepointResolver.zig">
//! CodepointResolver maps a codepoint to a font. It is more dynamic
//! than "Collection" since it supports mapping codepoint ranges to
//! specific fonts, searching for fallback fonts, and more.
//!
//! To initialize the codepoint resolver, manually initialize using
//! Zig initialization syntax: .{}-style. Set the fields you want set,
//! and begin using the resolver.
//!
//! Deinit must still be called on the resolver to free any memory
//! allocated during use. All functions that take allocators should use
//! the same allocator.
const CodepointResolver = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const uucode = @import("uucode");
const font = @import("main.zig");
const Atlas = font.Atlas;
const CodepointMap = font.CodepointMap;
const Collection = font.Collection;
const Discover = font.Discover;
const DiscoveryDescriptor = font.discovery.Descriptor;
const Face = font.Face;
const Glyph = font.Glyph;
const Library = font.Library;
const Presentation = font.Presentation;
const RenderOptions = font.Glyph.RenderOptions;
const SpriteFace = font.SpriteFace;
const Style = font.Style;

... (533 lines truncated)
</file>

<file path="src/font/Collection.zig">
//! A font collection is a list of faces of different styles. The list is
//! ordered by priority (per style). All fonts in a collection share the same
//! size so they can be used interchangeably in cases a glyph is missing in one
//! and present in another.
//!
//! The purpose of a collection is to store a list of fonts by style
//! and priority order. A collection does not handle searching for font
//! callbacks, rasterization, etc. For this, see CodepointResolver.
//!
//! The collection can contain both loaded and deferred faces. Deferred faces
//! typically use less memory while still providing some necessary information
//! such as codepoint support, presentation, etc. This is useful for looking
//! for fallback fonts as efficiently as possible. For example, when the glyph
//! "X" is not found, we can quickly search through deferred fonts rather
//! than loading the font completely.
const Collection = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const config = @import("../config.zig");
const comparison = @import("../datastruct/comparison.zig");
const font = @import("main.zig");
const options = font.options;
const DeferredFace = font.DeferredFace;
const DesiredSize = font.face.DesiredSize;
const Face = font.Face;
const Library = font.Library;
const Metrics = font.Metrics;
const Presentation = font.Presentation;
const Style = font.Style;
... (1495 lines truncated)
</file>

<file path="src/font/DeferredFace.zig">
//! A deferred face represents a single font face with all the information
//! necessary to load it, but defers loading the full face until it is
//! needed.
//!
//! This allows us to have many fallback fonts to look for glyphs, but
//! only load them if they're really needed.
const DeferredFace = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const fontconfig = @import("fontconfig");
const macos = @import("macos");
const font = @import("main.zig");
const options = @import("main.zig").options;
const Library = @import("main.zig").Library;
const Face = @import("main.zig").Face;
const Presentation = @import("main.zig").Presentation;

const log = std.log.scoped(.deferred_face);

/// Fontconfig
fc: if (options.backend == .fontconfig_freetype) ?Fontconfig else void =
    if (options.backend == .fontconfig_freetype) null else {},

/// CoreText
ct: if (font.Discover == font.discovery.CoreText) ?CoreText else void =
    if (font.Discover == font.discovery.CoreText) null else {},

/// Windows (FreeType directory scan)
win: if (options.backend == .freetype_windows) ?Windows else void =
... (502 lines truncated)
</file>

<file path="src/font/discovery.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const assert = @import("../quirks.zig").inlineAssert;
const fontconfig = @import("fontconfig");
const macos = @import("macos");
const opentype = @import("opentype.zig");
const options = @import("main.zig").options;
const Collection = @import("main.zig").Collection;
const DeferredFace = @import("main.zig").DeferredFace;
const Face = @import("main.zig").Face;
const Library = @import("main.zig").Library;
const Presentation = @import("main.zig").Presentation;
const Variation = @import("main.zig").face.Variation;
const global = @import("../global.zig");

const log = std.log.scoped(.discovery);

/// Discover implementation for the compile options.
pub const Discover = switch (options.backend) {
    .freetype => void, // no discovery
    .freetype_windows => Windows,
    .fontconfig_freetype => Fontconfig,
    .web_canvas => void, // no discovery
    .coretext,
    .coretext_freetype,
    .coretext_harfbuzz,
    .coretext_noshape,
    => CoreText,
};
... (1387 lines truncated)
</file>

<file path="src/font/embedded.zig">
//! Fonts that can be embedded with Ghostty. Note they are only actually
//! embedded in the binary if they are referenced by the code, so fonts
//! used for tests will not result in the final binary being larger.
//!
//! Be careful to ensure that any fonts you embed are licensed for
//! redistribution and include their license as necessary.

/// Default fonts that we prefer for Ghostty.
pub const variable = @embedFile("jetbrains_mono_variable");
pub const variable_italic = @embedFile("jetbrains_mono_variable_italic");

/// Symbols-only nerd font.
pub const symbols_nerd_font = @embedFile("nerd_fonts_symbols_only");

/// Static jetbrains mono faces, currently unused.
pub const regular = @embedFile("jetbrains_mono_regular");
pub const bold = @embedFile("jetbrains_mono_bold");
pub const italic = @embedFile("jetbrains_mono_italic");
pub const bold_italic = @embedFile("jetbrains_mono_bold_italic");

/// Emoji fonts
pub const emoji = @embedFile("res/NotoColorEmoji.ttf");
pub const emoji_text = @embedFile("res/NotoEmoji-Regular.ttf");

// Fonts below are ONLY used for testing.

/// Fonts with general properties
pub const arabic = @embedFile("res/KawkabMono-Regular.ttf");

/// A font for testing which is patched with nerd font symbols.
... (26 lines truncated)
</file>

<file path="src/font/face.zig">
const std = @import("std");
const builtin = @import("builtin");
const build_config = @import("../build_config.zig");
const options = @import("main.zig").options;
const config = @import("../config.zig");
const freetype = @import("face/freetype.zig");
const coretext = @import("face/coretext.zig");
pub const web_canvas = @import("face/web_canvas.zig");

/// Face implementation for the compile options.
pub const Face = switch (options.backend) {
    .freetype,
    .freetype_windows,
    .fontconfig_freetype,
    .coretext_freetype,
    => freetype.Face,

    .coretext,
    .coretext_harfbuzz,
    .coretext_noshape,
    => coretext.Face,

    .web_canvas => web_canvas.Face,
};

/// If a DPI can't be calculated, this DPI is used. This is probably
/// wrong on modern devices so it is highly recommended you get the DPI
/// using whatever platform method you can.
pub const default_dpi = if (builtin.os.tag == .macos) 72 else 96;

... (83 lines truncated)
</file>

<file path="src/font/glyf_rasterize_png_test.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const wuffs = @import("wuffs");
const z2d = @import("z2d");
const compat_file = @import("../lib/compat/file.zig");

const glyf_rasterize = @import("glyf_rasterize.zig");
const glyf = @import("opentype/glyf.zig");

const log = std.log.scoped(.glyf_rasterize);

const test_glyf_payloads = [_][]const u8{
    // Nerd Font branch, folder, home, heart, and Rust cog outlines from:
    // https://github.com/raphamorim/glyph-protocol-examples/blob/main/bubbletea/main.go
    "AAIARv8zAhIDnQAZAB0AABcjNTQ3Njc3Njc2NTUjNxcjFRQGBwcGBwYVEQcRM82HJxs3SyoUE2aPjmY0NCUvDxSHh83rVzgoIzAbKSZAoaenvF5kIhkfHSM9AVdXAn8=",
    "AAEAAP/UA5wC/AAVAAAXIiY1ETQ2MzMyFxcWMyEyFgcRFgYjcy9ERC/nOCQjER0BITBEAQFEMCxELwJBMEQvLhdEL/4yL0Q=",
    "AAEAAP+aBBEDNgA+AAABFAYjIxMUBxUUBisFIiY9AjQmIyMiBh0CFAYrAiIiJwYiIyMiJjc1MjQ1NSMiJjQ3ATYzMhcBFgQOJBY5AQEqHh0GBzsrHioiGHMYIioeLDkBBAMBBAIcHiwBAToYIhIBzg4aFw8BzBcBahgi/t4KBB4eKioeLHQYIiIYdCweKgICKh7KBAJ+IDISAZQODP5qFA==",
    "AAEAAP/dA5sC+QAZAAATJjU1NDY3NhYXFzc2NhcWFhUVFAcBBiMiJ1ZWel09eCwWFSx4PV16Vv66FB0eFAEhUHULXpAQCiYsFhYsJgoQkF4LdVD+zxMT",
    "AAoAAP/YAyEC+AENARcBWgFlAW8BfQGIAbsBxAHNAAAAMhYXFhYyNjc2MzIXFhcWFxY3NjMyFhcWFxY3NjMyFxcHBxcWNzYXFgcGFxYzMhcWBw4CFAcUFQcUFxYWFRQGFhcWFgcGFBcWFxYGBwYUFxYGBw4CFhYXFgcGBwYVFBcWBwYjIgYXFgYnJgcGFxcHBiInJgYHBiMiJyYHBgcGBiMiJyYiBwYiJyYmBwYGJyYmJyYHBiImJyYmBwYiJjc3JyYHBicmNzYmIwYmNzY2Nzc0JyYmNTQ3NiYnJiY3NjQnJiY0Njc2NjQnJicmJjY3NjYnJjc3Mjc2NScmJyYnJjYXMjY1NCYmJyc3NhcWNzcnJjYzMhcWNjc2NjMyFxY3Njc2NjMyFxYyNzY3FyIHBhYzMjYnJgczBwYHBhUUMzIXFhYHBgcOAhUGFQciFhcWFxYXFhcWFjc2NzY3NjMzNzYvAiYnJjU0NzcnJicmJicnBwYGJyYnBwYGFxYyNzYmJyYFIgcGFBcWNicmBRcWBwYPAgYXFzM1NRcVMzY3NjU0JyYjBxUzMhcWFQcjIhUGFjMyNzYyFxYXFhUWFhcWNzY/AjY2Fxc2NjQjIiYnJicmJyYnJiMGIgcGFjMyNiclIgcGFjc2JyYBjQQICgcECAgIEQMJBgUCAwUGEBMDBgQEAwUDFBIFAwQEAQEEBRIZBQUGBQMCFxUFBwwBAgICARgSChoEFBcEExEUDwQECBATERMEGAoGCAQEBhEHAxUZCAsGAxcYBAUGChoVAgMBAQQEBhQSCgMECgQRFAUEBgcGBAUQEAgLDQwOCwoODQgFBg4CBRUPDAQEBAgTFAYIAQEEBREaBAYGBQQYGQYKAQQCARgSCg0NBBQXBBMQERIEBg4KCAIDCg0ECBEUBA0QBwQFEBcBAQICAgsIGRgCAgIBBAMFGhIFBAEBCAMFEhMIBAQEBgUREQQGCAcEBgQQDwoLCQQFCQcMDBARCg0HPgEPQjEfoJ8NJzACAykCBAQCAQEEAgIDGAgEAwggCg0BAQMCDBABAgIBHRsDBw4PAx8xFkQTCRQSEAkHEvoMDgcHGAgEBAcFAjAHBA0OFBQTBf3wBAsIAh0cAQMKBFOENjcIERsLLzEkJAECAXl5ARgBBBQZEAYEBQYBRCEnKiYSBgYGECAcARg/NhQLDgkLBQkQBimQEAQPChESCA4BVRAGCigLChEFAvgEEQsIBgkREA8FCAIBDA0KERYCAgkIBAQWFwIDBQYFBBkVAwIDBhkDBAQEAQEBAQcEAwQHBSQICAgMEREICwoFBggKDAgQEQwJBAQCCAgHGAYDAwQIAxAXBwMGFBkKBgQCAxYWBAQJCAQVHAwOAwQQEwYREBMVFBMCEA0GAgQmAgQPDAoSFgQJCQgXFgICBAYEBhgVBgEMFgQKAwMGBAQEBgQTEQgJCQwQEAgLCwQMBAkHBAoDAwkLDAgGCAgSFwcEAwQHAgIGBQQXDAEEBQEGCgQTBAcGBAICFxYICAkEFhEKDA0BARcSBBEPEw8ERQcKHiAKBScEESgaBAIDCjghJh4BBAIBAQEBBAECAhUjEQMJAgcIGBMBAQURFgcNDAMHCgYgIQY0IxAcBAETEwgDBBObARgMCwwIFAQEAgIIHAYKKAsDAwkYDQQNDRAjLg9eXgE4AQQHDhQHA4g0AgQqKwICGgUECAkVHAEHFAMDCAcKAx4iCgcGARwCBAwPJjAHDgQCwgMJIiIJAg0UFBIRDgQ=",
};

/// Return deterministic font metrics for the PNG reference test.
///
/// These are intentionally minimal: the rasterizer only needs cell geometry,
/// face geometry, and icon heights for constraint calculations.
fn testMetrics(width: u32, height: u32) @import("Metrics.zig") {
    return .{
        .cell_width = width,
        .cell_height = height,
        .cell_baseline = 0,
... (274 lines truncated)
</file>

<file path="src/font/glyf_rasterize.zig">
//! Rasterization for OpenType glyf outlines.
//!
//! This module intentionally lives in `font` rather than `font/opentype`
//! because I wanted to keep `font/opentype` dependency free on the font
//! package.

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const z2d = @import("z2d");

const Glyph = @import("Glyph.zig");
const glyf = @import("opentype/glyf.zig");

const DesignMetrics = Glyph.DesignMetrics;

/// An owned, tightly packed alpha8 bitmap.
pub const Bitmap = struct {
    width: u32,
    height: u32,
    data: []u8,

    // An empty 0x0 bitmap.
    pub const empty: Bitmap = .{ .width = 0, .height = 0, .data = "" };

    pub fn initEmpty(alloc: Allocator, width: u32, height: u32) Allocator.Error!Bitmap {
        const data = try alloc.alloc(u8, @as(usize, width) * @as(usize, height));
        @memset(data, 0);
        return .{ .width = width, .height = height, .data = data };
    }
... (798 lines truncated)
</file>

<file path="src/font/Glyph.zig">
//! Glyph is a single loaded glyph for a face.
const Glyph = @This();

const std = @import("std");
const Metrics = @import("Metrics.zig");

/// width of glyph in pixels
width: u32,

/// height of glyph in pixels
height: u32,

/// left bearing
offset_x: i32,

/// top bearing
offset_y: i32,

/// coordinates in the atlas of the top-left corner. These have to
/// be normalized to be between 0 and 1 prior to use in shaders.
atlas_x: u32,
atlas_y: u32,

/// The size and position of a glyph.
pub const Size = struct {
    width: f64,
    height: f64,
    x: f64,
    y: f64,
};
... (601 lines truncated)
</file>

<file path="src/font/library.zig">
//! A library represents the shared state that the underlying font
//! library implementation(s) require per-process.
const std = @import("std");
const Allocator = std.mem.Allocator;
const options = @import("main.zig").options;
const freetype = @import("freetype");
const font = @import("main.zig");

/// Library implementation for the compile options.
pub const Library = switch (options.backend) {
    // Freetype requires a state library
    .freetype,
    .freetype_windows,
    .fontconfig_freetype,
    .coretext_freetype,
    => FreetypeLibrary,

    // Some backends such as CT and Canvas don't have a "library"
    .coretext,
    .coretext_harfbuzz,
    .coretext_noshape,
    .web_canvas,
    => NoopLibrary,
};

pub const FreetypeLibrary = struct {
    lib: freetype.Library,

    alloc: Allocator,

... (35 lines truncated)
</file>

<file path="src/font/main.zig">
const std = @import("std");
const builtin = @import("builtin");
const build_config = @import("../build_config.zig");

const library = @import("library.zig");

pub const Atlas = @import("Atlas.zig");
pub const Backend = @import("backend.zig").Backend;
pub const discovery = @import("discovery.zig");
pub const embedded = @import("embedded.zig");
pub const face = @import("face.zig");
pub const CodepointMap = @import("CodepointMap.zig");
pub const CodepointResolver = @import("CodepointResolver.zig");
pub const Collection = @import("Collection.zig");
pub const DeferredFace = @import("DeferredFace.zig");
pub const Face = face.Face;
pub const Glyph = @import("Glyph.zig");
pub const glyf_rasterize = @import("glyf_rasterize.zig");
pub const Metrics = @import("Metrics.zig");
pub const opentype = @import("opentype.zig");
pub const shape = @import("shape.zig");
pub const Shaper = shape.Shaper;
pub const ShaperCache = shape.Cache;
pub const SharedGrid = @import("SharedGrid.zig");
pub const SharedGridSet = @import("SharedGridSet.zig");
pub const sprite = @import("sprite.zig");
pub const Sprite = sprite.Sprite;
pub const SpriteFace = sprite.Face;
pub const Descriptor = discovery.Descriptor;
pub const Discover = discovery.Discover;
... (54 lines truncated)
</file>

<file path="src/font/Metrics.zig">
const Metrics = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;

/// Recommended cell width and height for a monospace grid using this font.
cell_width: u32,
cell_height: u32,

/// Distance in pixels from the bottom of the cell to the text baseline.
cell_baseline: u32,

/// Distance in pixels from the top of the cell to the top of the underline.
underline_position: u32,
/// Thickness in pixels of the underline.
underline_thickness: u32,

/// Distance in pixels from the top of the cell to the top of the strikethrough.
strikethrough_position: u32,
/// Thickness in pixels of the strikethrough.
strikethrough_thickness: u32,

/// Distance in pixels from the top of the cell to the top of the overline.
/// Can be negative to adjust the position above the top of the cell.
overline_position: i32,
/// Thickness in pixels of the overline.
overline_thickness: u32,

/// Thickness in pixels of box drawing characters.
box_thickness: u32,
... (789 lines truncated)
</file>

<file path="src/font/nerd_font_attributes.zig">
//! Nerd Font glyph constraints.
//!
//! `table` is a 3-level codepoint lookup, same shape as
//! `unicode/symbols_table.zig`. Pages with no constrained glyphs share
//! one stage2 block and return null after the stage1 load.

const std = @import("std");
const lut = @import("../unicode/lut.zig");
const Constraint = @import("Glyph.zig").RenderOptions.Constraint;
const generated = @import("nerd_font_tables.zig").Tables(?Constraint);

/// 3-level codepoint lookup. Same shape as `unicode/symbols_table.zig`.
pub const table: lut.Tables(?Constraint) = .{
    .stage1 = &generated.stage1,
    .stage2 = &generated.stage2,
    .stage3 = &generated.stage3,
};

// lut.zig pages are 256 codepoints. The generator stores the all-null
// page at stage2 offset 0, and stage3 index 0 is null.
const empty_block: u16 = 0;

comptime {
    // One stage1 entry for every high byte of a u21.
    if (generated.stage1.len != 0x2000) @compileError("stage1 must cover every u21 page");
    if (generated.stage3.len == 0 or generated.stage3[0] != null) {
        @compileError("stage3[0] must be null");
    }
    for (generated.stage2[0..256]) |entry| {
        if (entry != 0) @compileError("empty nerd-font page must be stage2 offset 0");
... (38 lines truncated)
</file>

<file path="src/font/nerd_font_codegen.py">
class PatchSetScaleRules(TypedDict)
⋮----
ShiftMode: str
ScaleGroups: list[list[int] | range]
⋮----
class PatchSetAttributeEntry(TypedDict)
⋮----
align: str
valign: str
stretch: str
params: dict[str, float | bool]
⋮----
relative_x: float
relative_y: float
relative_width: float
relative_height: float
⋮----
class PatchSet(TypedDict)
⋮----
Name: str
Filename: str
Exact: bool
SymStart: int
SymEnd: int
SrcStart: int | None
ScaleRules: PatchSetScaleRules | None
Attributes: PatchSetAttributes
⋮----
class PatchSetExtractor(ast.NodeVisitor)
⋮----
... (80 lines truncated)
</file>

<file path="src/font/nerd_font_codepoint_tables.py">
version = "3.4.0"
cp_tables = {
</file>

<file path="src/font/nerd_font_tables.zig">
//! This is a generated file, produced by nerd_font_codegen.py
//! DO NOT EDIT BY HAND!
//!
//! 3-level lookup from a codepoint to a Nerd Font glyph constraint.
//! The layout matches src/unicode/lut.zig. stage3 index 0 is null.
//! Stage2 offset 0 is the shared page with no constrained glyphs.

pub fn Tables(comptime Elem: type) type {
    return struct {
        pub const stage1: [8192]u16 = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 256, 0, 0, 512, 768, 0, 0, 0, 1024, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1280, 0, 1536, 1792, 0, 2048, 2304, 2560, 2816, 0, 3072, 3328, 3584, 2560, 3840, 4096, 4352, 4608, 4864, 5120, 5376, 5632, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5888, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, 6144, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        pub const stage2: [6400]u16 = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 19, 0, 21, 0, 27, 28, 29, 6, 29, 29, 30, 0, 31, 0, 32, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 1, 1, 99, 100, 1, 101, 1, 102, 1, 1, 103, 104, 1, 105, 1, 106, 107, 108, 109, 109, 109, 110, 109, 109, 111, 112, 1, 1, 60, 44, 113, 73, 114, 115, 116, 48, 117, 75, 1, 118, 1, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 1, 136, 137, 138, 139, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 140, 140, 140, 140, 141, 141, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 155, 156, 155, 156, 155, 155, 110, 157, 158, 159, 160, 161, 162, 163, 163, 163, 162, 1, 162, 162, 162, 162, 162, 162, 162, 1, 1, 1, 1, 1, 164, 165, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 166, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 167, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 168, 169, 170, 171, 172, 173, 173, 172, 169, 174, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 175, 176, 177, 178, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 179, 179, 180, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 181, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 182, 183, 184, 182, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 185, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 186, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 187, 188, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 189, 1, 1, 1, 190, 191, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 193, 194, 192, 193, 194, 195, 196, 197, 198, 199, 200, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 201, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 202, 202, 1, 1, 1, 203, 1, 1, 1, 1, 1, 204, 204, 204, 1, 205, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 206, 1, 207, 1, 208, 209, 208, 210, 211, 211, 208, 212, 209, 208, 213, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 214, 214, 1, 215, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 216, 217, 1, 1, 1, 1, 1, 218, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 219, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 220, 220, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 221, 222, 223, 224, 1, 225, 226, 227, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 228, 228, 229, 230, 228, 228, 231, 231, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 232, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 233, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 207, 207, 1, 234, 235, 207, 236, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 237, 1, 238, 238, 1, 1, 1, 1, 1, 1, 1, 1, 1, 239, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 240, 241, 1, 240, 240, 240, 241, 240, 242, 240, 243, 240, 243, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 244, 244, 245, 246, 1, 244, 247, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 248, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 249, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 250, 251, 252, 253, 1, 1, 1, 254, 1, 1, 1, 1, 1, 255, 1, 1, 1, 1, 256, 257, 257, 1, 1, 1, 1, 258, 259, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 260, 1, 1, 1, 261, 262, 1, 1, 1, 1, 1, 263, 1, 1, 1, 1, 264, 1, 1, 1, 265, 1, 1, 1, 1, 1, 266, 1, 1, 1, 267, 268, 268, 269, 270, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 271, 1, 1, 1, 1, 1, 1, 1, 272, 1, 1, 1, 1, 1, 1, 273, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 257, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 274, 275, 276, 274, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 257, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        pub const stage3: [277]Elem = .{
            null,
            .{
                .size = .fit_cover1,
                .height = .icon,
                .align_horizontal = .center1,
                .align_vertical = .center1,
            },
            .{
                .size = .cover,
                .height = .icon,
                .max_constraint_width = 1,
                .align_horizontal = .center1,
                .align_vertical = .center1,
                .pad_left = 0.05,
                .pad_right = 0.05,
                .pad_top = 0.05,
... (2336 lines truncated)
</file>

<file path="src/font/opentype.zig">
pub const sfnt = @import("opentype/sfnt.zig");

const svg = @import("opentype/svg.zig");
const os2 = @import("opentype/os2.zig");
const post = @import("opentype/post.zig");
const hhea = @import("opentype/hhea.zig");
const head = @import("opentype/head.zig");
const glyf = @import("opentype/glyf.zig");

pub const SVG = svg.SVG;
pub const OS2 = os2.OS2;
pub const Post = post.Post;
pub const Hhea = hhea.Hhea;
pub const Head = head.Head;
pub const Glyf = glyf.Glyf;

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/font/shape.zig">
const std = @import("std");
const options = @import("main.zig").options;
const run = @import("shaper/run.zig");
const feature = @import("shaper/feature.zig");
const configpkg = @import("../config.zig");
const terminal = @import("../terminal/main.zig");
const SharedGrid = @import("main.zig").SharedGrid;
pub const noop = @import("shaper/noop.zig");
pub const harfbuzz = @import("shaper/harfbuzz.zig");
pub const coretext = @import("shaper/coretext.zig");
pub const web_canvas = @import("shaper/web_canvas.zig");
pub const Cache = @import("shaper/Cache.zig");
pub const TextRun = run.TextRun;
pub const RunIterator = run.RunIterator;
pub const Feature = feature.Feature;
pub const FeatureList = feature.FeatureList;
pub const default_features = feature.default_features;

/// Shaper implementation for our compile options.
pub const Shaper = switch (options.backend) {
    .freetype,
    .freetype_windows,
    .fontconfig_freetype,
    .coretext_freetype,
    .coretext_harfbuzz,
    => harfbuzz.Shaper,

    // Note that coretext_freetype cannot use the coretext
    // shaper because the coretext shaper requests CoreText
    // font faces.
... (73 lines truncated)
</file>

<file path="src/font/SharedGrid.zig">
//! This structure represents the state required to render a terminal
//! grid using the font subsystem. It is "shared" because it is able to
//! be shared across multiple surfaces.
//!
//! It is desirable for the grid state to be shared because the font
//! configuration for a set of surfaces is almost always the same and
//! font data is relatively memory intensive. Further, the font subsystem
//! should be read-heavy compared to write-heavy, so it handles concurrent
//! reads well. Going even further, the font subsystem should be very rarely
//! read at all since it should only be necessary when the grid actively
//! changes.
//!
//! SharedGrid does NOT support resizing, font-family changes, font removals
//! in collections, etc. Because the Grid is shared this would cause a
//! major disruption in the rendering of multiple surfaces (i.e. increasing
//! the font size in one would increase it in all). In many cases this isn't
//! desirable so to implement configuration changes the grid should be
//! reinitialized and all surfaces should switch over to using that one.
const SharedGrid = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const tripwire = @import("../tripwire.zig");
const Allocator = std.mem.Allocator;
const renderer = @import("../renderer.zig");
const font = @import("main.zig");
const Atlas = font.Atlas;
const CodepointResolver = font.CodepointResolver;
const Collection = font.Collection;
const Face = font.Face;
... (658 lines truncated)
</file>

<file path="src/font/SharedGridSet.zig">
//! This structure contains a set of SharedGrid structures keyed by
//! unique font configuration.
//!
//! Most terminals (surfaces) will share the same font configuration.
//! This structure allows expensive font information such as
//! the font atlas, glyph cache, font faces, etc. to be shared.
//!
//! This structure is thread-safe when the operations are documented
//! as thread-safe.
const SharedGridSet = @This();

const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const font = @import("main.zig");
const CodepointResolver = font.CodepointResolver;
const Collection = font.Collection;
const Discover = font.Discover;
const Style = font.Style;
const Library = font.Library;
const Metrics = font.Metrics;
const CodepointMap = font.CodepointMap;
const DesiredSize = font.face.DesiredSize;
const Face = font.Face;
const SharedGrid = font.SharedGrid;
const discovery = @import("discovery.zig");
const configpkg = @import("../config.zig");
const Config = configpkg.Config;
... (824 lines truncated)
</file>

<file path="src/font/sprite.zig">
const std = @import("std");
const canvas = @import("sprite/canvas.zig");
pub const Face = @import("sprite/Face.zig");

pub const Box = canvas.Box;
pub const Point = canvas.Point;
pub const Canvas = canvas.Canvas;
pub const Color = canvas.Color;

/// Sprites are represented as special codepoints outside of the Unicode
/// codepoint range. Unicode maxes out at U+10FFFF (21 bits), and we use the
/// high 11 bits to hide our special characters.
///
/// These characters are ONLY used for rendering and NEVER used written to
/// text files or any other exported format, so we don't use the Private Use
/// Area of Unicode.
pub const Sprite = enum(u32) {
    // Start 1 above the maximum Unicode codepoint.
    pub const start: u32 = std.math.maxInt(u21) + 1;
    pub const end: u32 = std.math.maxInt(u32);

    underline = start,
    underline_double,
    underline_dotted,
    underline_dashed,
    underline_curly,

    strikethrough,

    overline,
... (16 lines truncated)
</file>

<file path="src/input/Binding.zig">
//! A binding maps some input trigger to an action. When the trigger
//! occurs, the action is performed.
const Binding = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../quirks.zig").inlineAssert;
const build_config = @import("../build_config.zig");
const uucode = @import("uucode");
const EntryFormatter = @import("../config/formatter.zig").EntryFormatter;
const deepEqual = @import("../datastruct/comparison.zig").deepEqual;
const key = @import("key.zig");
const key_mods = @import("key_mods.zig");
const KeyEvent = key.KeyEvent;

/// The trigger that needs to be performed to execute the action.
trigger: Trigger,

/// The action to take if this binding matches
action: Action,

/// Boolean flags that can be set per binding.
flags: Flags = .{},

pub const Error = error{
    InvalidFormat,
    InvalidAction,
};

/// Flags the full binding-scoped flags that can be set per binding.
... (4892 lines truncated)
</file>

<file path="src/input/command.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const Action = @import("Binding.zig").Action;
const i18n = @import("../os/i18n.zig");

/// A command is a named binding action that can be executed from
/// something like a command palette.
///
/// A command must be associated with a binding; all commands can be
/// mapped to traditional `keybind` configurations. This restriction
/// makes it so that there is nothing special about commands and likewise
/// it makes it trivial and consistent to define custom commands.
///
/// For apprt implementers: a command palette doesn't have to make use
/// of all the fields here. We try to provide as much information as
/// possible to make it easier to implement a command palette in the way
/// that makes the most sense for the application.
pub const Command = struct {
    action: Action,
    title: [:0]const u8,
    description: [:0]const u8 = "",

    /// ghostty_command_s
    pub const C = extern struct {
        action_key: [*:0]const u8,
        action: [*:0]const u8,
        title: [*:0]const u8,
        description: [*:0]const u8,
    };
... (739 lines truncated)
</file>

<file path="src/input/config.zig">
/// Determines the macOS option key behavior. See the config
/// `macos-option-as-alt` for a lot more details.
pub const OptionAsAlt = enum(c_int) {
    false,
    true,
    left,
    right,
};
</file>

<file path="src/input/function_keys.zig">
//! This is the list of "PC style function keys" that xterm supports for
//! the legacy keyboard protocols. These always take priority since at the
//! time of writing this, even the most modern keyboard protocols still
//! are backwards compatible with regards to these sequences.
//!
//! This is based on a variety of sources cross-referenced but mostly
//! based on foot's keymap.h: https://codeberg.org/dnkl/foot/src/branch/master/keymap.h

const std = @import("std");
const key = @import("key.zig");

pub const CursorMode = enum { any, normal, application };
pub const KeypadMode = enum { any, normal, application };

/// A bit confusing so I'll document this one: this is the "modify other keys"
/// setting. We only change behavior for "set_other" which is ESC [ > 4; 2 m.
/// So this can be "any" which means we don't care what's going on. Or it
/// can be "set" which means modify keys must be set EXCEPT FOR "other keys"
/// mode, and "set_other" which means modify keys must be set to "other keys"
/// mode.
///
/// See: https://invisible-island.net/xterm/modified-keys.html
pub const ModifyKeys = enum {
    any,
    set,
    set_other,
};

/// A single entry in the table of keys.
pub const Entry = struct {
... (305 lines truncated)
</file>

<file path="src/input/helpgen_actions.zig">
//! This module is a help generator for keybind actions documentation.
//! It can generate documentation in different formats (plaintext for CLI,
//! markdown for website) while maintaining consistent content.

const std = @import("std");
const KeybindAction = @import("Binding.zig").Action;
const help_strings = @import("help_strings");

/// Format options for generating keybind actions documentation
pub const Format = enum {
    /// Plain text output with indentation
    plaintext,
    /// Markdown formatted output
    markdown,

    fn formatFieldName(self: Format, writer: *std.Io.Writer, field_name: []const u8) !void {
        switch (self) {
            .plaintext => {
                try writer.writeAll(field_name);
                try writer.writeAll(":\n");
            },
            .markdown => {
                try writer.writeAll("## `");
                try writer.writeAll(field_name);
                try writer.writeAll("`\n");
            },
        }
    }

    fn formatDocLine(self: Format, writer: *std.Io.Writer, line: []const u8) !void {
... (83 lines truncated)
</file>

<file path="src/input/key_encode.zig">
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const KittyFlags = @import("../terminal/kitty/key.zig").Flags;
const OptionAsAlt = @import("config.zig").OptionAsAlt;
const Terminal = @import("../terminal/Terminal.zig");
const function_keys = @import("function_keys.zig");
const key = @import("key.zig");
const KittyEntry = @import("kitty.zig").Entry;
const kitty_entries = @import("kitty.zig").entries;

/// Options that affect key encoding behavior. This is a mix of behavior
/// from terminal state as well as application configuration.
pub const Options = struct {
    /// Terminal DEC mode 1
    cursor_key_application: bool = false,

    /// Terminal DEC mode 66
    keypad_key_application: bool = false,

    // DEC Backarrow Key Mode (DECBKM)
    // See https://vt100.net/dec/ek-vt3xx-tp-002.pdf page 170
    // If `false` (the default), `backspace` emits 0x7f
    // If `true`, `backspace` emits 0x08
    backarrow_key_mode: bool = false,

    /// Terminal DEC mode 1035
    ignore_keypad_with_numlock: bool = false,

    /// Terminal DEC mode 1036
... (2831 lines truncated)
</file>

<file path="src/input/key_mods.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const OptionAsAlt = @import("config.zig").OptionAsAlt;

/// Aliases for modifier names.
pub const alias: []const struct { []const u8, Mod } = &.{
    .{ "cmd", .super },
    .{ "command", .super },
    .{ "opt", .alt },
    .{ "option", .alt },
    .{ "control", .ctrl },
};

/// Single modifier
pub const Mod = enum {
    shift,
    ctrl,
    alt,
    super,

    pub const Side = enum(u1) { left, right };
};

/// A bitmask for all key modifiers.
///
/// IMPORTANT: Any changes here update include/ghostty.h
pub const Mods = packed struct(Mods.Backing) {
    pub const Backing = u16;
... (884 lines truncated)
</file>

<file path="src/input/key.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const cimgui = @import("dcimgui");

pub const Mods = @import("key_mods.zig").Mods;

/// A generic key input event. This is the information that is necessary
/// regardless of apprt in order to generate the proper terminal
/// control sequences for a given key press.
///
/// Some apprts may not be able to provide all of this information, such
/// as GLFW. In this case, the apprt should provide as much information
/// as it can and it should be expected that the terminal behavior
/// will not be totally correct.
pub const KeyEvent = struct {
    /// The action: press, release, etc.
    action: Action = .press,

    /// The keycode of the physical key that was pressed. This is agnostic
    /// to the layout. Layout-dependent matching can only be done via the
    /// UTF-8 or unshifted codepoint.
    key: Key = .unidentified,

    /// Mods are the modifiers that are pressed.
    mods: Mods = .{},

    /// The mods that were consumed in order to generate the text
    /// in utf8. This has the mods set that were consumed, so to
    /// get the set of mods that are effective you must negate
... (847 lines truncated)
</file>

<file path="src/input/keyboard.zig">
const std = @import("std");
const OptionAsAlt = @import("config.zig").OptionAsAlt;

/// Keyboard layouts.
///
/// These aren't heavily used in Ghostty and having a fully comprehensive
/// list is not important. We only need to distinguish between a few
/// different layouts for some nice-to-have features, such as setting a default
/// value for "macos-option-as-alt".
pub const Layout = enum {
    // Unknown, unmapped layout. Ghostty should not make any assumptions
    // about the layout of the keyboard.
    unknown,

    // The remaining should be fairly self-explanatory:
    us_standard,
    us_international,

    /// Map an Apple keyboard layout ID to a value in this enum. The layout
    /// ID can be retrieved using Carbon's TIKeyboardLayoutGetInputSourceProperty
    /// function.
    ///
    /// Even though our layout supports "unknown", we return null if we don't
    /// recognize the layout ID so callers can detect this scenario.
    pub fn mapAppleId(id: []const u8) ?Layout {
        if (std.mem.eql(u8, id, "com.apple.keylayout.US")) {
            return .us_standard;
        } else if (std.mem.eql(u8, id, "com.apple.keylayout.USInternational")) {
            return .us_international;
        }
... (29 lines truncated)
</file>

<file path="src/input/keycodes.zig">
// Based on the Chromium source. The Chromium source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// https://source.chromium.org/chromium/chromium/src/+/main:ui/events/keycodes/dom/dom_code_data.inc

const std = @import("std");
const builtin = @import("builtin");
const Key = @import("key.zig").Key;

/// The full list of entries for the current platform.
pub const entries: []const Entry = entries: {
    const native_idx = switch (builtin.os.tag) {
        .ios, .macos => 4, // mac
        .windows => 3, // win
        .freebsd, .linux => 2, // xkb
        else => @compileError("unsupported platform"),
    };

    var result: [raw_entries.len]Entry = undefined;
    for (raw_entries, 0..) |raw, i| {
        @setEvalBranchQuota(10000);
        result[i] = .{
            .key = code_to_key.get(raw[5]) orelse .unidentified,
            .usb = raw[0],
            .code = raw[5],
            .native = raw[native_idx],
        };
    }

    const final = result;
    break :entries &final;
... (644 lines truncated)
</file>

<file path="src/input/KeymapDarwin.zig">
// Keymap is responsible for translating keyboard inputs into localized chars.
///
/// For example, the physical key "S" on a US-layout keyboard might mean "O"
/// in Dvorak. On international keyboard layouts, it may require multiple
/// keystrokes to produce a single character that is otherwise a single
/// keystroke on a US-layout keyboard.
///
/// This information is critical to know for many reasons. For keybindings,
/// if a user configures "ctrl+o" to do something, it should work with the
/// physical "ctrl+S" key on a Dvorak keyboard and so on.
///
/// This is currently only implemented for macOS.
const Keymap = @This();

const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const macos = @import("macos");
const codes = @import("keycodes.zig").entries;
const Mods = @import("key.zig").Mods;

/// The current input source that is selected for the keyboard. This can
/// and does change whenever the user selects a new keyboard layout. This
/// change doesn't happen automatically; the user of this struct has to
/// detect it and then call `reload` to update the keymap.
source: *TISInputSource,

/// The keyboard layout for the current input source.
///
/// This doesn't need to be freed because its owned by the InputSource.
... (260 lines truncated)
</file>

<file path="src/input/KeymapNoop.zig">
//! A noop implementation of the keymap interface so that the embedded
//! library can compile on non-macOS platforms.
const KeymapNoop = @This();

const Mods = @import("key.zig").Mods;

pub const State = struct {};
pub const Translation = struct {
    text: []const u8 = "",
    composing: bool = false,
    mods: Mods = .{},
};

pub fn init() !KeymapNoop {
    return .{};
}

pub fn deinit(self: *const KeymapNoop) void {
    _ = self;
}

pub fn reload(self: *KeymapNoop) !void {
    _ = self;
}

pub fn translate(
    self: *const KeymapNoop,
    out: []u8,
    state: *State,
    code: u16,
... (10 lines truncated)
</file>

<file path="src/input/kitty.zig">
const key = @import("key.zig");

/// A single entry in the kitty keymap data. There are only ~100 entries
/// so the recommendation is to just use a linear search to find the entry
/// for a given key.
pub const Entry = struct {
    key: key.Key,
    code: u21,
    final: u8,
    modifier: bool,
};

/// The full list of entries for the current platform.
pub const entries: []const Entry = entries: {
    var result: [raw_entries.len]Entry = undefined;
    for (raw_entries, 0..) |raw, i| {
        result[i] = .{
            .key = raw[0],
            .code = raw[1],
            .final = raw[2],
            .modifier = raw[3],
        };
    }

    const final = result;
    break :entries &final;
};

/// Raw entry is the tuple form of an entry for easy human management.
/// This should never be used in a real program so it is not pub. For
... (105 lines truncated)
</file>

<file path="src/input/Link.zig">
//! A link is a clickable element that can be used to trigger some action.
//! A link is NOT just a URL that opens in a browser. A link is any generic
//! regular expression match over terminal text that can trigger various
//! action types.
const Link = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const oni = @import("oniguruma");
const Mods = @import("key.zig").Mods;

/// The regular expression that will be used to match the link. Ownership
/// of this memory is up to the caller. The link will never free this memory.
regex: []const u8,

/// The action that will be triggered when the link is clicked.
action: Action,

/// The situations in which the link will be highlighted. A link is only
/// clickable by the mouse when it is highlighted, so this also controls
/// when the link is clickable.
highlight: Highlight,

pub const Action = union(enum) {
    /// Open the full matched value using the default open program.
    /// For example, on macOS this is "open" and on Linux this is "xdg-open".
    open: void,

    /// Open the OSC8 hyperlink under the mouse position. _-prefixed means
    /// this can't be user-specified, it's only used internally.
... (50 lines truncated)
</file>

<file path="src/input/mouse_encode.zig">
const std = @import("std");
const testing = std.testing;
const terminal = @import("../terminal/main.zig");
const Terminal = terminal.Terminal;
const renderer_size = @import("../renderer/size.zig");
const point = @import("../terminal/point.zig");
const key = @import("key.zig");
const mouse = @import("mouse.zig");

const log = std.log.scoped(.mouse_encode);

/// Options that affect mouse encoding behavior and provide runtime context.
pub const Options = struct {
    /// Terminal mouse reporting mode (X10, normal, button, any).
    event: terminal.MouseEvent = .none,

    /// Terminal mouse reporting format.
    format: terminal.MouseFormat = .x10,

    /// Full renderer size used to convert surface-space pixel positions
    /// into grid cell coordinates (for most formats) and terminal-space
    /// pixel coordinates (for SGR-Pixels), as well as to determine
    /// whether a position falls outside the visible viewport.
    size: renderer_size.Size,

    /// Whether any mouse button is currently pressed. When a motion
    /// event occurs outside the viewport, it is only reported if a
    /// button is held down and the event mode supports motion tracking.
    /// Without this, out-of-viewport motions are silently dropped.
    ///
... (766 lines truncated)
</file>

<file path="src/input/mouse.zig">
const std = @import("std");

/// The type of action associated with a mouse event. This is different
/// from ButtonState because button state is simply the current state
/// of a mouse button but an action is something that triggers via
/// an GUI event and supports more.
pub const Action = enum(c_int) { press, release, motion };

/// The state of a mouse button.
///
/// This is backed by a c_int so we can use this as-is for our embedding API.
///
/// IMPORTANT: Any changes here update include/ghostty.h
pub const ButtonState = enum(c_int) {
    release,
    press,
};

/// Possible mouse buttons. We only track up to 11 because that's the maximum
/// button input that terminal mouse tracking handles without becoming
/// ambiguous.
///
/// Its a bit silly to name numbers like this but given its a restricted
/// set, it feels better than passing around raw numeric literals.
///
/// This is backed by a c_int so we can use this as-is for our embedding API.
///
/// IMPORTANT: Any changes here update include/ghostty.h
pub const Button = enum(c_int) {
    const Self = @This();
... (81 lines truncated)
</file>

<file path="src/input/paste.zig">
const std = @import("std");
const Terminal = @import("../terminal/Terminal.zig");

/// The bracketed paste (mode 2004) frame written around the data.
pub const bracketed_prefix = "\x1b[200~";
pub const bracketed_suffix = "\x1b[201~";

/// The maximum number of bytes `encode` adds around the data, so callers
/// can size a buffer for the full encoded result.
pub const max_frame_size = bracketed_prefix.len + bracketed_suffix.len;

pub const Options = struct {
    /// True if bracketed paste mode is on.
    bracketed: bool,

    /// Return the encoding options based on the current terminal state.
    pub fn fromTerminal(t: *const Terminal) Options {
        return .{
            .bracketed = t.modes.get(.bracketed_paste),
        };
    }
};

/// Encode the given data for pasting. The resulting value can be written
/// to the pty to perform a paste of the input data.
///
/// The data can be either a `[]u8` or a `[]const u8`. If the data
/// type is const then `EncodeError` may be returned. If the data type
/// is mutable then this function can't return an error.
///
... (363 lines truncated)
</file>

<file path="src/inspector/widgets/key.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const input = @import("../../input.zig");
const CircBuf = @import("../../datastruct/main.zig").CircBuf;
const cimgui = @import("dcimgui");

/// Circular buffer of key events.
pub const EventRing = CircBuf(Event, undefined);

/// Represents a recorded keyboard event.
pub const Event = struct {
    /// The input event.
    event: input.KeyEvent,

    /// The binding that was triggered as a result of this event.
    /// Multiple bindings are possible if they are chained.
    binding: []const input.Binding.Action = &.{},

    /// The data sent to the pty as a result of this keyboard event.
    /// This is allocated using the inspector allocator.
    pty: []const u8 = "",

    /// State for the inspector GUI. Do not set this unless you're the inspector.
    imgui_state: struct {
        selected: bool = false,
    } = .{},

    pub fn init(alloc: Allocator, ev: input.KeyEvent) !Event {
        var copy = ev;
        copy.utf8 = "";
... (502 lines truncated)
</file>

<file path="src/inspector/widgets/page.zig">
const std = @import("std");
const cimgui = @import("dcimgui");
const terminal = @import("../../terminal/main.zig");
const units = @import("../units.zig");
const widgets = @import("../widgets.zig");

const PageList = terminal.PageList;
const Page = terminal.Page;

pub fn inspector(page: *const terminal.Page) void {
    cimgui.c.ImGui_SeparatorText("Managed Memory");
    managedMemory(page);

    cimgui.c.ImGui_SeparatorText("Styles");
    stylesList(page);

    cimgui.c.ImGui_SeparatorText("Hyperlinks");
    hyperlinksList(page);

    cimgui.c.ImGui_SeparatorText("Rows");
    rowsTable(page);
}

/// Draw a tree node header with metadata about this page. Returns if
/// the tree node is open or not. If it is open you must close it with
/// TreePop.
pub fn treeNode(state: struct {
    /// Page dimensions available without reading its backing memory.
    cols: terminal.size.CellCountInt,
    rows: terminal.size.CellCountInt,
... (408 lines truncated)
</file>

<file path="src/inspector/widgets/pagelist.zig">
const std = @import("std");
const cimgui = @import("dcimgui");
const terminal = @import("../../terminal/main.zig");
const pagepkg = @import("../../terminal/page.zig");
const stylepkg = @import("../../terminal/style.zig");
const widgets = @import("../widgets.zig");

const PageList = terminal.PageList;

/// Cell pointers resolved against a Node.PreservedPage rather than the
/// PageList node.
/// Omitting the node makes it impossible for inspector helpers to
/// accidentally restore the original compressed page.
const InspectedCell = struct {
    row: *pagepkg.Row,
    cell: *pagepkg.Cell,
    row_idx: terminal.size.CellCountInt,
    col_idx: terminal.size.CellCountInt,
};

/// PageList inspector widget.
pub const Inspector = struct {
    pub const empty: Inspector = .{};

    pub fn draw(_: *const Inspector, pages: *PageList) void {
        cimgui.c.ImGui_TextWrapped(
            "PageList manages the backing pages that hold scrollback and the active " ++
                "terminal grid. Each page is a contiguous memory buffer with its " ++
                "own rows, cells, style set, grapheme map, and hyperlink storage.",
        );
... (999 lines truncated)
</file>

<file path="src/inspector/widgets/renderer.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const cimgui = @import("dcimgui");
const widgets = @import("../widgets.zig");
const renderer = @import("../../renderer.zig");

const log = std.log.scoped(.inspector_renderer);

/// Renderer information inspector widget.
pub const Info = struct {
    features: std.AutoArrayHashMapUnmanaged(
        std.meta.Tag(renderer.Overlay.Feature),
        renderer.Overlay.Feature,
    ),

    pub const empty: Info = .{
        .features = .empty,
    };

    pub fn deinit(self: *Info, alloc: Allocator) void {
        self.features.deinit(alloc);
    }

    /// Grab the features into a new allocated slice. This is used by
    pub fn overlayFeatures(
        self: *const Info,
        alloc: Allocator,
    ) Allocator.Error![]renderer.Overlay.Feature {
        // The features from our internal state.
        const features = self.features.values();
... (94 lines truncated)
</file>

<file path="src/inspector/widgets/screen.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const cimgui = @import("dcimgui");
const widgets = @import("../widgets.zig");
const units = @import("../units.zig");
const terminal = @import("../../terminal/main.zig");
const stylepkg = @import("../../terminal/style.zig");

/// Window names for the screen dockspace.
const window_info = "Info";
const window_cell = "Cell";
const window_pagelist = "PageList";

/// Screen information inspector widget.
pub const Info = struct {
    pagelist: widgets.pagelist.Inspector,
    cell_chooser: widgets.pagelist.CellChooser,

    pub const empty: Info = .{
        .pagelist = .empty,
        .cell_chooser = .empty,
    };

    /// Draw the screen info contents.
    pub fn draw(self: *Info, open: bool, data: struct {
        /// The screen that we're inspecting.
        screen: *terminal.Screen,

... (376 lines truncated)
</file>

<file path="src/inspector/widgets/style.zig">
const std = @import("std");
const cimgui = @import("dcimgui");
const terminal = @import("../../terminal/main.zig");
const widgets = @import("../widgets.zig");

/// Render a style as a table.
pub fn table(
    st: terminal.Style,
    palette: ?*const terminal.color.Palette,
) void {
    {
        _ = cimgui.c.ImGui_BeginTable(
            "style",
            2,
            cimgui.c.ImGuiTableFlags_None,
        );
        defer cimgui.c.ImGui_EndTable();
        {
            cimgui.c.ImGui_TableNextRow();
            _ = cimgui.c.ImGui_TableSetColumnIndex(0);
            cimgui.c.ImGui_Text("Foreground");
            cimgui.c.ImGui_SameLine();
            widgets.helpMarker("The foreground (text) color");
            _ = cimgui.c.ImGui_TableSetColumnIndex(1);
            color("fg", st.fg_color, palette);
        }

        {
            cimgui.c.ImGui_TableNextRow();
            _ = cimgui.c.ImGui_TableSetColumnIndex(0);
... (96 lines truncated)
</file>

<file path="src/inspector/widgets/surface.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const cimgui = @import("dcimgui");
const inspector = @import("../main.zig");
const widgets = @import("../widgets.zig");
const input = @import("../../input.zig");
const renderer = @import("../../renderer.zig");
const terminal = @import("../../terminal/main.zig");
const Surface = @import("../../Surface.zig");
const global = @import("../../global.zig");

/// This is discovered via the hardcoded string in the ImGui demo window.
const window_imgui_demo = "Dear ImGui Demo";
const window_keyboard = "Keyboard";
const window_terminal = "Terminal";
const window_surface = "Surface";
const window_termio = "Terminal IO";
const window_renderer = "Renderer";

pub const Inspector = struct {
    /// Internal GUI state
    surface_info: Info,
    key_stream: widgets.key.Stream,
    terminal_info: widgets.terminal.Info,
    vt_stream: widgets.termio.Stream,
    renderer_info: widgets.renderer.Info,
    show_demo_window: bool,

... (476 lines truncated)
</file>

<file path="src/inspector/widgets/terminal.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const cimgui = @import("dcimgui");
const widgets = @import("../widgets.zig");
const terminal = @import("../../terminal/main.zig");
const modes = terminal.modes;
const Terminal = terminal.Terminal;

/// Terminal information inspector widget.
pub const Info = struct {
    /// True if we're showing the 256-color palette window.
    show_palette: bool,

    /// The various detachable headers.
    misc_header: widgets.DetachableHeader,
    layout_header: widgets.DetachableHeader,
    mouse_header: widgets.DetachableHeader,
    color_header: widgets.DetachableHeader,
    modes_header: widgets.DetachableHeader,

    /// Screen detail windows for each screen key.
    screens: ScreenMap,

    pub const empty: Info = .{
        .show_palette = false,
        .misc_header = .{},
        .layout_header = .{},
        .mouse_header = .{},
... (697 lines truncated)
</file>

<file path="src/inspector/widgets/termio.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const cimgui = @import("dcimgui");
const terminal = @import("../../terminal/main.zig");
const CircBuf = @import("../../datastruct/main.zig").CircBuf;
const Surface = @import("../../Surface.zig");
const screen = @import("screen.zig");

const log = std.log.scoped(.inspector_terminal_io);

/// VT event stream inspector widget.
pub const Stream = struct {
    events: VTEvent.Ring,
    parser_stream: VTHandler.Stream,

    /// The currently selected event sequence number for keyboard navigation
    selected_event_seq: ?u32 = null,

    /// Flag indicating whether we need to scroll to the selected item
    need_scroll_to_selected: bool = false,

    /// Flag indicating whether the selection was made by keyboard
    is_keyboard_selection: bool = false,

    pub fn init(alloc: Allocator) !Stream {
        var events: VTEvent.Ring = try .init(alloc, 2);
        errdefer events.deinit(alloc);

        var handler: VTHandler = .init;
... (863 lines truncated)
</file>

<file path="src/inspector/AGENTS.md">
# Inspector Subsystem

The inspector is a feature of Ghostty that works similar to a
browser's developer tools. It allows the user to inspect and modify the
terminal state.

- See the full C API by finding `dcimgui.h` in the `.zig-cache` folder
  in the root: `find . -type f -name dcimgui.h`. Use the newest version.
- See full examples of how to use every widget by loading this file:
  <https://raw.githubusercontent.com/ocornut/imgui/refs/heads/master/imgui_demo.cpp>
- On macOS, run builds with `-Demit-macos-app=false` to verify API usage.
- There are no unit tests in this package.
</file>

<file path="src/inspector/Inspector.zig">
//! The Inspector is a development tool to debug the terminal. This is
//! useful for terminal application developers as well as people potentially
//! debugging issues in Ghostty itself.
const Inspector = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const cimgui = @import("dcimgui");
const Surface = @import("../Surface.zig");
const font = @import("../font/main.zig");
const terminal = @import("../terminal/main.zig");
const inspector = @import("main.zig");
const widgets = @import("widgets.zig");

/// Mouse state that we track in addition to normal mouse states that
/// Ghostty always knows about.
mouse: widgets.surface.Mouse = .{},

// ImGui state
gui: widgets.surface.Inspector,

/// Setup the ImGui state. This requires an ImGui context to be set.
pub fn setup() void {
    const io: *cimgui.c.ImGuiIO = cimgui.c.ImGui_GetIO();

    // Enable docking, which we use heavily for the UI.
    io.ConfigFlags |= cimgui.c.ImGuiConfigFlags_DockingEnable;

... (100 lines truncated)
</file>

<file path="src/inspector/main.zig">
pub const widgets = @import("widgets.zig");
pub const Inspector = @import("Inspector.zig");

pub const KeyEvent = widgets.key.Event;

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/inspector/units.zig">
pub fn toKibiBytes(bytes: usize) usize {
    return bytes / 1024;
}
</file>

<file path="src/inspector/widgets.zig">
const cimgui = @import("dcimgui");

pub const page = @import("widgets/page.zig");
pub const pagelist = @import("widgets/pagelist.zig");
pub const key = @import("widgets/key.zig");
pub const renderer = @import("widgets/renderer.zig");
pub const screen = @import("widgets/screen.zig");
pub const style = @import("widgets/style.zig");
pub const surface = @import("widgets/surface.zig");
pub const terminal = @import("widgets/terminal.zig");
pub const termio = @import("widgets/termio.zig");

/// Draws a "(?)" disabled text marker that shows some help text
/// on hover.
pub fn helpMarker(text: [:0]const u8) void {
    cimgui.c.ImGui_TextDisabled("(?)");
    if (!cimgui.c.ImGui_BeginItemTooltip()) return;
    defer cimgui.c.ImGui_EndTooltip();

    cimgui.c.ImGui_PushTextWrapPos(cimgui.c.ImGui_GetFontSize() * 35.0);
    defer cimgui.c.ImGui_PopTextWrapPos();

    cimgui.c.ImGui_TextUnformatted(text.ptr);
}

/// DetachableHeader allows rendering a collapsing header that can be
/// detached into its own window.
pub const DetachableHeader = struct {
    /// Set whether the window is detached.
    detached: bool = false,
... (109 lines truncated)
</file>

<file path="src/os/wasm/log.zig">
const std = @import("std");
const wasm = @import("../wasm.zig");

// Use the correct implementation
pub const log = Freestanding.log;

/// A log function that discards everything. Since the format string and
/// scope are comptime parameters, using this compiles out all logging
/// machinery: call sites, format strings, and the std.fmt code they
/// reference (~220KB in a ReleaseFast wasm build).
pub fn noop(
    comptime level: std.log.Level,
    comptime scope: @TypeOf(.EnumLiteral),
    comptime format: []const u8,
    args: anytype,
) void {
    _ = level;
    _ = scope;
    _ = format;
    _ = args;
}

/// Freestanding implementation calls an extern "log" function.
pub const Freestanding = struct {
    // The function std.log will call.
    pub fn log(
        comptime level: std.log.Level,
        comptime scope: @TypeOf(.EnumLiteral),
        comptime format: []const u8,
        args: anytype,
... (32 lines truncated)
</file>

<file path="src/os/wasm/target.zig">
const std = @import("std");
const builtin = @import("builtin");
const options = @import("build_options");

/// The wasm target platform. This is used to toggle certain features
/// on and off since the standard triple target is often not specific
/// enough (i.e. we can't tell wasm32-freestanding is for browser or not).
pub const Target = enum {
    browser,
};

/// Our specific target platform.
pub const target: ?Target = if (!builtin.target.cpu.arch.isWasm()) null else target: {
    const result = @as(Target, @enumFromInt(@intFromEnum(options.wasm_target)));
    // This maybe isn't necessary but I don't know if enums without a specific
    // tag type and value are guaranteed to be the same between build.zig
    // compilation and our own source compilation so I have this just in case.
    std.debug.assert(std.mem.eql(u8, @tagName(result), @tagName(options.wasm_target)));
    break :target result;
};
</file>

<file path="src/os/cf_release_thread.zig">
//! Represents the CFRelease thread. Pools of CFTypeRefs are sent to
//! this thread to be released, so that their release callback logic
//! doesn't block the execution of a high throughput thread like the
//! renderer thread.
pub const Thread = @This();

const std = @import("std");
const builtin = @import("builtin");
const macos = @import("macos");

const internal_os = @import("../os/main.zig");
const global = @import("../global.zig");
const xev = global.xev;
const BlockingQueue = @import("../datastruct/main.zig").BlockingQueue;

const Allocator = std.mem.Allocator;
const log = std.log.scoped(.cf_release_thread);

pub const Message = union(enum) {
    /// Release a slice of CFTypeRefs. Uses alloc to free the slice after
    /// releasing all the refs.
    release: struct {
        refs: []*anyopaque,
        alloc: Allocator,
    },
};

/// The type used for sending messages to the thread. For now this is
/// hardcoded with a capacity. We can make this a comptime parameter in
/// the future if we want it configurable.
... (163 lines truncated)
</file>

<file path="src/os/cgroup.zig">
const std = @import("std");
const global = @import("../global.zig");

const log = std.log.scoped(.@"linux-cgroup");

/// Returns the path to the cgroup for the given pid.
pub fn current(buf: []u8, pid: u32) ?[]const u8 {
    var path_buf: [std.fs.max_path_bytes]u8 = undefined;

    // Read our cgroup by opening /proc/<pid>/cgroup and reading the first
    // line. The first line will look something like this:
    // 0::/user.slice/user-1000.slice/session-1.scope
    // The cgroup path is the third field.
    const path = std.fmt.bufPrint(&path_buf, "/proc/{}/cgroup", .{pid}) catch return null;
    const file = std.Io.Dir.openFileAbsolute(global.io(), path, .{}) catch return null;
    defer file.close(global.io());

    var read_buf: [64]u8 = undefined;
    var file_reader = file.reader(global.io(), &read_buf);
    const reader = &file_reader.interface;
    const len = reader.readSliceShort(buf) catch return null;
    const contents = buf[0..len];

    // Find the last ':'
    const idx = std.mem.lastIndexOfScalar(u8, contents, ':') orelse return null;
    return std.mem.trimEnd(u8, contents[idx + 1 ..], " \r\n");
}
</file>

<file path="src/os/dbus.zig">
const std = @import("std");
const builtin = @import("builtin");

/// Returns true if the program was launched by D-Bus activation.
///
/// On Linux GTK, this returns true if the program was launched using D-Bus
/// activation. It will return false if Ghostty was launched any other way.
///
/// For other platforms and app runtimes, this returns false.
pub fn launchedByDbusActivation() bool {
    return switch (builtin.os.tag) {
        // On Linux, D-Bus activation sets `DBUS_STARTER_ADDRESS` and
        // `DBUS_STARTER_BUS_TYPE`. If these environment variables are present
        // (no matter the value) we were launched by D-Bus activation.
        .linux => std.posix.getenv("DBUS_STARTER_ADDRESS") != null and
            std.posix.getenv("DBUS_STARTER_BUS_TYPE") != null,

        // No other system supports D-Bus so always return false.
        else => false,
    };
}
</file>

<file path="src/os/desktop.zig">
const std = @import("std");
const builtin = @import("builtin");
const build_config = @import("../build_config.zig");
const global = @import("../global.zig");

const c = @import("posix_c");

/// Returns true if the program was launched from a desktop environment.
///
/// On macOS, this returns true if the program was launched from Finder.
///
/// On Linux GTK, this returns true if the program was launched using the
/// desktop file. This also includes when `gtk-launch` is used because I
/// can't find a way to distinguish the two scenarios.
///
/// For other platforms and app runtimes, this returns false.
pub fn launchedFromDesktop() bool {
    return switch (builtin.os.tag) {
        // macOS apps launched from finder or `open` always have the init
        // process as their parent.
        .macos => macos: {
            // This special case is so that if we launch the app via the
            // app bundle (i.e. via open) then we still treat it as if it
            // was launched from the desktop.
            if (build_config.artifact == .lib) lib: {
                const env = "GHOSTTY_MAC_LAUNCH_SOURCE";
                const source = global.environ().getPosix(env) orelse break :lib;

                // Source can be "app", "cli", or "zig_run". We assume
                // its the desktop only if its "app". We may want to do
... (138 lines truncated)
</file>

<file path="src/os/edit.zig">
const std = @import("std");

const global = @import("../global.zig");
const ShellEscapeWriter = @import("shell.zig").ShellEscapeWriter;

const log = std.log.scoped(.os_edit);

const Options = struct {
    default_editor: enum {
        /// Return an error if $EDITOR or $VISUAL is not defined.
        failure,
        /// Default to "vi" if $EDITOR or $VISUAL is not defined.
        vi,
        /// Default to "nano" if $EDITOR or $VISUAL is not defined.
        nano,
    } = .vi,

    pub const default: Options = .{};
};

pub const Error = error{NoEditorConfigured};

pub fn getConfigEditCommand(alloc: std.mem.Allocator, path: []const u8, options: Options) (Error || std.Io.Writer.Error || std.mem.Allocator.Error)![:0]const u8 {
    const editor: []const u8 = editor: {
        // VISUAL vs. EDITOR: https://unix.stackexchange.com/questions/4859/visual-vs-editor-what-s-the-difference
        v: {
            if (global.environ().containsUnempty(alloc, "VISUAL") catch break :v) {
                break :editor global.environ().getAlloc(alloc, "VISUAL") catch break :v;
            }
        }
... (40 lines truncated)
</file>

<file path="src/os/file.zig">
const std = @import("std");
const builtin = @import("builtin");
const global = @import("../global.zig");
const posix = std.posix;
const windows = @import("windows.zig");

const log = std.log.scoped(.os);

pub const rlimit = if (@hasDecl(posix.system, "rlimit")) posix.rlimit else struct {};

/// This maximizes the number of file descriptors we can have open. We
/// need to do this because each window consumes at least a handful of fds.
/// This is extracted from the Zig compiler source code.
pub fn fixMaxFiles() ?rlimit {
    if (!@hasDecl(posix.system, "rlimit") or
        posix.system.rlimit == void) return null;

    const old = posix.getrlimit(.NOFILE) catch {
        log.warn("failed to query file handle limit, may limit max windows", .{});
        return null; // Oh well; we tried.
    };

    // If we're already at the max, we're done.
    if (old.cur >= old.max) {
        log.debug("file handle limit already maximized value={}", .{old.cur});
        return old;
    }

    // Do a binary search for the limit.
    var lim = old;
... (118 lines truncated)
</file>

<file path="src/os/flatpak.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const posix = std.posix;
const global = @import("../global.zig");
const xev = global.xev;

const log = std.log.scoped(.flatpak);

/// Returns true if we're running in a Flatpak environment.
pub fn isFlatpak() bool {
    // If we're not on Linux then we'll make this comptime false.
    if (comptime builtin.os.tag != .linux) return false;
    return if (std.Io.Dir.accessAbsolute(global.io(), "/.flatpak-info", .{}))
        true
    else |_|
        false;
}

/// A struct to help execute commands on the host via the
/// org.freedesktop.Flatpak.Development DBus module. This uses GIO/GLib
/// under the hood.
///
/// This always spawns its own thread and maintains its own GLib event loop.
/// This makes it easy for the command to behave synchronously similar to
/// std.process.Child.
///
/// There are lots of chances for low-hanging improvements here (automatic
/// pipes, /dev/null, etc.) but this was purpose built for my needs so
/// it doesn't have all of those.
... (492 lines truncated)
</file>

<file path="src/os/homedir.zig">
const std = @import("std");
const builtin = @import("builtin");
const passwd = @import("passwd.zig");
const objc = @import("objc");

const Error = error{
    /// The buffer used for output is not large enough to store the value.
    BufferTooSmall,
};

/// Determine the home directory for the currently executing user. This
/// is generally an expensive process so the value should be cached.
pub inline fn home(io: std.Io, environ_map: *const std.process.Environ.Map, buf: []u8) !?[]const u8 {
    return switch (builtin.os.tag) {
        .linux, .freebsd, .macos => try homeUnix(io, environ_map, buf),
        .windows => homeWindows(environ_map, buf) catch return error.BufferTooSmall,

        // iOS doesn't have a user-writable home directory
        .ios => null,

        else => @compileError("unimplemented"),
    };
}

fn homeUnix(io: std.Io, environ_map: *const std.process.Environ.Map, buf: []u8) !?[]const u8 {
    // First: if we have a HOME env var, then we use that.
    if (environ_map.get("HOME")) |result| {
        if (buf.len < result.len) return Error.BufferTooSmall;
        @memcpy(buf[0..result.len], result);
        return buf[0..result.len];
... (156 lines truncated)
</file>

<file path="src/os/hostname.zig">
const std = @import("std");
const builtin = @import("builtin");
const posix = std.posix;

pub const LocalHostnameValidationError = error{
    PermissionDenied,
    Unexpected,
};

/// Checks if a hostname is local to the current machine. This matches
/// both "localhost" and the current hostname of the machine (as returned
/// by `gethostname`).
pub fn isLocal(hostname: []const u8) LocalHostnameValidationError!bool {
    // A 'localhost' hostname is always considered local.
    if (std.mem.eql(u8, "localhost", hostname)) return true;

    // If hostname is not "localhost" it must match our hostname.
    switch (builtin.os.tag) {
        .windows => {
            const windows = @import("windows.zig");
            var buf: [256:0]u8 = undefined;
            var nSize: windows.DWORD = buf.len;
            if (windows.exp.kernel32.GetComputerNameA(&buf, &nSize) == windows.FALSE) return false;
            const ourHostname = buf[0..nSize];
            return std.mem.eql(u8, hostname, ourHostname);
        },
        else => {
            var buf: [posix.HOST_NAME_MAX]u8 = undefined;
            const ourHostname = try posix.gethostname(&buf);
            return std.mem.eql(u8, hostname, ourHostname);
... (34 lines truncated)
</file>

<file path="src/os/i18n_locales.zig">
// NOTE: This is in a separate file because our build depends on it and
// we want to minimize the transitive dependencies of the build binary
// itself.

/// Supported locales for the application. This must be kept up to date
/// with the translations available in the `po/` directory; this is used
/// by our build process as well as runtime libghostty APIs.
///
/// The order also matters. For incomplete locale information (i.e. only
/// a language code available), the first match is used. For example, if
/// we know the user requested `zh` but has no script code, then we'd pick
/// the first locale that matches `zh`.
///
/// For ordering, we prefer:
///
///   1. The most common locales first, since there are places in the code
///      where we do linear searches for a locale and we want to minimize
///      the number of iterations for the common case.
///
///   2. Alphabetical for otherwise equally common locales.
///
///   3. Most preferred locale for a language without a country code.
///
/// Note for "most common" locales, this is subjective and based on
/// the perceived userbase of Ghostty, which may not be representative
/// of general populations or global language distribution. Also note
/// that ordering may be weird when we first merge a new locale since
/// we don't have a good way to determine this. We can always reorder
/// with some data.
pub const locales = [_][:0]const u8{
... (36 lines truncated)
</file>

<file path="src/os/i18n.zig">
const std = @import("std");
const builtin = @import("builtin");
const build_config = @import("../build_config.zig");
const locales = @import("i18n_locales.zig");

const log = std.log.scoped(.i18n);

/// Set for faster membership lookup of locales.
pub const locales_map = map: {
    var kvs: [locales.len]struct { []const u8 } = undefined;
    for (locales, 0..) |locale, i| kvs[i] = .{locale};
    break :map std.StaticStringMap(void).initComptime(kvs);
};

pub const InitError = error{
    InvalidResourcesDir,
    OutOfMemory,
};

/// Initialize i18n support for the application. This should be
/// called automatically by the global state initialization
/// in global.zig.
///
/// This calls `bindtextdomain` for gettext with the proper directory
/// of translations. This does NOT call `textdomain` as we don't
/// want to set the domain for the entire application since this is also
/// used by libghostty.
pub fn init(resources_dir: []const u8) InitError!void {
    if (comptime !build_config.i18n) return;

... (181 lines truncated)
</file>

<file path="src/os/kernel_info.zig">
const std = @import("std");
const builtin = @import("builtin");
const global = @import("../global.zig");

pub fn getKernelInfo(alloc: std.mem.Allocator) ?[]const u8 {
    if (comptime builtin.os.tag != .linux) return null;
    const path = "/proc/sys/kernel/osrelease";
    var file = std.Io.Dir.openFileAbsolute(global.io(), path, .{}) catch return null;
    defer file.close(global.io());

    // 128 bytes should be enough to hold the kernel information
    var kernel_info_buf: [128]u8 = undefined;
    const kernel_info = kernel_info_buf[0 .. file.readPositionalAll(
        global.io(),
        &kernel_info_buf,
        0,
    ) catch return null];
    return alloc.dupe(u8, std.mem.trim(u8, kernel_info, &std.ascii.whitespace)) catch return null;
}

test "read /proc/sys/kernel/osrelease" {
    if (comptime builtin.os.tag != .linux) return null;
    const allocator = std.testing.allocator;

    const kernel_info = getKernelInfo(allocator).?;
    defer allocator.free(kernel_info);

    // Since we can't hardcode the info in tests, just check
    // if something was read from the file
    try std.testing.expect(kernel_info.len > 0);
... (3 lines truncated)
</file>

<file path="src/os/locale.c">

</file>

<file path="src/os/locale.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const macos = @import("macos");
const objc = @import("objc");
const internal_os = @import("main.zig");
const i18n = internal_os.i18n;

const log = std.log.scoped(.os_locale);

/// Ensure that the locale is set.
pub fn ensureLocale() !void {
    // This does a lot of in-process mutation of the environment and can't be
    // run in a test as a result.
    assert(!builtin.is_test);

    // On macOS, pre-populate the LANG env var with system preferences.
    // When launching the .app, LANG is not set so we must query it from the
    // OS. When launching from the CLI, LANG is usually set by the parent
    // process.
    if (comptime builtin.target.os.tag.isDarwin()) {
        // Set the lang if it is not set or if its empty.
        const lang = std.posix.system.getenv("LANG");
        if (lang == null or lang.?[0] == 0) {
            setLangFromCocoa();
        }
    }

    // Set the locale to whatever is set in env vars.
    if (setlocale(LC_ALL, "")) |v| {
... (203 lines truncated)
</file>

<file path="src/os/mach.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const mem = std.mem;
const Allocator = std.mem.Allocator;

/// macOS virtual memory tags for use with mach_vm_map/mach_vm_allocate.
/// These identify memory regions in tools like vmmap and Instruments.
pub const VMTag = enum(u8) {
    application_specific_1 = 240,
    application_specific_2 = 241,
    application_specific_3 = 242,
    application_specific_4 = 243,
    application_specific_5 = 244,
    application_specific_6 = 245,
    application_specific_7 = 246,
    application_specific_8 = 247,
    application_specific_9 = 248,
    application_specific_10 = 249,
    application_specific_11 = 250,
    application_specific_12 = 251,
    application_specific_13 = 252,
    application_specific_14 = 253,
    application_specific_15 = 254,
    application_specific_16 = 255,

    // We ignore the rest because we never realistic set them.
    _,

    /// Converts the tag to the format expected by mach_vm_map/mach_vm_allocate.
    /// Equivalent to C macro: VM_MAKE_TAG(tag)
... (124 lines truncated)
</file>

<file path="src/os/macos.zig">
const std = @import("std");
const builtin = @import("builtin");
const build_config = @import("../build_config.zig");
const assert = @import("../quirks.zig").inlineAssert;
const objc = @import("objc");
const Allocator = std.mem.Allocator;

/// Verifies that the running macOS system version is at least the given version.
pub fn isAtLeastVersion(major: i64, minor: i64, patch: i64) bool {
    comptime assert(builtin.target.os.tag.isDarwin());

    const NSProcessInfo = objc.getClass("NSProcessInfo").?;
    const info = NSProcessInfo.msgSend(objc.Object, objc.sel("processInfo"), .{});
    return info.msgSend(bool, objc.sel("isOperatingSystemAtLeastVersion:"), .{
        NSOperatingSystemVersion{ .major = major, .minor = minor, .patch = patch },
    });
}

pub const AppSupportDirError = Allocator.Error || error{AppleAPIFailed};

/// Return the path to the application support directory for Ghostty
/// with the given sub path joined. This allocates the result using the
/// given allocator.
pub fn appSupportDir(
    alloc: Allocator,
    sub_path: []const u8,
) AppSupportDirError![]const u8 {
    return try commonDir(
        alloc,
        .NSApplicationSupportDirectory,
... (145 lines truncated)
</file>

<file path="src/os/main.zig">
//! The "os" package contains utilities for interfacing with the operating
//! system. These aren't restricted to syscalls or low-level operations, butos/main.zig
//! also OS-specific features and conventions.

const builtin = @import("builtin");

const dbus = @import("dbus.zig");
const desktop = @import("desktop.zig");
const file = @import("file.zig");
const flatpak = @import("flatpak.zig");
const homedir = @import("homedir.zig");
const locale = @import("locale.zig");
const mouse = @import("mouse.zig");
const openpkg = @import("open.zig");
const pipepkg = @import("pipe.zig");
const resourcesdir = @import("resourcesdir.zig");
const systemd = @import("systemd.zig");
const kernel_info = @import("kernel_info.zig");

// Namespaces
pub const cgroup = @import("cgroup.zig");
pub const edit = @import("edit.zig");
pub const hostname = @import("hostname.zig");
pub const i18n = @import("i18n.zig");
pub const mach = @import("mach.zig");
pub const path = @import("path.zig");
pub const passwd = @import("passwd.zig");
pub const xdg = @import("xdg.zig");
pub const windows = @import("windows.zig");
pub const macos = @import("macos.zig");
... (47 lines truncated)
</file>

<file path="src/os/mouse.zig">
const std = @import("std");
const builtin = @import("builtin");
const objc = @import("objc");

const log = std.log.scoped(.os);

/// The system-configured double-click interval if its available.
pub fn clickInterval() ?u32 {
    return switch (builtin.os.tag) {
        // On macOS, we can ask the system.
        .macos => macos: {
            const NSEvent = objc.getClass("NSEvent") orelse {
                log.err("NSEvent class not found. Can't get click interval.", .{});
                return null;
            };

            // Get the interval and convert to ms
            const interval = NSEvent.msgSend(f64, objc.sel("doubleClickInterval"), .{});
            const ms = @as(u32, @intFromFloat(@ceil(interval * 1000)));
            break :macos ms;
        },

        else => null,
    };
}
</file>

<file path="src/os/open.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const build_config = @import("../build_config.zig");
const apprt = @import("../apprt.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.@"os-open");

/// Open a URL in the default handling application.
///
/// Any output on stderr is logged as a warning in the application logs.
/// Output on stdout is ignored.
///
/// This function is purposely simple for the sake of providing some portable
/// way to open URLs. If you are implementing an apprt for Ghostty, you should
/// consider doing something special-cased for your platform.
pub fn open(
    kind: apprt.action.OpenUrl.Kind,
    url: []const u8,
) !void {
    // On macOS, the apprt handles OSC 8 targets before this fallback. Ghostty's
    // native apprt applies its allowlist, confirmation, and file safety policy.
    // If a macOS embedder declines the action, fail closed rather than bypassing
    // that policy by handing producer-controlled terminal output to `open`.
    if (comptime builtin.os.tag == .macos) {
        if (kind == .osc8) return error.UnsafeOSC8Link;
    }

    var spawn_opts: std.process.SpawnOptions = switch (builtin.os.tag) {
... (76 lines truncated)
</file>

<file path="src/os/passwd.zig">
const std = @import("std");
const builtin = @import("builtin");
const internal_os = @import("main.zig");
const build_config = @import("../build_config.zig");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const posix = std.posix;
const compat_fd = @import("../lib/compat/fd.zig");

const log = std.log.scoped(.passwd);

// We want to be extra sure since this will force bad symbols into our import table
comptime {
    if (builtin.target.cpu.arch.isWasm()) {
        @compileError("passwd is not available for wasm");
    }
}

/// Used to determine the default shell and directory on Unixes.
const c = if (builtin.os.tag != .windows) @import("posix_c") else {};

// Entry that is retrieved from the passwd API. This only contains the fields
// we care about.
pub const Entry = struct {
    shell: ?[:0]const u8 = null,
    home: ?[:0]const u8 = null,
    name: ?[:0]const u8 = null,
};

/// Get the passwd entry for the currently executing user.
... (125 lines truncated)
</file>

<file path="src/os/path.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const testing = std.testing;

/// Search for "cmd" in the PATH and return the absolute path. This will
/// always allocate if there is a non-null result. The caller must free the
/// resulting value.
pub fn expand(
    io: std.Io,
    alloc: Allocator,
    environ_map: *const std.process.Environ.Map,
    cmd: []const u8,
) !?[]u8 {
    // If the command already contains a slash, then we return it as-is
    // because it is assumed to be absolute or relative.
    if (std.mem.indexOfScalar(u8, cmd, '/') != null) {
        return try alloc.dupe(u8, cmd);
    }

    const PATH = environ_map.get("PATH") orelse return null;

    var path_buf: [std.fs.max_path_bytes]u8 = undefined;
    var it = std.mem.tokenizeScalar(u8, PATH, std.fs.path.delimiter);
    var seen_eacces = false;
    while (it.next()) |search_path| {
        // We need enough space in our path buffer to store this
        const path_len = search_path.len + cmd.len + 1;
        if (path_buf.len < path_len) return error.PathTooLong;

... (71 lines truncated)
</file>

<file path="src/os/pipe.zig">
const std = @import("std");
const builtin = @import("builtin");
const windows = @import("windows.zig");
const posix = std.posix;
const compat_fd = @import("../lib/compat/fd.zig");

/// pipe() that works on Windows and POSIX. For POSIX systems, this sets
/// CLOEXEC on the file descriptors.
pub fn pipe() ![2]posix.fd_t {
    switch (builtin.os.tag) {
        else => return compat_fd.pipe2(.{ .CLOEXEC = true }),
        .windows => {
            var read: windows.HANDLE = undefined;
            var write: windows.HANDLE = undefined;
            if (windows.exp.kernel32.CreatePipe(&read, &write, null, 0) == windows.FALSE) {
                return windows.unexpectedError(windows.GetLastError());
            }

            return .{ read, write };
        },
    }
}
</file>

<file path="src/os/resourcesdir.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const global = @import("../global.zig");

pub const ResourcesDir = struct {
    /// Avoid accessing these directly, use the app() and host() methods instead.
    app_path: ?[]const u8 = null,
    host_path: ?[]const u8 = null,

    /// Free resources held. Requires the same allocator as when resourcesDir()
    /// is called.
    pub fn deinit(self: *ResourcesDir, alloc: Allocator) void {
        if (self.app_path) |p| alloc.free(p);
        if (self.host_path) |p| alloc.free(p);
    }

    /// Get the directory to the bundled resources directory accessible
    /// by the application.
    pub fn app(self: *const ResourcesDir) ?[]const u8 {
        return self.app_path;
    }

    /// Get the directory to the bundled resources directory accessible
    /// by the host environment (i.e. for sandboxed applications). The
    /// returned directory might not be accessible from the application
    /// itself.
    ///
    /// In non-sandboxed environment, this should be the same as app().
    pub fn host(self: *const ResourcesDir) ?[]const u8 {
... (119 lines truncated)
</file>

<file path="src/os/shell.zig">
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const Writer = std.Io.Writer;

/// Builder for constructing space-separated shell command strings.
/// Uses a caller-provided allocator (typically with stackFallback).
pub const ShellCommandBuilder = struct {
    buffer: std.Io.Writer.Allocating,

    pub fn init(allocator: Allocator) ShellCommandBuilder {
        return .{ .buffer = .init(allocator) };
    }

    pub fn deinit(self: *ShellCommandBuilder) void {
        self.buffer.deinit();
    }

    /// Append an argument to the command with automatic space separation.
    pub fn appendArg(self: *ShellCommandBuilder, arg: []const u8) (Allocator.Error || Writer.Error)!void {
        if (arg.len == 0) return;
        if (self.buffer.written().len > 0) {
            try self.buffer.writer.writeByte(' ');
        }
        try self.buffer.writer.writeAll(arg);
    }

    /// Get the final null-terminated command string, transferring ownership to caller.
    /// Calling deinit() after this is safe but unnecessary.
    pub fn toOwnedSlice(self: *ShellCommandBuilder) Allocator.Error![:0]const u8 {
... (167 lines truncated)
</file>

<file path="src/os/stderr.zig">
//! Raw, best-effort stderr writing that bypasses `std.Io` entirely.
//!
//! `std.debug.lockStderr` (and everything layered on top of it) routes
//! through `std.Options.debug_io`, whose default implementation is
//! `std.Io.Threaded`. This keeps ~70KB of unreachable code in binaries.

const std = @import("std");
const builtin = @import("builtin");

/// Write bytes to stderr using the most primitive mechanism available
/// for the target. This is best-effort: errors are ignored, since this
/// is only used for diagnostics (logging and panic messages).
///
/// Freestanding targets (e.g. wasm) have no stderr, so this is a no-op
/// there.
pub fn write(bytes: []const u8) void {
    switch (builtin.os.tag) {
        .freestanding, .other => {},

        .windows => {
            const windows = std.os.windows;
            const handle = windows.peb().ProcessParameters.hStdError;
            var iosb: windows.IO_STATUS_BLOCK = undefined;
            _ = windows.ntdll.NtWriteFile(
                handle,
                null, // event
                null, // APC routine
                null, // APC context
                &iosb,
                bytes.ptr,
... (31 lines truncated)
</file>

<file path="src/os/string_encoding.zig">
const std = @import("std");

/// Decode date from the buffer that has been encoded in the same way that
/// `bash`'s `printf %q` encodes a string and write it to the writer. If an
/// error is returned garbage may have been written to the buffer.
pub fn printfQDecode(writer: *std.Io.Writer, buf: []const u8) (std.Io.Writer.Error || error{DecodeError})!void {
    const data: []const u8 = data: {
        // Strip off `$''` quoting.
        if (std.mem.startsWith(u8, buf, "$'")) {
            if (buf.len < 3 or !std.mem.endsWith(u8, buf, "'")) return error.DecodeError;
            break :data buf[2 .. buf.len - 1];
        }
        // Strip off `''` quoting.
        if (std.mem.startsWith(u8, buf, "'")) {
            if (buf.len < 2 or !std.mem.endsWith(u8, buf, "'")) return error.DecodeError;
            break :data buf[1 .. buf.len - 1];
        }
        break :data buf;
    };

    var src: usize = 0;

    while (src < data.len) {
        switch (data[src]) {
            else => {
                try writer.writeByte(data[src]);
                src += 1;
            },
            '\\' => {
                if (src + 1 >= data.len) return error.DecodeError;
... (278 lines truncated)
</file>

<file path="src/os/systemd.zig">
const std = @import("std");
const builtin = @import("builtin");
const global = @import("../global.zig");

const log = std.log.scoped(.systemd);

/// Returns true if the program was launched as a systemd service.
///
/// On Linux, this returns true if the program was launched as a systemd
/// service. It will return false if Ghostty was launched any other way.
///
/// For other platforms and app runtimes, this returns false.
pub fn launchedBySystemd() bool {
    return switch (builtin.os.tag) {
        .linux => linux: {
            // On Linux, systemd sets the `INVOCATION_ID` (v232+) and the
            // `JOURNAL_STREAM` (v231+) environment variables. If these
            // environment variables are not present we were not launched by
            // systemd.
            if (global.environ().getPosix("INVOCATION_ID") == null) break :linux false;
            if (global.environ().getPosix("JOURNAL_STREAM") == null) break :linux false;

            // If `INVOCATION_ID` and `JOURNAL_STREAM` are present, check to make sure
            // that our parent process is actually `systemd`, not some other terminal
            // emulator that doesn't clean up those environment variables.
            const ppid = std.os.linux.getppid();
            if (ppid == 1) break :linux true;

            // If the parent PID is not 1 we need to check to see if we were launched by
            // a user systemd daemon. Do that by checking the `/proc/<ppid>/comm`
... (171 lines truncated)
</file>

<file path="src/os/TempDir.zig">
//! Creates a temporary directory at runtime that can be safely used to
//! store temporary data and is destroyed on deinit.
const TempDir = @This();

const std = @import("std");
const Dir = std.Io.Dir;
const file = @import("file.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.tempdir);

/// Dir is the directory handle
dir: Dir,

/// Parent directory
parent: Dir,

/// Name buffer that name points into. Generally do not use. To get the
/// name call the name() function.
name_buf: [file.random_basename_len:0]u8,

/// Create the temporary directory.
pub fn init() !TempDir {
    // Note: the tmp_path_buf sentinel is important because it ensures
    // we actually always have random_basename_len+1 bytes of available
    // space. We need that so we can set the sentinel in the case we use
    // all the possible length.
    var tmp_path_buf: [file.random_basename_len:0]u8 = undefined;

    const dir = dir: {
... (100 lines truncated)
</file>

<file path="src/os/uri.zig">
const std = @import("std");

pub const ParseOptions = struct {
    /// Parse MAC addresses in the host component.
    ///
    /// This is useful when the "Private Wi-Fi address" is enabled on macOS,
    /// which sets the hostname to a rotating MAC address (12:34:56:ab:cd:ef).
    mac_address: bool = false,

    /// Return the full, raw, unencoded path string. Any query and fragment
    /// values will be return as part of the path instead of as distinct
    /// fields.
    raw_path: bool = false,
};

pub const ParseError = std.Uri.ParseError || error{InvalidMacAddress};

/// Parses a URI from the given string.
///
/// This extends std.Uri.parse with some additional ParseOptions.
pub fn parse(text: []const u8, options: ParseOptions) ParseError!std.Uri {
    var uri = std.Uri.parse(text) catch |err| uri: {
        // We can attempt to re-parse the text as a URI that has a MAC address
        // in its host field (which tripped up std.Uri.parse's port parsing):
        //
        //      file://12:34:56:78:90:aa/path/to/file
        //                            ^^ InvalidPort
        //
        if (err != error.InvalidPort or !options.mac_address) return err;

... (175 lines truncated)
</file>

<file path="src/os/wasm.zig">
//! This file contains helpers for wasm compilation.
const std = @import("std");
const builtin = @import("builtin");
const options = @import("build_options");

comptime {
    if (!builtin.target.cpu.arch.isWasm()) {
        @compileError("wasm.zig should only be analyzed for wasm32 builds");
    }
}

/// True if we're in shared memory mode. If true, then the memory buffer
/// in JS will be backed by a SharedArrayBuffer and some behaviors change.
pub const shared_mem = options.wasm_shared;

/// The allocator to use in wasm environments.
///
/// The return values of this should NOT be sent to the host environment
/// unless toHostOwned is called on them. In this case, the caller is expected
/// to call free. If a pointer is NOT host-owned, then the wasm module is
/// expected to call the normal alloc.free/destroy functions.
pub const alloc = if (builtin.is_test)
    std.testing.allocator
else
    std.heap.wasm_allocator;
</file>

<file path="src/os/windows.zig">
const std = @import("std");
const windows = std.os.windows;

// NOTE: The Windows part of the Zig stdlib is currently in the process of
// having most of its features removed, with the ultimate goal of switching to
// serve as a support for higher-level functionality offered in places like
// `std.Io` only. As such this file serves as a "bridge" between type
// information (mostly coming from stdlib) and manually-defined constants and
// external functions.

// Utility functions
pub const GetCurrentProcessId = windows.GetCurrentProcessId;
pub const GetLastError = windows.GetLastError;
pub const unexpectedError = windows.unexpectedError;
pub const unexpectedStatus = windows.unexpectedStatus;

// Primitive types
pub const BOOL = windows.BOOL;
pub const COORD = windows.COORD;
pub const DWORD = windows.DWORD;
pub const DWORD_PTR = windows.DWORD_PTR;
pub const HANDLE = windows.HANDLE;
pub const HINSTANCE = windows.HINSTANCE;
pub const HPCON = windows.LPVOID;
pub const HRESULT = c_long;
pub const LARGE_INTEGER = windows.LARGE_INTEGER;
pub const LPCWSTR = windows.LPCWSTR;
pub const LPSTR = windows.LPSTR;
pub const LPVOID = windows.LPVOID;
pub const LPWSTR = windows.LPWSTR;
... (349 lines truncated)
</file>

<file path="src/os/xdg.zig">
//! Implementation of the XDG Base Directory specification
//! (https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html)

const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const posix = std.posix;
const homedir = @import("homedir.zig");

pub const Options = struct {
    /// Subdirectories to join to the base. This avoids extra allocations
    /// when building up the directory. This is commonly the application.
    subdir: ?[]const u8 = null,

    /// The home directory for the user. If this is not set, we will attempt
    /// to look it up which is an expensive process. By setting this, you can
    /// avoid lookups.
    home: ?[]const u8 = null,
};

/// Get the XDG user config directory. The returned value is allocated.
pub fn config(io: std.Io, alloc: Allocator, environ_map: *const std.process.Environ.Map, opts: Options) ![]u8 {
    return try dir(io, alloc, environ_map, opts, .{
        .env = "XDG_CONFIG_HOME",
        .windows_env = "LOCALAPPDATA",
        .default_subdir = ".config",
    });
}

/// Get the XDG cache directory. The returned value is allocated.
... (240 lines truncated)
</file>

<file path="src/renderer/metal/api.zig">
//! This file contains the definitions of the Metal API that we use.
//!
//! Because the online Apple developer docs have recently (as of January 2025)
//! been changed to hide enum values, `Metal-cpp` has been used as a reference
//! source instead.
//!
//! Ref: https://developer.apple.com/metal/cpp/

/// https://developer.apple.com/documentation/metal/mtlcommandbufferstatus?language=objc
pub const MTLCommandBufferStatus = enum(c_ulong) {
    not_enqueued = 0,
    enqueued = 1,
    committed = 2,
    scheduled = 3,
    completed = 4,
    @"error" = 5,
    _,
};

/// https://developer.apple.com/documentation/metal/mtlloadaction?language=objc
pub const MTLLoadAction = enum(c_ulong) {
    dont_care = 0,
    load = 1,
    clear = 2,
};

/// https://developer.apple.com/documentation/metal/mtlstoreaction?language=objc
pub const MTLStoreAction = enum(c_ulong) {
    dont_care = 0,
    store = 1,
... (418 lines truncated)
</file>

<file path="src/renderer/metal/buffer.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const objc = @import("objc");
const macos = @import("macos");

const mtl = @import("api.zig");
const Metal = @import("../Metal.zig");

const log = std.log.scoped(.metal);

/// Options for initializing a buffer.
pub const Options = struct {
    /// MTLDevice
    device: objc.Object,
    resource_options: mtl.MTLResourceOptions,
};

/// Metal data storage for a certain set of equal types. This is usually
/// used for vertex buffers, etc. This helpful wrapper makes it easy to
/// prealloc, shrink, grow, sync, buffers with Metal.
pub fn Buffer(comptime T: type) type {
    return struct {
        const Self = @This();

        /// The options this buffer was initialized with.
        opts: Options,

        /// The underlying MTLBuffer object.
        buffer: objc.Object,

... (156 lines truncated)
</file>

<file path="src/renderer/metal/Device.zig">
//! The Metal device context.
//!
//! This holds the MTLDevice and metadata derived from it.
//! The device is shared by all surface renderers; each renderer
//! creates its own MTLCommandQueue.
const Device = @This();

const std = @import("std");
const builtin = @import("builtin");
const objc = @import("objc");

const mtl = @import("api.zig");
const shaders = @import("shaders.zig");

const log = std.log.scoped(.metal);

/// MTLDevice
device: objc.Object,

/// The default storage mode to use for resources created with our device.
///
/// This is based on whether the device is a discrete GPU or not, since
/// discrete GPUs do not have unified memory and therefore do not support
/// the "shared" storage mode, instead we have to use the "managed" mode.
default_storage_mode: mtl.MTLResourceOptions.StorageMode,

/// The maximum 2D texture width and height supported by the device.
max_texture_size: u32,

pub fn init(self: *Device, alloc: std.mem.Allocator) !void {
... (120 lines truncated)
</file>

<file path="src/renderer/metal/Frame.zig">
//! Wrapper for handling render passes.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const objc = @import("objc");

const mtl = @import("api.zig");
const Renderer = @import("../generic.zig").Renderer(Metal);
const Metal = @import("../Metal.zig");
const Target = @import("Target.zig");
const RenderPass = @import("RenderPass.zig");

const Health = @import("../../renderer.zig").Health;

const log = std.log.scoped(.metal);

/// Options for beginning a frame.
pub const Options = struct {
    /// MTLCommandQueue
    queue: objc.Object,
};

/// MTLCommandBuffer
buffer: objc.Object,

block: CompletionBlock.Context,

/// Begin encoding a frame.
pub fn begin(
... (102 lines truncated)
</file>

<file path="src/renderer/metal/IOSurfaceLayer.zig">
//! A wrapper around a CALayer with a utility method
//! for settings its `contents` to an IOSurface.
const IOSurfaceLayer = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const objc = @import("objc");
const macos = @import("macos");

const IOSurface = macos.iosurface.IOSurface;

const log = std.log.scoped(.IOSurfaceLayer);

/// We subclass CALayer with a custom display handler, we only need
/// to make the subclass once, and then we can use it as a singleton.
var Subclass: ?objc.Class = null;

/// The underlying CALayer
layer: objc.Object,

pub fn init() !IOSurfaceLayer {
    // The layer returned by `[CALayer layer]` is autoreleased, which means
    // that at the end of the current autorelease pool it will be deallocated
    // if it isn't retained, so we retain it here manually an extra time.
    const layer = (try getSubclass()).msgSend(
        objc.Object,
        objc.sel("layer"),
        .{},
    ).retain();
    errdefer layer.release();
... (158 lines truncated)
</file>

<file path="src/renderer/metal/Pipeline.zig">
//! Wrapper for handling render pipelines.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const macos = @import("macos");
const objc = @import("objc");

const mtl = @import("api.zig");

const log = std.log.scoped(.metal);

/// Options for initializing a render pipeline.
pub const Options = struct {
    /// MTLDevice
    device: objc.Object,

    /// Name of the vertex function
    vertex_fn: []const u8,
    /// Name of the fragment function
    fragment_fn: []const u8,

    /// MTLLibrary to get the vertex function from
    vertex_library: objc.Object,
    /// MTLLibrary to get the fragment function from
    fragment_library: objc.Object,

    /// Vertex step function
    step_fn: mtl.MTLVertexStepFunction = .per_vertex,

... (175 lines truncated)
</file>

<file path="src/renderer/metal/RenderPass.zig">
//! Wrapper for handling render passes.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const objc = @import("objc");

const mtl = @import("api.zig");
const Pipeline = @import("Pipeline.zig");
const Sampler = @import("Sampler.zig");
const Texture = @import("Texture.zig");
const Target = @import("Target.zig");

const log = std.log.scoped(.metal);

/// Options for beginning a render pass.
pub const Options = struct {
    /// MTLCommandBuffer
    command_buffer: objc.Object,
    /// Color attachments for this render pass.
    attachments: []const Attachment,

    /// Describes a color attachment.
    pub const Attachment = struct {
        target: union(enum) {
            texture: Texture,
            target: Target,
        },
        clear_color: ?[4]f64 = null,
    };
... (200 lines truncated)
</file>

<file path="src/renderer/metal/Sampler.zig">
//! Wrapper for handling samplers.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const objc = @import("objc");

const mtl = @import("api.zig");
const Metal = @import("../Metal.zig");

const log = std.log.scoped(.metal);

/// Options for initializing a sampler.
pub const Options = struct {
    /// MTLDevice
    device: objc.Object,
    min_filter: mtl.MTLSamplerMinMagFilter,
    mag_filter: mtl.MTLSamplerMinMagFilter,
    s_address_mode: mtl.MTLSamplerAddressMode,
    t_address_mode: mtl.MTLSamplerAddressMode,
};

/// The underlying MTLSamplerState Object.
sampler: objc.Object,

pub const Error = error{
    /// A Metal API call failed.
    MetalFailed,
};

... (35 lines truncated)
</file>

<file path="src/renderer/metal/shaders.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const macos = @import("macos");
const objc = @import("objc");
const math = @import("../../math.zig");
const global = @import("../../global.zig");

const mtl = @import("api.zig");
const Pipeline = @import("Pipeline.zig");

const log = std.log.scoped(.metal);

const pipeline_descs: []const struct { [:0]const u8, PipelineDescription } =
    &.{
        .{ "bg_color", .{
            .vertex_fn = "full_screen_vertex",
            .fragment_fn = "bg_color_fragment",
            .blending_enabled = false,
        } },
        .{ "cell_bg", .{
            .vertex_fn = "full_screen_vertex",
            .fragment_fn = "cell_bg_fragment",
            .blending_enabled = true,
        } },
        .{ "cell_text", .{
            .vertex_attributes = CellText,
            .vertex_fn = "cell_text_vertex",
            .fragment_fn = "cell_text_fragment",
            .step_fn = .per_instance,
            .blending_enabled = true,
... (426 lines truncated)
</file>

<file path="src/renderer/metal/Target.zig">
//! Represents a render target.
//!
//! In this case, an IOSurface-backed MTLTexture.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const objc = @import("objc");
const macos = @import("macos");
const graphics = macos.graphics;
const IOSurface = macos.iosurface.IOSurface;

const mtl = @import("api.zig");

const log = std.log.scoped(.metal);

/// Options for initializing a Target
pub const Options = struct {
    /// MTLDevice
    device: objc.Object,

    /// Desired width
    width: usize,
    /// Desired height
    height: usize,

    /// Pixel format for the MTLTexture
    pixel_format: mtl.MTLPixelFormat,
    /// Storage mode for the MTLTexture
    storage_mode: mtl.MTLResourceOptions.StorageMode,
... (79 lines truncated)
</file>

<file path="src/renderer/metal/Texture.zig">
//! Wrapper for handling textures.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../../quirks.zig").inlineAssert;
const objc = @import("objc");

const mtl = @import("api.zig");
const Metal = @import("../Metal.zig");

const log = std.log.scoped(.metal);

/// Options for initializing a texture.
pub const Options = struct {
    /// MTLDevice
    device: objc.Object,
    pixel_format: mtl.MTLPixelFormat,
    resource_options: mtl.MTLResourceOptions,
    usage: mtl.MTLTextureUsage,
};

/// The underlying MTLTexture Object.
texture: objc.Object,

/// The width of this texture.
width: usize,
/// The height of this texture.
height: usize,

... (173 lines truncated)
</file>

<file path="src/renderer/opengl/buffer.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");

const OpenGL = @import("../OpenGL.zig");

const log = std.log.scoped(.opengl);

/// Options for initializing a buffer.
pub const Options = struct {
    target: gl.Buffer.Target = .array,
    usage: gl.Buffer.Usage = .dynamic_draw,
};

/// OpenGL data storage for a certain set of equal types. This is usually
/// used for vertex buffers, etc. This helpful wrapper makes it easy to
/// prealloc, shrink, grow, sync, buffers with OpenGL.
pub fn Buffer(comptime T: type) type {
    return struct {
        const Self = @This();

        /// Underlying `gl.Buffer` instance.
        buffer: gl.Buffer,

        /// Options this buffer was allocated with.
        opts: Options,

        /// Current allocated length of the data store.
        /// Note this is the number of `T`s, not the size in bytes.
        len: usize,
... (97 lines truncated)
</file>

<file path="src/renderer/opengl/Device.zig">
//! The OpenGL device context.
//!
//! This holds the EGL display and config used to create EGL
//! contexts, each corresponding to a surface, its renderer
//! object and its render thread.
//!
//! TODO: If there's a way to prefer certain devices like in
//! Vulkan or Metal we should do it here.
const Device = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");
const egl = gl.egl;

const log = std.log.scoped(.opengl);

/// The EGL display.
///
/// Since we use the default display, this is torn down
/// automagically by the OS.
display: *egl.Display,

/// The EGL config used to create surface renderer contexts. Chosen
/// once here so that all contexts share compatible capabilities.
config: *egl.Config,

pub fn init(self: *Device, alloc: Allocator) !void {
    _ = alloc;

... (67 lines truncated)
</file>

<file path="src/renderer/opengl/Frame.zig">
//! Wrapper for handling render passes.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");

const global = @import("../../global.zig");
const Renderer = @import("../generic.zig").Renderer(OpenGL);
const OpenGL = @import("../OpenGL.zig");
const Target = @import("Target.zig");
const RenderPass = @import("RenderPass.zig");

const Health = @import("../../renderer.zig").Health;

const log = std.log.scoped(.opengl);

/// Options for beginning a frame.
pub const Options = struct {};

renderer: *Renderer,
target: *Target,

/// Begin encoding a frame.
pub fn begin(
    opts: Options,
    /// Once the frame has been completed, the `frameCompleted` method
    /// on the renderer is called with the health status of the frame.
    renderer: *Renderer,
    /// The target is presented via the provided renderer's API when completed.
... (61 lines truncated)
</file>

<file path="src/renderer/opengl/Pipeline.zig">
//! Wrapper for handling render pipelines.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");

const log = std.log.scoped(.opengl);

/// Options for initializing a render pipeline.
pub const Options = struct {
    /// GLSL source of the vertex function
    vertex_fn: [:0]const u8,
    /// GLSL source of the fragment function
    fragment_fn: [:0]const u8,

    /// Vertex step function
    step_fn: StepFunction = .per_vertex,

    /// Whether to enable blending.
    blending_enabled: bool = true,

    pub const StepFunction = enum {
        constant,
        per_vertex,
        per_instance,
    };
};

program: gl.Program,
... (135 lines truncated)
</file>

<file path="src/renderer/opengl/RenderPass.zig">
//! Wrapper for handling render passes.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");

const Sampler = @import("Sampler.zig");
const Target = @import("Target.zig");
const Texture = @import("Texture.zig");
const Pipeline = @import("Pipeline.zig");
const Buffer = @import("buffer.zig").Buffer;

/// Options for beginning a render pass.
pub const Options = struct {
    /// Color attachments for this render pass.
    attachments: []const Attachment,

    /// Describes a color attachment.
    pub const Attachment = struct {
        target: union(enum) {
            texture: Texture,
            target: Target,
        },
        clear_color: ?[4]f32 = null,
    };
};

/// Describes a step in a render pass.
pub const Step = struct {
... (115 lines truncated)
</file>

<file path="src/renderer/opengl/Sampler.zig">
//! Wrapper for handling samplers.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");

const OpenGL = @import("../OpenGL.zig");

const log = std.log.scoped(.opengl);

/// Options for initializing a sampler.
pub const Options = struct {
    min_filter: gl.Texture.MinFilter,
    mag_filter: gl.Texture.MagFilter,
    wrap_s: gl.Texture.Wrap,
    wrap_t: gl.Texture.Wrap,
};

sampler: gl.Sampler,

pub const Error = error{
    /// An OpenGL API call failed.
    OpenGLFailed,
};

/// Initialize a sampler
pub fn init(
    opts: Options,
) Error!Self {
... (16 lines truncated)
</file>

<file path="src/renderer/opengl/shaders.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../../quirks.zig").inlineAssert;
const math = @import("../../math.zig");

const Pipeline = @import("Pipeline.zig");

const log = std.log.scoped(.opengl);

const pipeline_descs: []const struct { [:0]const u8, PipelineDescription } =
    &.{
        .{ "bg_color", .{
            .vertex_fn = loadShaderCode("../shaders/glsl/full_screen.v.glsl"),
            .fragment_fn = loadShaderCode("../shaders/glsl/bg_color.f.glsl"),
            .blending_enabled = false,
        } },
        .{ "cell_bg", .{
            .vertex_fn = loadShaderCode("../shaders/glsl/full_screen.v.glsl"),
            .fragment_fn = loadShaderCode("../shaders/glsl/cell_bg.f.glsl"),
            .blending_enabled = true,
        } },
        .{ "cell_text", .{
            .vertex_attributes = CellText,
            .vertex_fn = loadShaderCode("../shaders/glsl/cell_text.v.glsl"),
            .fragment_fn = loadShaderCode("../shaders/glsl/cell_text.f.glsl"),
            .step_fn = .per_instance,
            .blending_enabled = true,
        } },
        .{ "image", .{
            .vertex_attributes = Image,
... (347 lines truncated)
</file>

<file path="src/renderer/opengl/Target.zig">
//! Represents a render target.
//!
//! In this case, a texture-backed framebuffer. The color attachment is a
//! `GL_TEXTURE_2D` texture instead of a renderbuffer so that we can create
//! an EGLImage from it and export the rendered frame as a dma-buf for
//! presentation by the apprt.
//!
//! We use two textures:
//!
//!   - `texture`: `GL_SRGB8_ALPHA8`. We render to this. With
//!     `GL_FRAMEBUFFER_SRGB` enabled, the GPU automatically converts linear
//!     shader output to sRGB on write. This is required for the
//!     linear-blending color pipeline to produce correct output.
//!
//!   - `export_texture`: `GL_RGBA8`. This is the texture we actually export
//!     as a dma-buf. Mesa cannot export `GL_SRGB8_ALPHA8` textures to
//!     dma-buf, so we blit the rendered sRGB texture into this plain RGBA8
//!     texture (the blit copies the already-sRGB-encoded pixel values
//!     verbatim) and export that instead.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");
const egl = gl.egl;
const Dmabuf = @import("../Dmabuf.zig");

const log = std.log.scoped(.opengl);

/// Options for initializing a Target
... (213 lines truncated)
</file>

<file path="src/renderer/opengl/Texture.zig">
//! Wrapper for handling textures.
const Self = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");

const OpenGL = @import("../OpenGL.zig");

const log = std.log.scoped(.opengl);

/// Options for initializing a texture.
pub const Options = struct {
    format: gl.Texture.Format,
    internal_format: gl.Texture.InternalFormat,
    target: gl.Texture.Target,
    min_filter: gl.Texture.MinFilter,
    mag_filter: gl.Texture.MagFilter,
    wrap_s: gl.Texture.Wrap,
    wrap_t: gl.Texture.Wrap,
};

texture: gl.Texture,

/// The width of this texture.
width: usize,
/// The height of this texture.
height: usize,

/// Format for this texture.
... (75 lines truncated)
</file>

<file path="src/renderer/shaders/glsl/bg_color.f.glsl">
#include "common.glsl"

// Must declare this output for some versions of OpenGL.
layout(location = 0) out vec4 out_FragColor;

void main() {
    bool use_linear_blending = (bools & USE_LINEAR_BLENDING) != 0;

    out_FragColor = load_color(
            unpack4u8(bg_color_packed_4u8),
            use_linear_blending
        );
}
</file>

<file path="src/renderer/shaders/glsl/bg_image.f.glsl">
#include "common.glsl"

// Position the FragCoord origin to the upper left
// so as to align with our texture's directionality.
layout(origin_upper_left) in vec4 gl_FragCoord;

layout(binding = 0) uniform sampler2D image;

flat in vec4 bg_color;
flat in vec2 offset;
flat in vec2 scale;
flat in float opacity;
flat in uint repeat;

layout(location = 0) out vec4 out_FragColor;

void main() {
    bool use_linear_blending = (bools & USE_LINEAR_BLENDING) != 0;

    // Our texture coordinate is based on the screen position, offset by the
    // dest rect origin, and scaled by the ratio between the dest rect size
    // and the original texture size, which effectively scales the original
    // size of the texture to the dest rect size.
    vec2 tex_coord = (gl_FragCoord.xy - offset) * scale;

    vec2 tex_size = textureSize(image, 0);

    // If we need to repeat the texture, wrap the coordinates.
    if (repeat != 0) {
        tex_coord = mod(mod(tex_coord, tex_size) + tex_size, tex_size);
... (34 lines truncated)
</file>

<file path="src/renderer/shaders/glsl/bg_image.v.glsl">
#include "common.glsl"

layout(binding = 0) uniform sampler2D image;

layout(location = 0) in float in_opacity;
layout(location = 1) in uint info;

// 4 bits of info.
const uint BG_IMAGE_POSITION = 15u;
const uint BG_IMAGE_TL = 0u;
const uint BG_IMAGE_TC = 1u;
const uint BG_IMAGE_TR = 2u;
const uint BG_IMAGE_ML = 3u;
const uint BG_IMAGE_MC = 4u;
const uint BG_IMAGE_MR = 5u;
const uint BG_IMAGE_BL = 6u;
const uint BG_IMAGE_BC = 7u;
const uint BG_IMAGE_BR = 8u;

// 2 bits of info shifted 4.
const uint BG_IMAGE_FIT = 3u << 4;
const uint BG_IMAGE_CONTAIN = 0u << 4;
const uint BG_IMAGE_COVER = 1u << 4;
const uint BG_IMAGE_STRETCH = 2u << 4;
const uint BG_IMAGE_NO_FIT = 3u << 4;

// 1 bit of info shifted 6.
const uint BG_IMAGE_REPEAT = 1u << 6;

flat out vec4 bg_color;
... (116 lines truncated)
</file>

<file path="src/renderer/shaders/glsl/cell_bg.f.glsl">
#include "common.glsl"

// Position the origin to the upper left
layout(origin_upper_left) in vec4 gl_FragCoord;

// Must declare this output for some versions of OpenGL.
layout(location = 0) out vec4 out_FragColor;

layout(binding = 1, std430) readonly buffer bg_cells {
    uint cells[];
};

vec4 cell_bg() {
    uvec2 grid_size = unpack2u16(grid_size_packed_2u16);
    ivec2 grid_pos = ivec2(floor((gl_FragCoord.xy - grid_padding.wx) / cell_size));
    bool use_linear_blending = (bools & USE_LINEAR_BLENDING) != 0;

    vec4 bg = vec4(0.0);

    // Clamp x position, extends edge bg colors in to padding on sides.
    if (grid_pos.x < 0) {
        if ((padding_extend & EXTEND_LEFT) != 0) {
            grid_pos.x = 0;
        } else {
            return bg;
        }
    } else if (grid_pos.x > grid_size.x - 1) {
        if ((padding_extend & EXTEND_RIGHT) != 0) {
            grid_pos.x = int(grid_size.x) - 1;
        } else {
... (32 lines truncated)
</file>

<file path="src/renderer/shaders/glsl/cell_text.f.glsl">
#include "common.glsl"

layout(binding = 0) uniform sampler2DRect atlas_grayscale;
layout(binding = 1) uniform sampler2DRect atlas_color;

in CellTextVertexOut {
    flat uint atlas;
    flat vec4 color;
    flat vec4 bg_color;
    vec2 tex_coord;
} in_data;

// Values `atlas` can take.
const uint ATLAS_GRAYSCALE = 0u;
const uint ATLAS_COLOR = 1u;

// Must declare this output for some versions of OpenGL.
layout(location = 0) out vec4 out_FragColor;

void main() {
    bool use_linear_blending = (bools & USE_LINEAR_BLENDING) != 0;
    bool use_linear_correction = (bools & USE_LINEAR_CORRECTION) != 0;

    switch (in_data.atlas) {
        default:
        case ATLAS_GRAYSCALE:
        {
            // Our input color is always linear.
            vec4 color = in_data.color;

... (71 lines truncated)
</file>

<file path="src/renderer/shaders/glsl/cell_text.v.glsl">
#include "common.glsl"

// The position of the glyph in the texture (x, y)
layout(location = 0) in uvec2 glyph_pos;

// The size of the glyph in the texture (w, h)
layout(location = 1) in uvec2 glyph_size;

// The left and top bearings for the glyph (x, y)
layout(location = 2) in ivec2 bearings;

// The grid coordinates (x, y) where x < columns and y < rows
layout(location = 3) in uvec2 grid_pos;

// The color of the rendered text glyph.
layout(location = 4) in uvec4 color;

// Which atlas this glyph is in.
layout(location = 5) in uint atlas;

// Misc glyph properties.
layout(location = 6) in uint glyph_bools;

// Values `atlas` can take.
const uint ATLAS_GRAYSCALE = 0u;
const uint ATLAS_COLOR = 1u;

// Masks for the `glyph_bools` attribute
const uint NO_MIN_CONTRAST = 1u;
const uint IS_CURSOR_GLYPH = 2u;
... (117 lines truncated)
</file>

<file path="src/renderer/shaders/glsl/common.glsl">
#version 430 core

// These are common definitions to be shared across shaders, the first
// line of any shader that needs these should be `#include "common.glsl"`.
//
// Included in this file are:
// - The interface block for the global uniforms.
// - Functions for unpacking values.
// - Functions for working with colors.

//----------------------------------------------------------------------------//
// Global Uniforms
//----------------------------------------------------------------------------//
layout(binding = 1, std140) uniform Globals {
    uniform mat4 projection_matrix;
    uniform vec2 screen_size;
    uniform vec2 cell_size;
    uniform uint grid_size_packed_2u16;
    uniform vec4 grid_padding;
    uniform uint padding_extend;
    uniform float min_contrast;
    uniform uint cursor_pos_packed_2u16;
    uniform uint cursor_color_packed_4u8;
    uniform uint bg_color_packed_4u8;
    uniform uint bools;
};

// Bools
const uint CURSOR_WIDE = 1u;
const uint USE_DISPLAY_P3 = 2u;
... (127 lines truncated)
</file>

<file path="src/renderer/shaders/glsl/full_screen.v.glsl">
#version 330 core

void main() {
  vec4 position;
  position.x = (gl_VertexID == 2) ? 3.0 : -1.0;
  position.y = (gl_VertexID == 0) ? -3.0 : 1.0;
  position.z = 1.0;
  position.w = 1.0;

  // Single triangle is clipped to viewport.
  //
  // X <- vid == 0: (-1, -3)
  // |\
  // | \
  // |  \
  // |###\
  // |#+# \ `+` is (0, 0). `#`s are viewport area.
  // |###  \
  // X------X <- vid == 2: (3, 1)
  // ^
  // vid == 1: (-1, 1)

  gl_Position = position;
}
</file>

<file path="src/renderer/shaders/glsl/image.f.glsl">
#include "common.glsl"

layout(binding = 0) uniform sampler2D image;

in vec2 tex_coord;

layout(location = 0) out vec4 out_FragColor;

void main() {
    bool use_linear_blending = (bools & USE_LINEAR_BLENDING) != 0;

    vec4 rgba = texture(image, tex_coord);

    if (!use_linear_blending) {
        rgba = unlinearize(rgba);
    }

    rgba.rgb *= vec3(rgba.a);

    out_FragColor = rgba;
}
</file>

<file path="src/renderer/shaders/glsl/image.v.glsl">
#include "common.glsl"

layout(binding = 0) uniform sampler2D image;

layout(location = 0) in vec2 grid_pos;
layout(location = 1) in vec2 cell_offset;
layout(location = 2) in vec4 source_rect;
layout(location = 3) in vec2 dest_size;

out vec2 tex_coord;

void main() {
    int vid = gl_VertexID;

    // We use a triangle strip with 4 vertices to render quads,
    // so we determine which corner of the cell this vertex is in
    // based on the vertex ID.
    //
    //   0 --> 1
    //   |   .'|
    //   |  /  |
    //   | L   |
    //   2 --> 3
    //
    // 0 = top-left  (0, 0)
    // 1 = top-right (1, 0)
    // 2 = bot-left  (0, 1)
    // 3 = bot-right (1, 1)
    vec2 corner;
    corner.x = float(vid == 1 || vid == 3);
... (18 lines truncated)
</file>

<file path="src/renderer/shaders/shaders.metal">
#include <metal_stdlib>

using namespace metal;

enum Padding : uint8_t {
  EXTEND_LEFT = 1u,
  EXTEND_RIGHT = 2u,
  EXTEND_UP = 4u,
  EXTEND_DOWN = 8u,
};

struct Uniforms {
  float4x4 projection_matrix;
  float2 screen_size;
  float2 cell_size;
  ushort2 grid_size;
  float4 grid_padding;
  uint8_t padding_extend;
  float min_contrast;
  ushort2 cursor_pos;
  uchar4 cursor_color;
  uchar4 bg_color;
  bool cursor_wide;
  bool use_display_p3;
  bool use_linear_blending;
  bool use_linear_correction;
};

//-------------------------------------------------------------------
// Color Functions
... (823 lines truncated)
</file>

<file path="src/renderer/shaders/shadertoy_prefix.glsl">
#version 430 core

layout(binding = 1, std140) uniform Globals {
    uniform vec3  iResolution;
    uniform float iTime;
    uniform float iTimeDelta;
    uniform float iFrameRate;
    uniform int   iFrame;
    uniform float iChannelTime[4];
    uniform vec3  iChannelResolution[4];
    uniform vec4  iMouse;
    uniform vec4  iDate;
    uniform float iSampleRate;
    uniform vec4  iCurrentCursor;
    uniform vec4  iPreviousCursor;
    uniform vec4  iCurrentCursorColor;
    uniform vec4  iPreviousCursorColor;
    uniform int   iCurrentCursorStyle;
    uniform int   iPreviousCursorStyle;
    uniform int   iCursorVisible;
    uniform float iTimeCursorChange;
    uniform float iTimeFocus;
    uniform int iFocus;
    uniform vec3  iPalette[256];
    uniform vec3  iBackgroundColor;
    uniform vec3  iForegroundColor;
    uniform vec3  iCursorColor;
    uniform vec3  iCursorText;
    uniform vec3  iSelectionForegroundColor;
    uniform vec3  iSelectionBackgroundColor;
... (23 lines truncated)
</file>

<file path="src/renderer/shaders/test_shadertoy_crt.glsl">
// This shader is NOT BUILD INTO Ghostty. This is only here for unit tests.

// Loosely based on postprocessing shader by inigo quilez, License Creative
// Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

vec2 curve(vec2 uv)
{
	uv = (uv - 0.5) * 2.0;
	uv *= 1.1;
	uv.x *= 1.0 + pow((abs(uv.y) / 5.0), 2.0);
	uv.y *= 1.0 + pow((abs(uv.x) / 4.0), 2.0);
	uv  = (uv / 2.0) + 0.5;
	uv =  uv *0.92 + 0.04;
	return uv;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 q = fragCoord.xy / iResolution.xy;
    vec2 uv = q;
    uv = curve( uv );
    vec3 oricol = texture( iChannel0, vec2(q.x,q.y) ).xyz;
    vec3 col;
	float x =  sin(0.3*iTime+uv.y*21.0)*sin(0.7*iTime+uv.y*29.0)*sin(0.3+0.33*iTime+uv.y*31.0)*0.0017;

    col.r = texture(iChannel0,vec2(x+uv.x+0.001,uv.y+0.001)).x+0.05;
    col.g = texture(iChannel0,vec2(x+uv.x+0.000,uv.y-0.002)).y+0.05;
    col.b = texture(iChannel0,vec2(x+uv.x-0.002,uv.y+0.000)).z+0.05;
    col.r += 0.08*texture(iChannel0,0.75*vec2(x+0.025, -0.027)+vec2(uv.x+0.001,uv.y+0.001)).x;
    col.g += 0.05*texture(iChannel0,0.75*vec2(x+-0.022, -0.02)+vec2(uv.x+0.000,uv.y-0.002)).y;
    col.b += 0.08*texture(iChannel0,0.75*vec2(x+-0.02, -0.018)+vec2(uv.x-0.002,uv.y+0.000)).z;
... (30 lines truncated)
</file>

<file path="src/renderer/shaders/test_shadertoy_focus.glsl">
// Test shader for iTimeFocus and iFocus
// Shows border when focused, green fade that restarts on each focus gain
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;

    // Sample the terminal content
    vec4 terminal = texture2D(iChannel0, uv);
    vec3 color = terminal.rgb;

    if (iFocus > 0) {
        // FOCUSED: Add border and fading green overlay

        // Calculate time since focus was gained
        float timeSinceFocus = iTime - iTimeFocus;

        // Green fade: starts at 1.0 (full green), fades to 0.0 over 3 seconds
        float fadeOut = max(0.0, 1.0 - (timeSinceFocus / 3.0));

        // Add green overlay that fades out
        color = mix(color, vec3(0.0, 1.0, 0.0), fadeOut * 0.4);

        // Add border (5 pixels)
        float borderSize = 5.0;
        vec2 pixelCoord = fragCoord;
        bool isBorder = pixelCoord.x < borderSize ||
                       pixelCoord.x > iResolution.x - borderSize ||
                       pixelCoord.y < borderSize ||
                       pixelCoord.y > iResolution.y - borderSize;

        if (isBorder) {
... (12 lines truncated)
</file>

<file path="src/renderer/shaders/test_shadertoy_invalid.glsl">
vec2 curve(vec2 uv)
{
	uv = (uv - 0.5) * 2.0;
	uv *= 1.1;
	uv.x *= 1.0 + pow((abs(uv.y) / 5.0), 2.0);
	uv.y *= 1.0 + pow((abs(uv.x) / 4.0), 2.0);
	uv  = (uv / 2.0) + 0.5;
	uv =  uv *0.92 + 0.04;
	return uv;
}

// Missing mainImage!
</file>

<file path="src/renderer/backend.zig">
const std = @import("std");
const WasmTarget = @import("../os/wasm/target.zig").Target;

/// Possible implementations, used for build options.
pub const Backend = enum {
    opengl,
    metal,

    pub fn default(
        target: std.Target,
        wasm_target: WasmTarget,
    ) Backend {
        _ = wasm_target;
        if (target.os.tag.isDarwin()) return .metal;
        return .opengl;
    }
};
</file>

<file path="src/renderer/cell.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../quirks.zig").inlineAssert;
const font = @import("../font/main.zig");
const terminal = @import("../terminal/main.zig");
const renderer = @import("../renderer.zig");
const shaderpkg = renderer.Renderer.API.shaders;
const symbols = @import("../unicode/symbols_table.zig").table;

const CellTextRow = std.ArrayListUnmanaged(shaderpkg.CellText);

/// The possible cell content keys that exist.
pub const Key = enum {
    bg,
    text,
    underline,
    strikethrough,
    overline,

    /// Returns the GPU vertex type for this key.
    pub fn CellType(self: Key) type {
        return switch (self) {
            .bg => shaderpkg.CellBg,

            .text,
            .underline,
            .strikethrough,
            .overline,
            => shaderpkg.CellText,
        };
... (677 lines truncated)
</file>

<file path="src/renderer/cursor.zig">
const std = @import("std");
const terminal = @import("../terminal/main.zig");

/// Available cursor styles for drawing that renderers must support.
/// This is a superset of terminal cursor styles since the renderer supports
/// some additional cursor states such as the hollow block.
pub const Style = enum {
    // Typical cursor input styles
    block,
    block_hollow,
    bar,
    underline,

    // Special cursor styles
    lock,

    /// Create a cursor style from the terminal style request.
    pub fn fromTerminal(term: terminal.CursorStyle) Style {
        return switch (term) {
            .bar => .bar,
            .block => .block,
            .block_hollow => .block_hollow,
            .underline => .underline,
        };
    }
};

pub const StyleOptions = struct {
    preedit: bool = false,
    focused: bool = false,
... (129 lines truncated)
</file>

<file path="src/renderer/Dmabuf.zig">
//! A DMABUF frame produced by exporting a GPU texture.
//! This may be used on apprts like GTK that require us to manually
//! export each frame and import them as textures in their UI scene graphs.
//!
//! Note that DMABUFs are independent of the graphics API used:
//! the OpenGL renderer allocates them with GBM, and Vulkan can
//! export them with a KHR external memory implementation. Therefore
//! this struct has to be placed parallel to the renderer
//! implementations.
pub const Dmabuf = @This();
pub const std = @import("std");

/// The maximum number of planes in a DMABUF that we support.
/// This matches the maximum found in apprts such as GTK.
pub const max_planes = 4;

/// Width of the texture in device pixels.
width: u32,

/// Height of the texture in device pixels.
height: u32,

/// DRM fourcc of the pixel format.
/// Ghostty renders RGBA/BGRA8 premultiplied.
fourcc: u32,

/// DRM modifier of the format.
modifier: u64,

/// Whether the data is premultiplied.
... (46 lines truncated)
</file>

<file path="src/renderer/generic.zig">
const std = @import("std");
const builtin = @import("builtin");
const global = @import("../global.zig");
const xev = global.xev;
const wuffs = @import("wuffs");
const apprt = @import("../apprt.zig");
const configpkg = @import("../config.zig");
const font = @import("../font/main.zig");
const inputpkg = @import("../input.zig");
const os = @import("../os/main.zig");
const terminal = @import("../terminal/main.zig");
const renderer = @import("../renderer.zig");
const math = @import("../math.zig");
const Surface = @import("../Surface.zig");
const link = @import("link.zig");
const cellpkg = @import("cell.zig");
const noMinContrast = cellpkg.noMinContrast;
const constraintWidth = cellpkg.constraintWidth;
const isCovering = cellpkg.isCovering;
const rowNeverExtendBg = @import("row.zig").neverExtendBg;
const Overlay = @import("Overlay.zig");
const imagepkg = @import("image.zig");
const ImageState = imagepkg.State;
const shadertoy = @import("shadertoy.zig");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const Terminal = terminal.Terminal;
const Health = renderer.Health;
const compat_file = @import("../lib/compat/file.zig");
... (3632 lines truncated)
</file>

<file path="src/renderer/image.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../quirks.zig").inlineAssert;
const wuffs = @import("wuffs");
const terminal = @import("../terminal/main.zig");
const global = @import("../global.zig");

const Renderer = @import("../renderer.zig").Renderer;
const GraphicsAPI = Renderer.API;
const Texture = GraphicsAPI.Texture;
const CellSize = @import("size.zig").CellSize;
const Overlay = @import("Overlay.zig");

const log = std.log.scoped(.renderer_image);

/// Generic image rendering state for the renderer. This stores all
/// images and their placements and exposes only a limited public API
/// for adding images and placements and drawing them.
pub const State = struct {
    /// The full image state for the renderer that specifies what images
    /// need to be uploaded, pruned, etc.
    images: ImageMap,

    /// The placements for the Kitty image protocol.
    kitty_placements: std.ArrayListUnmanaged(Placement),

    /// The end index (exclusive) for placements that should be
    /// drawn below the background, below the text, etc.
    kitty_bg_end: u32,
    kitty_text_end: u32,
... (1490 lines truncated)
</file>

<file path="src/renderer/link.zig">
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const oni = @import("oniguruma");
const inputpkg = @import("../input.zig");
const terminal = @import("../terminal/main.zig");
const point = terminal.point;
const Screen = terminal.Screen;
const Terminal = terminal.Terminal;

const log = std.log.scoped(.renderer_link);

/// The link configuration needed for renderers.
pub const Link = struct {
    /// The regular expression to match the link against.
    regex: oni.Regex,

    /// The situations in which the link should be highlighted.
    highlight: inputpkg.Link.Highlight,

    pub fn deinit(self: *Link) void {
        self.regex.deinit();
    }

    /// Returns true if this link's highlight condition matches the given mouse state.
    fn active(
        self: *const Link,
        mouse_viewport: ?point.Coordinate,
        mouse_mods: inputpkg.Mods,
    ) bool {
... (362 lines truncated)
</file>

<file path="src/renderer/message.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const configpkg = @import("../config.zig");
const font = @import("../font/main.zig");
const renderer = @import("../renderer.zig");
const terminal = @import("../terminal/main.zig");

/// The messages that can be sent to a renderer thread.
pub const Message = union(enum) {
    /// Purposely crash the renderer. This is used for testing and debugging.
    /// See the "crash" binding action.
    crash,

    /// A change in state in the window focus that this renderer is
    /// rendering within. This is only sent when a change is detected so
    /// the renderer is expected to handle all of these.
    focus: bool,

    /// A change in the view occlusion state. This can be used to determine
    /// if the window is visible or not. A window can be not visible (occluded)
    /// and still have focus.
    visible: bool,

    /// Reset the cursor blink by immediately showing the cursor then
    /// restarting the timer.
    reset_cursor_blink,

    /// Change the font grid. This can happen for any number of reasons
    /// including a font size change, family change, etc.
... (88 lines truncated)
</file>

<file path="src/renderer/Metal.zig">
//! Graphics API wrapper for Metal.
pub const Metal = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const objc = @import("objc");
const macos = @import("macos");
const graphics = macos.graphics;
const apprt = @import("../apprt.zig");
const font = @import("../font/main.zig");
const configpkg = @import("../config.zig");
const rendererpkg = @import("../renderer.zig");
const Renderer = rendererpkg.GenericRenderer(Metal);
const shadertoy = @import("shadertoy.zig");

const mtl = @import("metal/api.zig");
const IOSurfaceLayer = @import("metal/IOSurfaceLayer.zig");
pub const Device = @import("metal/Device.zig");

pub const GraphicsAPI = Metal;
pub const Target = @import("metal/Target.zig");
pub const Frame = @import("metal/Frame.zig");
pub const RenderPass = @import("metal/RenderPass.zig");
pub const Pipeline = @import("metal/Pipeline.zig");
const bufferpkg = @import("metal/buffer.zig");
pub const Buffer = bufferpkg.Buffer;
pub const Sampler = @import("metal/Sampler.zig");
pub const Texture = @import("metal/Texture.zig");
... (358 lines truncated)
</file>

<file path="src/renderer/OpenGL.zig">
//! Graphics API wrapper for OpenGL.
pub const OpenGL = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const gl = @import("opengl");
const egl = gl.egl;
const shadertoy = @import("shadertoy.zig");
const apprt = @import("../apprt.zig");
const font = @import("../font/main.zig");
const configpkg = @import("../config.zig");
const rendererpkg = @import("../renderer.zig");
const Renderer = rendererpkg.GenericRenderer(OpenGL);
const Dmabuf = @import("Dmabuf.zig");
pub const Device = @import("opengl/Device.zig");

pub const GraphicsAPI = OpenGL;
pub const Target = @import("opengl/Target.zig");
pub const Frame = @import("opengl/Frame.zig");
pub const RenderPass = @import("opengl/RenderPass.zig");
pub const Pipeline = @import("opengl/Pipeline.zig");
const bufferpkg = @import("opengl/buffer.zig");
pub const Buffer = bufferpkg.Buffer;
pub const Sampler = @import("opengl/Sampler.zig");
pub const Texture = @import("opengl/Texture.zig");
pub const shaders = @import("opengl/shaders.zig");

pub const custom_shader_target: shadertoy.Target = .glsl;
// The fragCoord for OpenGL shaders is +Y = up.
pub const custom_shader_y_is_down = false;
... (420 lines truncated)
</file>

<file path="src/renderer/Options.zig">
//! The options that are used to configure a renderer.

const apprt = @import("../apprt.zig");
const font = @import("../font/main.zig");
const renderer = @import("../renderer.zig");

/// The device state that corresponds to the physical GPU
/// we'd like to render to.
device: *renderer.Device,

/// The derived configuration for this renderer implementation.
config: renderer.Renderer.DerivedConfig,

/// The font grid that should be used along with the key for deref-ing.
font_grid: *font.SharedGrid,

/// The size of everything.
size: renderer.Size,

/// The mailbox for sending the surface messages. This is only valid
/// once the thread has started and should not be used outside of the thread.
surface_mailbox: apprt.surface.Mailbox,

/// The apprt surface.
rt_surface: *apprt.Surface,

/// The renderer thread.
thread: *renderer.Thread,
</file>

<file path="src/renderer/Overlay.zig">
/// The debug overlay that can be drawn on top of the terminal
/// during the rendering process.
///
/// This is implemented by doing all the drawing on the CPU via z2d,
/// since the debug overlay isn't that common, z2d is pretty fast, and
/// it simplifies our implementation quite a bit by not relying on us
/// having a bunch of shaders that we have to write per-platform.
///
/// Initialize the overlay, apply features with `applyFeatures`, then
/// get the resulting image with `pendingImage` to upload to the GPU.
/// This works in concert with `renderer.image.State` to simplify. Draw
/// it on the GPU as an image composited on top of the terminal output.
const Overlay = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const z2d = @import("z2d");
const terminal = @import("../terminal/main.zig");
const size = @import("size.zig");
const Size = size.Size;
const CellSize = size.CellSize;
const Image = @import("image.zig").Image;
const global = @import("../global.zig");

const log = std.log.scoped(.renderer_overlay);

/// The colors we use for overlays.
pub const Color = enum {
    hyperlink, // light blue
    semantic_prompt, // orange/gold
... (387 lines truncated)
</file>

<file path="src/renderer/row.zig">
const terminal = @import("../terminal/main.zig");

// TODO: Test neverExtendBg function

/// Returns true if the row of this pin should never have its background
/// color extended for filling padding space in the renderer. This is
/// a set of heuristics that help making our padding look better.
pub fn neverExtendBg(
    row: terminal.page.Row,
    cells: []const terminal.page.Cell,
    styles: []const terminal.Style,
    palette: *const terminal.color.Palette,
    default_background: terminal.color.RGB,
) bool {
    // Any semantic prompts should not have their background extended
    // because prompts often contain special formatting (such as
    // powerline) that looks bad when extended.
    switch (row.semantic_prompt) {
        .prompt, .prompt_continuation => return true,
        .none => {},
    }

    for (0.., cells) |x, *cell| {
        // If any cell has a default background color then we don't
        // extend because the default background color probably looks
        // good enough as an extension.
        switch (cell.content_tag) {
            // If it is a background color cell, we check the color.
            .bg_color_palette, .bg_color_rgb => {
                const s: terminal.Style = if (cell.hasStyling()) styles[x] else .{};
... (34 lines truncated)
</file>

<file path="src/renderer/shadertoy.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const glslang = @import("glslang");
const spvcross = @import("spirv_cross");
const configpkg = @import("../config.zig");
const compat_file = @import("../lib/compat/file.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.shadertoy);

/// The uniform struct used for shadertoy shaders.
pub const Uniforms = extern struct {
    resolution: [3]f32 align(16),
    time: f32 align(4),
    time_delta: f32 align(4),
    frame_rate: f32 align(4),
    frame: i32 align(4),
    channel_time: [4][4]f32 align(16),
    channel_resolution: [4][4]f32 align(16),
    mouse: [4]f32 align(16),
    date: [4]f32 align(16),
    sample_rate: f32 align(4),
    current_cursor: [4]f32 align(16),
    previous_cursor: [4]f32 align(16),
    current_cursor_color: [4]f32 align(16),
    previous_cursor_color: [4]f32 align(16),
    current_cursor_style: i32 align(4),
    previous_cursor_style: i32 align(4),
... (465 lines truncated)
</file>

<file path="src/renderer/size.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const terminal_size = @import("../terminal/size.zig");

const log = std.log.scoped(.renderer_size);

/// Controls how extra whitespace around the terminal grid is distributed.
pub const PaddingBalance = enum {
    /// No balancing; padding is applied as specified explicitly.
    false,
    /// Balances padding but caps the top padding so the first row doesn't
    /// drift too far from the top of the window. Excess vertical space is
    /// shifted to the bottom.
    true,
    /// Distributes leftover space equally on all sides so the grid is
    /// centered within the screen.
    equal,
};

/// All relevant sizes for a rendered terminal. These are all the sizes that
/// any functionality should need to know about the terminal in order to
/// convert between any coordinate systems.
///
/// See the individual field type documentation for more information on each
/// field. One important note is that any pixel values should already be scaled
/// to the current DPI of the screen. If the DPI changes, the sizes should be
/// recalculated and we expect this to be done by the caller.
pub const Size = struct {
    screen: ScreenSize,
    cell: CellSize,
... (429 lines truncated)
</file>

<file path="src/renderer/State.zig">
//! This is the render state that is given to a renderer.

const State = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Inspector = @import("../inspector/main.zig").Inspector;
const terminalpkg = @import("../terminal/main.zig");
const inputpkg = @import("../input.zig");
const renderer = @import("../renderer.zig");

/// The mutex that must be held while reading any of the data in the
/// members of this state. Note that the state itself is NOT protected
/// by the mutex and is NOT thread-safe, only the members values of the
/// state (i.e. the terminal, devmode, etc. values).
mutex: *std.Io.Mutex,

/// The terminal data.
terminal: *terminalpkg.Terminal,

/// The terminal inspector, if any. This will be null while the inspector
/// is not active and will be set when it is active.
inspector: ?*Inspector = null,

/// Dead key state. This will render the current dead key preedit text
/// over the cursor. This currently only ever renders a single codepoint.
/// Preedit can in theory be multiple codepoints long but that is left as
/// a future exercise.
preedit: ?Preedit = null,
... (206 lines truncated)
</file>

<file path="src/renderer/Thread.zig">
//! Represents the renderer thread logic. The renderer thread is able to
//! be woken up to render.
pub const Thread = @This();

const std = @import("std");
const builtin = @import("builtin");
const global = @import("../global.zig");
const xev = global.xev;
const crash = @import("../crash/main.zig");
const internal_os = @import("../os/main.zig");
const rendererpkg = @import("../renderer.zig");
const apprt = @import("../apprt.zig");
const configpkg = @import("../config.zig");
const terminalpkg = @import("../terminal/main.zig");
const BlockingQueue = @import("../datastruct/main.zig").BlockingQueue;

const Allocator = std.mem.Allocator;
const log = std.log.scoped(.renderer_thread);

const CURSOR_BLINK_INTERVAL = 600;

/// Whether calls to `drawFrame` must be done from the app thread.
///
/// The type used for sending messages to the IO thread. For now this is
/// hardcoded with a capacity. We can make this a comptime parameter in
/// the future if we want it configurable.
pub const Mailbox = BlockingQueue(rendererpkg.Message, 64);

/// Allocator used for some state
alloc: std.mem.Allocator,
... (828 lines truncated)
</file>

<file path="src/shell-integration/fish/vendor_conf.d/ghostty-shell-integration.fish">
# This shell script aims to be written in a way where it can't really fail
# or all failure scenarios are handled, so that we never leave the shell in
# a weird state. If you find a way to break this, please report a bug!

function ghostty_restore_xdg_data_dir -d "restore the original XDG_DATA_DIR value"
    # If we don't have our own data dir then we don't need to do anything.
    if not set -q GHOSTTY_SHELL_INTEGRATION_XDG_DIR
        return
    end

    # If the data dir isn't set at all then we don't need to do anything.
    if not set -q XDG_DATA_DIRS
        return
    end

    # We need to do this so that XDG_DATA_DIRS turns into an array.
    set --function --path xdg_data_dirs "$XDG_DATA_DIRS"

    # If our data dir is in the list then remove it.
    if set --function index (contains --index "$GHOSTTY_SHELL_INTEGRATION_XDG_DIR" $xdg_data_dirs)
        set --erase --function xdg_data_dirs[$index]
    end

    # Re-export our data dir
    if set -q xdg_data_dirs[1]
        set --global --export --unpath XDG_DATA_DIRS "$xdg_data_dirs"
    else
        set --erase --global XDG_DATA_DIRS
    end

... (149 lines truncated)
</file>

<file path="src/shell-integration/zsh/ghostty-integration">
# vim:ft=zsh
#
# Based on (started as) a copy of Kitty's zsh integration. Kitty is
# distributed under GPLv3, so this file is also distributed under GPLv3.
# The license header is reproduced below:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

#
# Enables integration between zsh and ghostty.
#
# This is an autoloadable function. It's invoked automatically in shells
# directly spawned by Ghostty but not in any other shells. For example, running
# `exec zsh`, `sudo -E zsh`, `tmux`, or plain `zsh` will create a shell where
# ghostty-integration won't automatically run. Zsh users who want integration with
# Ghostty in all shells should add the following lines to their .zshrc:
#
#   if [[ -n $GHOSTTY_RESOURCES_DIR ]]; then
#     source "$GHOSTTY_RESOURCES_DIR"/shell-integration/zsh/ghostty-integration
... (366 lines truncated)
</file>

<file path="src/shell-integration/README.md">
# Shell Integration Code

This is the shell-specific shell-integration code that is
used for the shell-integration feature set that Ghostty
supports.

This README is meant as developer documentation and not as
user documentation. For user documentation, see the main
README or [ghostty.org](https://ghostty.org/docs)

## Implementation Details

### Bash

Automatic [Bash](https://www.gnu.org/software/bash/) shell integration works by
starting Bash in POSIX mode and using the `ENV` environment variable to load
our integration script (`bash/ghostty.bash`). This prevents Bash from loading
its normal startup files, which becomes our script's responsibility (along with
disabling POSIX mode).

Bash shell integration can also be sourced manually from `bash/ghostty.bash`.
This also works for older versions of Bash.

```bash
# Ghostty shell integration for Bash. This must be at the top of your bashrc!
if [ -n "${GHOSTTY_RESOURCES_DIR}" ]; then
    builtin source "${GHOSTTY_RESOURCES_DIR}/shell-integration/bash/ghostty.bash"
fi
```

... (82 lines truncated)
</file>

<file path="src/simd/base64_scalar.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;

pub const scalar_decoder: Base64Decoder = .init(
    std.base64.standard_alphabet_chars,
    null,
);

/// Whether c is one of the 64 standard base64 alphabet characters
/// (padding is not part of the alphabet).
pub fn isAlphabetChar(c: u8) bool {
    return scalar_decoder.char_to_index[c] != Base64Decoder.invalid_char;
}

/// Copied from Zig 0.14.1 stdlib and commented out the invalid padding
/// scenarios, because Kitty Graphics requires a decoder that doesn't care
/// about invalid padding scenarios.
const Base64Decoder = struct {
    const invalid_char: u8 = 0xff;
    const invalid_char_tst: u32 = 0xff000000;

    const Error = error{
        InvalidCharacter,
        InvalidPadding,
        NoSpaceLeft,
    };

    /// e.g. 'A' => 0.
    /// `invalid_char` for any value not in the 64 alphabet chars.
    char_to_index: [256]u8,
... (124 lines truncated)
</file>

<file path="src/simd/base64.cpp">
size_t ghostty_simd_base64_max_length(const char* input, size_t length) {
⋮----
size_t ghostty_simd_base64_decode(const char* input,
</file>

<file path="src/simd/base64.zig">
const std = @import("std");
const options = @import("build_options");
const assert = @import("../quirks.zig").inlineAssert;
const base64_scalar = @import("base64_scalar.zig");
const scalar_decoder = base64_scalar.scalar_decoder;

const log = std.log.scoped(.simd_base64);

pub fn maxLen(input: []const u8) usize {
    if (comptime options.simd) return ghostty_simd_base64_max_length(
        input.ptr,
        input.len,
    );

    return maxLenScalar(input);
}

fn maxLenScalar(input: []const u8) usize {
    return scalar_decoder.calcSizeForSlice(scalarInput(input)) catch |err| {
        log.warn("failed to calculate base64 size for payload: {}", .{err});
        return 0;
    };
}

pub fn decode(input: []const u8, output: []u8) error{Base64Invalid}![]const u8 {
    if (comptime options.simd) {
        const res = ghostty_simd_base64_decode(
            input.ptr,
            input.len,
            output.ptr,
... (413 lines truncated)
</file>

<file path="src/simd/codepoint_width.cpp">
constexpr size_t array_size(const T (&)[N]) { return N; }
⋮----
constexpr T array_min(const T (&a)[N]) {
⋮----
constexpr T array_max(const T (&a)[N]) {
⋮----
int8_t CodepointWidth16(D d, uint16_t input) {
⋮----
int8_t CodepointWidth32(D d, T input) {
⋮----
int8_t CodepointWidth(uint32_t input) {
⋮----
int8_t CodepointWidth(uint32_t cp) {
⋮----
int8_t ghostty_simd_codepoint_width(uint32_t cp) {
</file>

<file path="src/simd/codepoint_width.zig">
const std = @import("std");
const options = @import("build_options");

// vt.cpp
extern "c" fn ghostty_simd_codepoint_width(u32) i8;

pub fn codepointWidth(cp: u32) i8 {
    if (comptime options.simd) return ghostty_simd_codepoint_width(cp);
    const uucode = @import("uucode");
    if (cp > uucode.config.max_code_point) return 1;
    return @import("uucode").get(.width, @intCast(cp));
}

test "codepointWidth basic" {
    const testing = std.testing;
    try testing.expectEqual(@as(i8, 1), codepointWidth('a'));
    try testing.expectEqual(@as(i8, 1), codepointWidth(0x100)); // Ā
    try testing.expectEqual(@as(i8, 2), codepointWidth(0x3400)); // 㐀
    try testing.expectEqual(@as(i8, 2), codepointWidth(0x2E3A)); // ⸺
    try testing.expectEqual(@as(i8, 2), codepointWidth(0x1F1E6)); // 🇦
    try testing.expectEqual(@as(i8, 2), codepointWidth(0x4E00)); // 一
    try testing.expectEqual(@as(i8, 2), codepointWidth(0xF900)); // 豈
    try testing.expectEqual(@as(i8, 2), codepointWidth(0x20000)); // 𠀀
    try testing.expectEqual(@as(i8, 2), codepointWidth(0x30000)); // 𠀀
    // try testing.expectEqual(@as(i8, 1), @import("uucode").get(.width, 0x100));
}

// This is not very fast in debug modes, so its commented by default.
// IMPORTANT: UNCOMMENT THIS WHENEVER MAKING CODEPOINTWIDTH CHANGES.
// test "codepointWidth matches uucode" {
... (23 lines truncated)
</file>

<file path="src/simd/index_of.cpp">
size_t IndexOf(const uint8_t needle,
⋮----
size_t ghostty_simd_index_of(const uint8_t needle,
</file>

<file path="src/simd/index_of.h">
size_t IndexOf(const uint8_t needle,
</file>

<file path="src/simd/index_of.zig">
const std = @import("std");
const options = @import("build_options");

extern "c" fn ghostty_simd_index_of(
    needle: u8,
    input: [*]const u8,
    count: usize,
) usize;

pub fn indexOf(input: []const u8, needle: u8) ?usize {
    if (comptime options.simd) {
        const result = ghostty_simd_index_of(needle, input.ptr, input.len);
        return if (result == input.len) null else result;
    }

    return indexOfScalar(input, needle);
}

fn indexOfScalar(input: []const u8, needle: u8) ?usize {
    return std.mem.indexOfScalar(u8, input, needle);
}

test "indexOf" {
    const testing = std.testing;
    try testing.expect(indexOf("hello", ' ') == null);
    try testing.expectEqual(@as(usize, 2), indexOf("hi lo", ' ').?);
    try testing.expectEqual(@as(usize, 5), indexOf(
        \\XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        \\XXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXX
    , ' ').?);
... (6 lines truncated)
</file>

<file path="src/simd/main.zig">
//! SIMD-optimized routines. If `build_options.simd` is false, then the API
//! still works but we fall back to pure Zig scalar implementations.

const std = @import("std");

const codepoint_width = @import("codepoint_width.zig");
pub const base64 = @import("base64.zig");
pub const index_of = @import("index_of.zig");
pub const vt = @import("vt.zig");
pub const codepointWidth = codepoint_width.codepointWidth;

/// The number of vector lanes to use for manually vectorized hot
/// loops operating on elements of type T, or null if the target has
/// no usable SIMD support and a plain scalar loop should be used
/// instead (e.g. wasm32 without simd128).
///
/// This is twice the native vector width so that each iteration works
/// two vector registers, giving better instruction-level parallelism.
pub fn lanes(comptime T: type) ?comptime_int {
    const native = std.simd.suggestVectorLength(T) orelse return null;
    return native * 2;
}

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/simd/vt.cpp">
static size_t MaximalSubpart(const unsigned char* p, size_t len) {
⋮----
static size_t TrimValidPartialUTF8(const uint8_t* input, size_t len) {
⋮----
size_t DecodeUTF8(const uint8_t* HWY_RESTRICT input,
⋮----
static HWY_INLINE void WidenAsciiStore(D d,
⋮----
static HWY_NOINLINE size_t DecodeNonAsciiUntilControlSeq(
⋮----
size_t DecodeUTF8UntilControlSeqImpl(D d,
⋮----
size_t DecodeUTF8UntilControlSeq(const uint8_t* HWY_RESTRICT input,
⋮----
size_t ghostty_simd_decode_utf8_until_control_seq(const uint8_t* HWY_RESTRICT
</file>

<file path="src/simd/vt.h">

</file>

<file path="src/simd/vt.zig">
const std = @import("std");
const options = @import("build_options");
const assert = @import("../quirks.zig").inlineAssert;
const indexOf = @import("index_of.zig").indexOf;

// vt.cpp
extern "c" fn ghostty_simd_decode_utf8_until_control_seq(
    input: [*]const u8,
    count: usize,
    output: [*]u32,
    output_count: *usize,
) usize;

const DecodeResult = struct {
    consumed: usize,
    decoded: usize,
};

pub fn utf8DecodeUntilControlSeq(
    input: []const u8,
    output: []u32,
) DecodeResult {
    assert(output.len >= input.len);

    if (comptime options.simd) {
        var decoded: usize = 0;
        const consumed = ghostty_simd_decode_utf8_until_control_seq(
            input.ptr,
            input.len,
            output.ptr,
... (545 lines truncated)
</file>

<file path="src/stb/main.zig">
const c = @import("stb_c");

// We'll just add the exports of the functions or types we actually use
// here, no need to export everything from the C lib if we don't use it.
pub const stbi_load_from_memory = c.stbi_load_from_memory;
pub const stbi_image_free = c.stbi_image_free;
pub const stbir_resize_uint8 = c.stbir_resize_uint8;
</file>

<file path="src/stb/stb_image_resize.h">
typedef unsigned char  stbir_uint8;
typedef unsigned short stbir_uint16;
typedef unsigned int   stbir_uint32;
⋮----
typedef uint8_t  stbir_uint8;
typedef uint16_t stbir_uint16;
typedef uint32_t stbir_uint32;
⋮----
STBIRDEF int stbir_resize_uint8(     const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,
⋮----
STBIRDEF int stbir_resize_float(     const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes,
⋮----
STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,
⋮----
} stbir_edge;
⋮----
STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,
⋮----
} stbir_filter;
⋮----
} stbir_colorspace;
⋮----
STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes,
⋮----
STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels  , int input_w , int input_h , int input_stride_in_bytes,
⋮----
STBIRDEF int stbir_resize_float_generic( const float *input_pixels         , int input_w , int input_h , int input_stride_in_bytes,
⋮----
} stbir_datatype;
⋮----
... (128 lines truncated)
</file>

<file path="src/stb/stb_image.h">
typedef unsigned char stbi_uc;
typedef unsigned short stbi_us;
⋮----
} stbi_io_callbacks;
⋮----
STBIDEF stbi_uc *stbi_load_from_memory   (stbi_uc           const *buffer, int len   , int *x, int *y, int *channels_in_file, int desired_channels);
STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk  , void *user, int *x, int *y, int *channels_in_file, int desired_channels);
⋮----
STBIDEF stbi_uc *stbi_load            (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
STBIDEF stbi_uc *stbi_load_from_file  (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
⋮----
STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp);
⋮----
STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);
⋮----
STBIDEF stbi_us *stbi_load_16_from_memory   (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);
⋮----
STBIDEF stbi_us *stbi_load_16          (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
⋮----
STBIDEF float *stbi_loadf_from_memory     (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
STBIDEF float *stbi_loadf_from_callbacks  (stbi_io_callbacks const *clbk, void *user, int *x, int *y,  int *channels_in_file, int desired_channels);
⋮----
STBIDEF float *stbi_loadf            (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
STBIDEF float *stbi_loadf_from_file  (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
⋮----
STBIDEF void   stbi_hdr_to_ldr_gamma(float gamma);
STBIDEF void   stbi_hdr_to_ldr_scale(float scale);
⋮----
... (560 lines truncated)
</file>

<file path="src/stb/stb.c">

</file>

<file path="src/synthetic/cli/Ascii.zig">
const Ascii = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Bytes = @import("../Bytes.zig");

const log = std.log.scoped(.@"terminal-stream-bench");

pub const Options = struct {
    /// When nonzero, emit lines whose printable length is uniformly
    /// distributed in `[line-min, line-max]`, each terminated by CR LF.
    /// When zero (the default), emit an unbroken stream of printable
    /// bytes that relies on terminal wrapping.
    @"line-min": usize = 0,
    @"line-max": usize = 0,
};

fn checkAsciiAlphabet(c: u8) bool {
    return switch (c) {
        ' ' => false,
        else => std.ascii.isPrint(c),
    };
}

pub const ascii = Bytes.generateAlphabet(checkAsciiAlphabet);

opts: Options,

/// Create a new terminal stream handler for the given arguments.
... (86 lines truncated)
</file>

<file path="src/synthetic/cli/Kitty.zig">
const Kitty = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const synthetic = @import("../main.zig");

const log = std.log.scoped(.@"kitty-gen");

pub const Options = struct {
    /// The base64 payload length of each command in bytes, rounded
    /// down to a multiple of four. Kitty clients typically chunk
    /// payloads at 4096 bytes.
    @"data-len": usize = 4096,
};

opts: Options,

/// The buffer a single generated sequence is written into. Sized to
/// the payload length plus room for the control data and terminator.
buf: []u8,

/// Create a new Kitty graphics sequence generator for the given arguments.
pub fn create(
    alloc: Allocator,
    opts: Options,
) !*Kitty {
    const ptr = try alloc.create(Kitty);
    errdefer alloc.destroy(ptr);

    const buf = try alloc.alloc(u8, opts.@"data-len" + 128);
... (41 lines truncated)
</file>

<file path="src/synthetic/cli/Osc.zig">
const Osc = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const synthetic = @import("../main.zig");

const log = std.log.scoped(.@"terminal-stream-bench");

pub const Options = struct {
    /// Probability of generating a valid value.
    @"p-valid": f64 = 0.5,

    style: enum {
        /// Write all OSC data, including ESC ] and ST for end-to-end tests
        streaming,
        /// Only write data, prefixed with a length, used for testing just the
        /// OSC parser.
        parser,
    } = .streaming,
};

opts: Options,

/// Create a new terminal stream handler for the given arguments.
pub fn create(
    alloc: Allocator,
    opts: Options,
) !*Osc {
    const ptr = try alloc.create(Osc);
... (53 lines truncated)
</file>

<file path="src/synthetic/cli/Styled.zig">
//! Generates styled terminal content: lines of printable text
//! interspersed with SGR sequences, optional multi-byte UTF-8
//! codepoints, combining marks (multi-codepoint graphemes), and
//! OSC 8 hyperlinks.
//!
//! This exists primarily to build corpora for benchmarking code that
//! consumes terminal *contents* (e.g. the terminal formatter used for
//! clipboard copy and dumps), where we want workloads with controlled
//! amounts of styling and Unicode rather than raw random bytes.
//!
//! Examples:
//!
//!   # Plain ASCII lines (equivalent to `ascii` with lines)
//!   ghostty-gen styled --seed=42
//!
//!   # Heavily styled ASCII
//!   ghostty-gen styled --seed=42 --style-rate=0.8
//!
//!   # Unicode-heavy, no styling
//!   ghostty-gen styled --seed=42 --weight-two=1 --weight-three=1 \
//!     --weight-four=0.5 --grapheme-rate=0.1
//!
//!   # Mixed: styles, Unicode, and hyperlinks
//!   ghostty-gen styled --seed=42 --style-rate=0.3 --weight-two=0.5 \
//!     --weight-three=0.25 --weight-four=0.1 --grapheme-rate=0.05 \
//!     --osc8-rate=0.1
const Styled = @This();

const std = @import("std");
const assert = std.debug.assert;
... (381 lines truncated)
</file>

<file path="src/synthetic/cli/Utf8.zig">
const Utf8 = @This();

const std = @import("std");
const Allocator = std.mem.Allocator;
const synthetic = @import("../main.zig");

pub const Options = struct {
    /// Seed to use for deterministic generation. If unset, a time-based
    /// seed is used by the generic synthetic CLI.
    seed: ?u64 = null,

    /// Relative weight for choosing 1-byte UTF-8 sequences.
    @"weight-one": f64 = 1.0,

    /// Relative weight for choosing 2-byte UTF-8 sequences.
    @"weight-two": f64 = 1.0,

    /// Relative weight for choosing 3-byte UTF-8 sequences.
    @"weight-three": f64 = 1.0,

    /// Relative weight for choosing 4-byte UTF-8 sequences.
    @"weight-four": f64 = 1.0,

    /// Restrict ASCII codepoints to printable characters.
    @"ascii-printable-only": bool = false,

    /// Probability that an emitted sequence is malformed UTF-8.
    @"invalid-rate": f64 = 0.0,
};

... (81 lines truncated)
</file>

<file path="src/synthetic/Bytes.zig">
//! Generates bytes.
const Bytes = @This();

const std = @import("std");
const Generator = @import("Generator.zig");

/// Random number generator.
rand: std.Random,

/// The minimum and maximum length of the generated bytes.
min_len: usize = 1,
max_len: usize = std.math.maxInt(usize),

/// The possible bytes that can be generated. If a byte is duplicated
/// in the alphabet, it will be more likely to be generated. That's a
/// side effect of the generator, not an intended use case.
alphabet: ?[]const u8 = null,

/// Generate an alphabet given a function that returns true/false for a
/// given byte.
pub fn generateAlphabet(comptime func: fn (u8) bool) []const u8 {
    @setEvalBranchQuota(3000);
    var count = 0;
    for (0..256) |c| {
        if (func(c)) count += 1;
    }
    var alphabet: [count]u8 = undefined;
    var i = 0;
    for (0..256) |c| {
        if (func(c)) {
... (90 lines truncated)
</file>

<file path="src/synthetic/cli.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const cli = @import("../cli.zig");

/// The available actions for the CLI. This is the list of available
/// synthetic generators. View docs for each individual one in the
/// predictably named files under `cli/`.
pub const Action = enum {
    ascii,
    kitty,
    osc,
    styled,
    utf8,

    /// Returns the struct associated with the action. The struct
    /// should have a few decls:
    ///
    ///   - `const Options`: The CLI options for the action.
    ///   - `fn create`: Create a new instance of the action from options.
    ///   - `fn destroy`: Destroy the instance of the action.
    ///
    /// See TerminalStream for an example.
    pub fn Struct(comptime action: Action) type {
        return switch (action) {
            .ascii => @import("cli/Ascii.zig"),
            .kitty => @import("cli/Kitty.zig"),
            .osc => @import("cli/Osc.zig"),
            .styled => @import("cli/Styled.zig"),
            .utf8 => @import("cli/Utf8.zig"),
        };
... (89 lines truncated)
</file>

<file path="src/synthetic/Generator.zig">
/// A common interface for all generators.
const Generator = @This();

const std = @import("std");
const assert = std.debug.assert;

/// For generators, this is the only error that is allowed to be
/// returned by the next function.
pub const Error = error{WriteFailed};

/// The vtable for the generator.
ptr: *anyopaque,
nextFn: *const fn (ptr: *anyopaque, *std.Io.Writer, usize) Error!void,

/// Create a new generator from a pointer and a function pointer.
/// This usually is only called by generator implementations, not
/// generator users.
pub fn init(
    pointer: anytype,
    comptime nextFn: fn (ptr: @TypeOf(pointer), *std.Io.Writer, usize) Error!void,
) Generator {
    const Ptr = @TypeOf(pointer);
    assert(@typeInfo(Ptr) == .pointer); // Must be a pointer
    assert(@typeInfo(Ptr).pointer.size == .one); // Must be a single-item pointer
    assert(@typeInfo(@typeInfo(Ptr).pointer.child) == .@"struct"); // Must point to a struct
    const gen = struct {
        fn next(ptr: *anyopaque, writer: *std.Io.Writer, max_len: usize) Error!void {
            const self: Ptr = @ptrCast(@alignCast(ptr));
            try nextFn(self, writer, max_len);
        }
... (13 lines truncated)
</file>

<file path="src/synthetic/Kitty.zig">
//! Generates random Kitty graphics protocol APC sequences.
//!
//! The payload is random base64, NOT a valid image: decoding it as
//! PNG will fail. This corpus is meant for benchmarking the stream,
//! APC, and Kitty command parsing paths, which never decode the
//! image data. It does not exercise successful image loading.
const Kitty = @This();

const std = @import("std");
const assert = std.debug.assert;
const Generator = @import("Generator.zig");
const Bytes = @import("Bytes.zig");

/// Random number generator.
rand: std.Random,

/// The base64 payload length for each generated command. This is
/// rounded down to a multiple of four so the payload is always valid
/// base64 without requiring padding. Kitty clients typically chunk
/// payloads at 4096 bytes.
data_len: usize = 4096,

fn checkBase64Alphabet(c: u8) bool {
    return switch (c) {
        'A'...'Z', 'a'...'z', '0'...'9', '+', '/' => true,
        else => false,
    };
}

/// The base64 alphabet, without the padding character.
... (59 lines truncated)
</file>

<file path="src/synthetic/main.zig">
//! The synthetic package contains an abstraction for generating
//! synthetic data. The motivating use case for this package is to
//! generate synthetic data for benchmarking, but it may also expand
//! to other use cases such as fuzzing (e.g. to generate a corpus
//! rather than directly fuzzing).
//!
//! The generators in this package are typically not performant
//! enough to be streamed in real time. They should instead be
//! used to generate a large amount of data in a single go
//! and then streamed from there.
//!
//! The generators are aimed for terminal emulation, but the package
//! is not limited to that and we may want to extract this to a
//! standalone package one day.

pub const cli = @import("cli.zig");

pub const Generator = @import("Generator.zig");
pub const Bytes = @import("Bytes.zig");
pub const Utf8 = @import("Utf8.zig");
pub const Kitty = @import("Kitty.zig");
pub const Osc = @import("Osc.zig");

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/synthetic/Osc.zig">
/// Generates random terminal OSC requests.
const Osc = @This();

const std = @import("std");
const assert = std.debug.assert;
const Generator = @import("Generator.zig");
const Bytes = @import("Bytes.zig");
const urlPercentEncode = @import("../os/string_encoding.zig").urlPercentEncode;

/// Valid OSC request kinds that can be generated.
pub const ValidKind = enum {
    change_window_title,
    prompt_start,
    prompt_end,
    end_of_input,
    end_of_command,
    rxvt_notify,
    mouse_shape,
    clipboard_operation,
    report_pwd,
    hyperlink_start,
    hyperlink_end,
    conemu_progress,
    iterm2_notification,
};

/// Invalid OSC request kinds that can be generated.
pub const InvalidKind = enum {
    /// Literally random bytes. Might even be valid, but probably not.
    random,
... (337 lines truncated)
</file>

<file path="src/synthetic/Utf8.zig">
/// Generates UTF-8.
///
/// This doesn't yet generate multi-codepoint graphemes, but it
/// has the ability to generate a custom distribution of UTF-8
/// encoding lengths (1, 2, 3, or 4 bytes).
const Utf8 = @This();

const std = @import("std");
const assert = std.debug.assert;
const Generator = @import("Generator.zig");

/// Possible UTF-8 encoding lengths.
pub const Utf8Len = enum(u3) {
    one = 1,
    two = 2,
    three = 3,
    four = 4,
};

const InvalidSequence = struct {
    len: u3,
    bytes: [4]u8,

    fn slice(self: *const InvalidSequence) []const u8 {
        return self.bytes[0..self.len];
    }
};

const invalid_sequences = [_]InvalidSequence{
    .{ .len = 1, .bytes = .{ 0x80, 0x00, 0x00, 0x00 } },
... (200 lines truncated)
</file>

<file path="src/terminal/apc/glyph/AGENTS.md">
# Glyph Protocol

- The specification source of truth is:
  <https://github.com/raphamorim/rio/blob/main/specs/glyph-protocol.md>
- A summary of the specification is available in
  `src/terminal/apc/glyph.zig` at the top.
- Reference the specification whenever any changes are made to
  this folder. Prefer the local specification over fetching the
  latest, unless it is lacking information.
</file>

<file path="src/terminal/apc/glyph/execute.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;

const request = @import("request.zig");
const response = @import("response.zig");
const Glossary = @import("Glossary.zig");
const Request = request.Request;
const Response = response.Response;

const log = std.log.scoped(.glyph);

/// Payload formats we support. Hardcoded because the support is
/// fixed.
pub const supported_formats: response.Response.Support.Formats = .{
    .glyf = true,
};

/// Execute a Glyph protocol request against the given state.
///
/// This will never fail, but the response may indiciate an error and
/// the terminal state may not be updated to reflect the command. This will
/// never put the terminal in a corrupt or non-recoverable state.
///
/// For example, allocation errors can happen, but they're wrapped up in
/// an out of memory response.
///
/// Query responses only report glossary coverage. Callers that can determine
/// system font coverage must update the returned query response before sending
/// it to the client.
pub fn execute(
... (338 lines truncated)
</file>

<file path="src/terminal/apc/glyph/Glossary.zig">
/// Glossary is the per-terminal storage for Glyph Protocol
/// codepoints. We use the word Glossary to match up with the spec which
/// also uses this word.
const Glossary = @This();

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const CircBuf = @import("../../../datastruct/circ_buf.zig").CircBuf;
const FontGlyph = @import("../../../font/Glyph.zig");
const Glyf = @import("../../../font/opentype/glyf.zig").Glyf;

const request = @import("request.zig");
const RegisterReq = request.Request.Register;

const DesignMetrics = FontGlyph.DesignMetrics;
const Constraint = FontGlyph.RenderOptions.Constraint;

/// Maximum entries allowed in the glossary before eviction.
/// Defined by the specification.
pub const max_entries = 1024;

/// Maximum size of any allocation made while decoding a glyf registration.
/// This is limited by the dynamic allocations not the struct size so the
/// actual size allowed is slightly larger, but worst case only by 10KB.
pub const max_glyf_allocation = 64 * 1024; // 64 KiB

/// An empty glossary with no registered glyphs.
pub const empty: Glossary = .{ .entries = .empty };

... (486 lines truncated)
</file>

<file path="src/terminal/apc/glyph/request.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const LimitedAllocator = @import("../../../datastruct/main.zig").LimitedAllocator;
const Glyf = @import("../../../font/opentype/glyf.zig").Glyf;
const fraction = @import("../../fraction.zig");

/// Maximum decoded glyph payload size accepted by the protocol.
/// This is documented in the spec.
const max_payload_size = 64 * 1024; // 64 KiB

/// Stateful parser for a single glyph APC payload after the `25a1;` prefix.
pub const CommandParser = struct {
    alloc: Allocator,
    data: std.ArrayList(u8) = .empty,

    /// Maximum bytes the data payload can buffer. This is to prevent
    /// malicious input from causing us to allocate too much memory.
    max_bytes: usize,

    pub const Error = Allocator.Error || error{InvalidFormat};

    /// Create a glyph APC parser that buffers the raw command bytes.
    pub fn init(alloc: Allocator, max_bytes: usize) CommandParser {
        return .{ .alloc = alloc, .max_bytes = max_bytes };
    }

    /// Release any buffered command bytes owned by the parser.
    pub fn deinit(self: *CommandParser) void {
        self.data.deinit(self.alloc);
... (845 lines truncated)
</file>

<file path="src/terminal/apc/glyph/response.zig">
const std = @import("std");

/// Query response coverage state for a codepoint.
pub const Coverage = packed struct(u2) {
    /// A system font covers the codepoint.
    system: bool = false,

    /// A session glyph registration covers the codepoint.
    glossary: bool = false,

    /// No system font or registered glyph covers the codepoint.
    pub const free: Coverage = .{};

    /// Parse the query response coverage list from its comma-separated form.
    /// Unknown coverage names are ignored for forward compatibility.
    pub fn init(value: []const u8) ?Coverage {
        var result: Coverage = .free;
        var it = std.mem.splitScalar(u8, value, ',');
        while (it.next()) |name| {
            if (std.mem.eql(u8, name, "system")) {
                result.system = true;
            } else if (std.mem.eql(u8, name, "glossary")) {
                result.glossary = true;
            }
        }

        return result;
    }
};

... (317 lines truncated)
</file>

<file path="src/terminal/apc/glyph.zig">
//! # Glyph Protocol
//!
//! The Glyph Protocol lets applications register custom glyphs with the
//! terminal at runtime and query whether a given codepoint is already
//! covered by a system font or a prior registration. It eliminates the
//! requirement for users to install patched fonts (e.g. Nerd Fonts) in
//! order to render icons in TUIs.
//!
//! This file documents the current wire protocol surface parsed and formatted
//! by the glyph APC modules.
//!
//! ## Transport
//!
//! Messages use APC (Application Program Command) framing.
//! Terminals that do not implement the protocol can safely ignore APC
//! sequences. Every message is prefixed with the identifier `25a1`
//! (U+25A1 WHITE SQUARE — the canonical tofu symbol).
//!
//! ## Framing
//!
//! ```
//! ESC _ 25a1 ; <verb> [ ; key=value ]* [ ; <payload> ] ESC \
//! ```
//!
//! Four verbs are defined:
//!
//!   - `s` — support query
//!   - `q` — codepoint query
//!   - `r` — register a glyph
//!   - `c` — clear registrations
... (136 lines truncated)
</file>

<file path="src/terminal/c/AGENTS.md">
# libghostty-vt C API

- C API must be designed with ABI compatibility in mind
- Zig tagged unions must be converted to C ABI compatible unions
  via `lib.TaggedUnion`.
- Any functions must be updated all the way through from here to
  `src/terminal/c/main.zig` to `src/lib_vt.zig` and the headers
  in `include/ghostty/vt.h`. Specifically:
  1. Define the function in `src/terminal/c/<module>.zig`.
  2. Re-export it via a `pub const` in `src/terminal/c/main.zig`.
  3. Add an `@export` call in `src/lib_vt.zig` with the
     `ghostty_` prefixed symbol name.
  4. Declare it in the corresponding header under `include/ghostty/vt/`.
- In `include/ghostty/vt.h`, always sort the header contents by:
  (1) macros, (2) forward declarations, (3) types, (4) functions

## ABI Compatibility

- Prefer opaque pointers for long-lived objects, such as
  `GhosttyTerminal`.
- Structs:
  - May contain padding bytes if we're confident we'll never grow
    beyond a certain size.
  - May use the "sized struct" pattern: an `extern struct` with
    `size: usize = @sizeOf(Self)` as the first field. In the C header,
    callers use `GHOSTTY_INIT_SIZED` from `types.h` to zero-initialize and
    set the size.
</file>

<file path="src/terminal/c/allocator.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;

/// Allocate a buffer of `len` bytes using the given allocator
/// (or the default allocator if NULL).
///
/// Returns a pointer to the allocated buffer, or NULL if the
/// allocation failed or `len` is zero.
pub fn alloc(
    alloc_: ?*const CAllocator,
    len: usize,
) callconv(lib.calling_conv) ?[*]u8 {
    // Zig's empty allocation pointer is not safe to expose to foreign runtimes.
    if (len == 0) return null;
    const allocator = lib.alloc.default(alloc_);
    const buf = allocator.alloc(u8, len) catch return null;
    return buf.ptr;
}

/// Free memory that was allocated by a libghostty-vt function.
///
/// This must be used to free buffers returned by functions like
/// `format_alloc`. Pass the same allocator (or NULL for the default)
/// that was used for the allocation.
pub fn free(
    alloc_: ?*const CAllocator,
    ptr: ?[*]u8,
    len: usize,
... (41 lines truncated)
</file>

<file path="src/terminal/c/build_info.zig">
const std = @import("std");
const builtin = @import("builtin");
const lib = @import("../lib.zig");
const build_options = @import("terminal_options");
const Result = @import("result.zig").Result;

const log = std.log.scoped(.build_info_c);

/// C: GhosttyOptimizeMode
pub const OptimizeMode = enum(c_int) {
    debug = 0,
    release_safe = 1,
    release_small = 2,
    release_fast = 3,
};

/// C: GhosttyBuildInfo
pub const BuildInfo = enum(c_int) {
    invalid = 0,
    simd = 1,
    kitty_graphics = 2,
    tmux_control_mode = 3,
    optimize = 4,
    version_string = 5,
    version_major = 6,
    version_minor = 7,
    version_patch = 8,
    version_pre = 9,
    version_build = 10,

... (147 lines truncated)
</file>

<file path="src/terminal/c/cell.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const page = @import("../page.zig");
const Cell = page.Cell;
const color = @import("../color.zig");
const style_c = @import("style.zig");
const Result = @import("result.zig").Result;

/// C: GhosttyCell
pub const CCell = u64;

/// C: GhosttyCellsView
pub const CellsView = extern struct {
    ptr: ?[*]const CCell,
    len: usize,
};

/// C: GhosttyCellContentTag
pub const ContentTag = enum(c_int) {
    codepoint = 0,
    codepoint_grapheme = 1,
    bg_color_palette = 2,
    bg_color_rgb = 3,
};

/// C: GhosttyCellWide
pub const Wide = enum(c_int) {
    narrow = 0,
    wide = 1,
... (215 lines truncated)
</file>

<file path="src/terminal/c/color_scheme.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const device_status = @import("../device_status.zig");
const Result = @import("result.zig").Result;

pub fn report_encode(
    scheme: device_status.ColorScheme,
    out_: ?[*]u8,
    out_len: usize,
    out_written: *usize,
) callconv(lib.calling_conv) Result {
    var writer: std.Io.Writer = .fixed(if (out_) |out| out[0..out_len] else &.{});
    device_status.encodeColorSchemeReport(&writer, scheme) catch |err| switch (err) {
        error.WriteFailed => {
            var discarding: std.Io.Writer.Discarding = .init(&.{});
            device_status.encodeColorSchemeReport(&discarding.writer, scheme) catch unreachable;
            out_written.* = @intCast(discarding.count);
            return .out_of_space;
        },
    };

    out_written.* = writer.end;
    return .success;
}

test "encode color scheme report dark" {
    var buf: [device_status.max_color_scheme_report_encode_size]u8 = undefined;
    var written: usize = 0;
    const result = report_encode(.dark, &buf, buf.len, &written);
    try std.testing.expectEqual(.success, result);
... (34 lines truncated)
</file>

<file path="src/terminal/c/color.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const color = @import("../color.zig");
const x11_color = @import("../x11_color.zig");
const Result = @import("result.zig").Result;

/// C: GhosttyColorPaletteMask
pub const PaletteMask = extern struct {
    bits: [4]u64,

    /// Convert to the Zig PaletteMask (std.StaticBitSet(256)).
    pub fn toZig(self: *const PaletteMask) color.PaletteMask {
        var result = color.PaletteMask.initEmpty();
        for (0..256) |i| {
            if (((self.bits[i >> 6] >> @as(u6, @intCast(i & 63))) & 1) != 0) {
                result.set(i);
            }
        }
        return result;
    }
};

/// C: GhosttyColorX11Entry
pub const X11Entry = extern struct {
    /// Null-terminated color name; null marks the end of the table.
    name: ?[*:0]const u8,
    color: color.RGB.C,
};

/// Comptime-built static table, terminated by a null-name entry.
... (557 lines truncated)
</file>

<file path="src/terminal/c/focus.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const terminal_focus = @import("../focus.zig");
const Result = @import("result.zig").Result;

pub fn encode(
    event: terminal_focus.Event,
    out_: ?[*]u8,
    out_len: usize,
    out_written: *usize,
) callconv(lib.calling_conv) Result {
    var writer: std.Io.Writer = .fixed(if (out_) |out| out[0..out_len] else &.{});
    terminal_focus.encode(&writer, event) catch |err| switch (err) {
        error.WriteFailed => {
            var discarding: std.Io.Writer.Discarding = .init(&.{});
            terminal_focus.encode(&discarding.writer, event) catch unreachable;
            out_written.* = @intCast(discarding.count);
            return .out_of_space;
        },
    };

    out_written.* = writer.end;
    return .success;
}

test "encode focus gained" {
    var buf: [terminal_focus.max_encode_size]u8 = undefined;
    var written: usize = 0;
    const result = encode(.gained, &buf, buf.len, &written);
    try std.testing.expectEqual(.success, result);
... (26 lines truncated)
</file>

<file path="src/terminal/c/formatter.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const io_c = @import("io.zig");
const terminal_c = @import("terminal.zig");
const grid_ref = @import("grid_ref.zig");
const selection_c = @import("selection.zig");
const ZigTerminal = @import("../Terminal.zig");
const formatterpkg = @import("../formatter.zig");
const Result = @import("result.zig").Result;

/// Wrapper around formatter that tracks the allocator for C API usage.
const FormatterWrapper = struct {
    kind: Kind,
    alloc: std.mem.Allocator,

    const Kind = union(enum) {
        terminal: formatterpkg.TerminalFormatter,
    };
};

/// C: GhosttyFormatter
pub const Formatter = ?*FormatterWrapper;

/// C: GhosttyFormatterFormat
pub const Format = formatterpkg.Format;

const CSelection = selection_c.CSelection;

... (614 lines truncated)
</file>

<file path="src/terminal/c/grid_ref_tracked.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const PageList = @import("../PageList.zig");
const point = @import("../point.zig");
const grid_ref_c = @import("grid_ref.zig");
const terminal_c = @import("terminal.zig");
const Result = @import("result.zig").Result;

/// C: GhosttyTrackedGridRef
///
/// An owned tracked reference to a position in the terminal grid. The
/// underlying PageList pin is automatically updated as the PageList changes.
pub const CTrackedGridRef = ?*TrackedGridRef;

pub const TrackedGridRef = struct {
    alloc: std.mem.Allocator,
    terminal: terminal_c.Terminal,
    screen_key: terminal_c.TerminalScreen,
    screen_generation: usize,
    pin: *PageList.Pin,

    /// Return the PageList that owns this tracked ref's pin, or null if the
    /// owning screen has been removed/reinitialized since the ref was created.
    fn pageList(ref: *const TrackedGridRef) ?*PageList {
        const wrapper = ref.terminal orelse return null;
        const t = wrapper.terminal;
        if (t.screens.generation(ref.screen_key) != ref.screen_generation) return null;
        const screen = t.screens.get(ref.screen_key) orelse return null;
        return &screen.pages;
... (200 lines truncated)
</file>

<file path="src/terminal/c/grid_ref.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const page = @import("../page.zig");
const PageList = @import("../PageList.zig");
const point = @import("../point.zig");
const size = @import("../size.zig");
const stylepkg = @import("../style.zig");
const cell_c = @import("cell.zig");
const row_c = @import("row.zig");
const style_c = @import("style.zig");
const terminal_c = @import("terminal.zig");
const Result = @import("result.zig").Result;

/// C: GhosttyGridRef
///
/// A sized struct that holds a reference to a position in the terminal grid.
/// The ref points to a specific cell position within the terminal's
/// internal page structure.
pub const CGridRef = extern struct {
    size: usize = @sizeOf(CGridRef),
    node: ?*PageList.List.Node = null,
    x: size.CellCountInt = 0,
    y: size.CellCountInt = 0,

    pub fn fromPin(pin: PageList.Pin) CGridRef {
        return .{
            .node = pin.node,
            .x = pin.x,
            .y = pin.y,
... (228 lines truncated)
</file>

<file path="src/terminal/c/io.zig">
//! C byte-stream callbacks and adapters for `std.Io`.
//!
//! The public callbacks deliberately expose a smaller contract than Zig's I/O
//! interfaces: reads are synchronous progress/EOF/error, and writes accept an
//! entire slice or fail. These adapters translate that contract while keeping
//! enough state to map failures back to distinct C result codes.

const std = @import("std");
const assert = std.debug.assert;
const lib = @import("../lib.zig");

/// C: GhosttyReaderFn
pub const ReaderFn = *const fn (
    userdata: ?*anyopaque,
    buffer: [*]u8,
    capacity: usize,
    out_read: *usize,
) callconv(lib.calling_conv) bool;

/// C: GhosttyWriterFn
pub const WriterFn = *const fn (
    userdata: ?*anyopaque,
    data: [*]const u8,
    len: usize,
) callconv(lib.calling_conv) bool;

/// C: GhosttyReader
pub const Reader = extern struct {
    read: ?ReaderFn = null,
    userdata: ?*anyopaque = null,
... (745 lines truncated)
</file>

<file path="src/terminal/c/key_encode.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const key_encode = @import("../../input/key_encode.zig");
const key_event = @import("key_event.zig");
const KittyFlags = @import("../../terminal/kitty/key.zig").Flags;
const OptionAsAlt = @import("../../input/config.zig").OptionAsAlt;
const Result = @import("result.zig").Result;
const KeyEvent = @import("key_event.zig").Event;
const Terminal = @import("terminal.zig").Terminal;
const ZigTerminal = @import("../Terminal.zig");

const log = std.log.scoped(.key_encode);

/// Wrapper around key encoding options that tracks the allocator for C API usage.
const KeyEncoderWrapper = struct {
    opts: key_encode.Options,
    alloc: Allocator,
};

/// C: GhosttyKeyEncoder
pub const Encoder = ?*KeyEncoderWrapper;

pub fn new(
    alloc_: ?*const CAllocator,
    result: *Encoder,
) callconv(lib.calling_conv) Result {
    const alloc = lib.alloc.default(alloc_);
    const ptr = alloc.create(KeyEncoderWrapper) catch
... (336 lines truncated)
</file>

<file path="src/terminal/c/key_event.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const key = @import("../../input/key.zig");
const Result = @import("result.zig").Result;

const log = std.log.scoped(.key_event);

/// Wrapper around KeyEvent that tracks the allocator for C API usage.
/// The UTF-8 text is not owned by this wrapper - the caller is responsible
/// for ensuring the lifetime of any UTF-8 text set via set_utf8.
const KeyEventWrapper = struct {
    event: key.KeyEvent = .{},
    alloc: Allocator,
};

/// C: GhosttyKeyEvent
pub const Event = ?*KeyEventWrapper;

pub fn new(
    alloc_: ?*const CAllocator,
    result: *Event,
) callconv(lib.calling_conv) Result {
    const alloc = lib.alloc.default(alloc_);
    const ptr = alloc.create(KeyEventWrapper) catch
        return .out_of_memory;
    ptr.* = .{ .alloc = alloc };
    result.* = ptr;
    return .success;
... (239 lines truncated)
</file>

<file path="src/terminal/c/kitty_graphics.zig">
const std = @import("std");
const testing = std.testing;
const build_options = @import("terminal_options");
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const kitty_storage = @import("../kitty/graphics_storage.zig");
const kitty_cmd = @import("../kitty/graphics_command.zig");
const Image = @import("../kitty/graphics_image.zig").Image;
const grid_ref = @import("grid_ref.zig");
const selection_c = @import("selection.zig");
const terminal_c = @import("terminal.zig");
const Terminal = @import("../Terminal.zig");
const PageList = @import("../PageList.zig");
const Result = @import("result.zig").Result;

/// C: GhosttyKittyGraphics
pub const KittyGraphics = if (build_options.kitty_graphics)
    *kitty_storage.ImageStorage
else
    *anyopaque;

/// C: GhosttyKittyGraphicsImage
pub const ImageHandle = if (build_options.kitty_graphics)
    ?*const Image
else
    ?*const anyopaque;

/// C: GhosttyKittyGraphicsPlacementIterator
pub const PlacementIterator = if (build_options.kitty_graphics)
    ?*PlacementIteratorWrapper
... (2109 lines truncated)
</file>

<file path="src/terminal/c/main.zig">
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;

const buildpkg = @import("build_info.zig");
pub const allocator = @import("allocator.zig");
pub const cell = @import("cell.zig");
pub const color = @import("color.zig");
pub const color_scheme = @import("color_scheme.zig");
pub const focus = @import("focus.zig");
pub const formatter = @import("formatter.zig");
pub const grid_ref = @import("grid_ref.zig");
pub const grid_ref_tracked = @import("grid_ref_tracked.zig");
pub const io = @import("io.zig");
pub const kitty_graphics = @import("kitty_graphics.zig");
pub const kitty_graphics_get = kitty_graphics.get;
pub const kitty_graphics_image = kitty_graphics.image_get_handle;
pub const kitty_graphics_image_get = kitty_graphics.image_get;
pub const kitty_graphics_image_get_multi = kitty_graphics.image_get_multi;
pub const kitty_graphics_placement_iterator_new = kitty_graphics.placement_iterator_new;
pub const kitty_graphics_placement_iterator_free = kitty_graphics.placement_iterator_free;
pub const kitty_graphics_placement_iterator_set = kitty_graphics.placement_iterator_set;
pub const kitty_graphics_placement_next = kitty_graphics.placement_iterator_next;
pub const kitty_graphics_placement_get = kitty_graphics.placement_get;
pub const kitty_graphics_placement_get_multi = kitty_graphics.placement_get_multi;
pub const kitty_graphics_placement_rect = kitty_graphics.placement_rect;
pub const kitty_graphics_placement_pixel_size = kitty_graphics.placement_pixel_size;
pub const kitty_graphics_placement_grid_size = kitty_graphics.placement_grid_size;
pub const kitty_graphics_placement_viewport_pos = kitty_graphics.placement_viewport_pos;
pub const kitty_graphics_placement_source_rect = kitty_graphics.placement_source_rect;
pub const kitty_graphics_placement_render_info = kitty_graphics.placement_render_info;
... (267 lines truncated)
</file>

<file path="src/terminal/c/modes.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const modes = @import("../modes.zig");
const Result = @import("result.zig").Result;

/// C: GhosttyModeReportState
pub const ReportState = enum(c_int) {
    _,

    fn toZig(self: ReportState) ?modes.Report.State {
        return std.enums.fromInt(
            modes.Report.State,
            @intFromEnum(self),
        );
    }
};

pub fn report_encode(
    tag: modes.ModeTag.Backing,
    state: ReportState,
    out_: ?[*]u8,
    out_len: usize,
    out_written: *usize,
) callconv(lib.calling_conv) Result {
    const mode_tag: modes.ModeTag = @bitCast(tag);
    const report: modes.Report = .{
        .tag = .{ .value = mode_tag.value, .ansi = mode_tag.ansi },
        .state = state.toZig() orelse return .invalid_value,
    };

... (75 lines truncated)
</file>

<file path="src/terminal/c/mouse_encode.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const testing = std.testing;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const input_mouse_encode = @import("../../input/mouse_encode.zig");
const renderer_size = @import("../../renderer/size.zig");
const point = @import("../point.zig");
const terminal_mouse = @import("../mouse.zig");
const mouse_event = @import("mouse_event.zig");
const Result = @import("result.zig").Result;
const Event = mouse_event.Event;
const Terminal = @import("terminal.zig").Terminal;
const ZigTerminal = @import("../Terminal.zig");

const log = std.log.scoped(.mouse_encode);

/// Wrapper around mouse encoding options that tracks the allocator for C API usage.
const MouseEncoderWrapper = struct {
    opts: input_mouse_encode.Options,
    track_last_cell: bool = false,
    last_cell: ?point.Coordinate = null,
    alloc: Allocator,
};

/// C: GhosttyMouseEncoder
pub const Encoder = ?*MouseEncoderWrapper;

/// C: GhosttyMouseTrackingMode
pub const TrackingMode = terminal_mouse.Event;
... (503 lines truncated)
</file>

<file path="src/terminal/c/mouse_event.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const testing = std.testing;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const key = @import("../../input/key.zig");
const mouse = @import("../../input/mouse.zig");
const mouse_encode = @import("../../input/mouse_encode.zig");
const Result = @import("result.zig").Result;

const log = std.log.scoped(.mouse_event);

/// Wrapper around mouse event that tracks the allocator for C API usage.
const MouseEventWrapper = struct {
    event: mouse_encode.Event = .{},
    alloc: Allocator,
};

/// C: GhosttyMouseEvent
pub const Event = ?*MouseEventWrapper;

/// C: GhosttyMouseAction
pub const Action = mouse.Action;

/// C: GhosttyMouseButton
pub const Button = mouse.Button;

/// C: GhosttyMousePosition
pub const Position = mouse_encode.Event.Pos;

... (126 lines truncated)
</file>

<file path="src/terminal/c/osc.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const osc = @import("../osc.zig");
const Result = @import("result.zig").Result;

const log = std.log.scoped(.osc);

/// C: GhosttyOscParser
pub const Parser = ?*osc.Parser;

/// C: GhosttyOscCommand
pub const Command = ?*osc.Command;

/// C: GhosttyOscCommandType
pub const CommandType = osc.Command.Key;

/// C: GhosttyOscTerminator
pub const Terminator = osc.Terminator.C;

pub fn new(
    alloc_: ?*const CAllocator,
    result: *Parser,
) callconv(lib.calling_conv) Result {
    const alloc = lib.alloc.default(alloc_);
    const ptr = alloc.create(osc.Parser) catch
        return .out_of_memory;
    ptr.* = .init(alloc);
    result.* = ptr;
    return .success;
... (216 lines truncated)
</file>

<file path="src/terminal/c/paste.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const paste = @import("../../input/paste.zig");
const terminal_paste_pkg = @import("../paste.zig");
const clipboard = @import("../clipboard.zig");
const io = @import("io.zig");
const terminal_c = @import("terminal.zig");
const Terminal = terminal_c.Terminal;
const ClipboardContent = terminal_c.ClipboardContent;
const ClipboardRead = terminal_c.ClipboardRead;
const ClipboardReadReply = terminal_c.ClipboardReadReply;
const Result = @import("result.zig").Result;

/// Why a paste happened. The flat C form of the Zig tagged union
/// (terminal.paste.Source); the location rides alongside in
/// GhosttyPaste and only applies to a clipboard paste.
///
/// C: GhosttyPasteSource
pub const Source = lib.Enum(lib.target, &.{
    "clipboard",
    "text",
});

/// A paste of clipboard contents into the terminal. Sized struct.
///
/// C: GhosttyPaste
pub const Request = extern struct {
    size: usize = @sizeOf(Request),
    location: clipboard.Location,
    source: Source,
... (525 lines truncated)
</file>

<file path="src/terminal/c/render.zig">
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const colorpkg = @import("../color.zig");
const cursorpkg = @import("../cursor.zig");
const page = @import("../page.zig");
const size = @import("../size.zig");
const Style = @import("../style.zig").Style;
const terminal_c = @import("terminal.zig");
const ZigTerminal = @import("../Terminal.zig");
const renderpkg = @import("../render.zig");
const Result = @import("result.zig").Result;
const cell_c = @import("cell.zig");
const row = @import("row.zig");
const style_c = @import("style.zig");
const PageList = @import("../PageList.zig");

const log = std.log.scoped(.render_state_c);

const RenderStateWrapper = struct {
    alloc: std.mem.Allocator,
    state: renderpkg.RenderState = .empty,

    /// The overscan request set through the C API. This is copied into
    /// `state.overscan_request` at the start of each update rather than
    /// written there directly, because the render state reads its
    /// request to locate the rows of the last update. Changing it
    /// between an update and reading that update's rows would point the
... (3049 lines truncated)
</file>

<file path="src/terminal/c/result.zig">
/// C: GhosttyResult
pub const Result = enum(c_int) {
    success = 0,
    out_of_memory = -1,
    invalid_value = -2,
    out_of_space = -3,
    no_value = -4,
    io_error = -5,
    limit_exceeded = -6,
    rejected = -7,
};
</file>

<file path="src/terminal/c/row.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const page = @import("../page.zig");
const Row = page.Row;
const Result = @import("result.zig").Result;

/// C: GhosttyRow
pub const CRow = Row.C;

/// C: GhosttyRowSemanticPrompt
pub const SemanticPrompt = enum(c_int) {
    none = 0,
    prompt = 1,
    prompt_continuation = 2,
};

/// C: GhosttyRowData
pub const RowData = enum(c_int) {
    invalid = 0,

    /// Whether this row is soft-wrapped.
    /// Output type: bool *
    wrap = 1,

    /// Whether this row is a continuation of a soft-wrapped row.
    /// Output type: bool *
    wrap_continuation = 2,

    /// Whether any cells in this row have grapheme clusters.
... (164 lines truncated)
</file>

<file path="src/terminal/c/search.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const searchpkg = @import("../search.zig");
const TerminalSearch = searchpkg.Terminal;
const FlattenedHighlight = @import("../highlight.zig").Flattened;
const selection_c = @import("selection.zig");
const terminal_c = @import("terminal.zig");
const Result = @import("result.zig").Result;

const log = std.log.scoped(.search_c);

/// C: GhosttySearch
pub const Search = ?*SearchWrapper;

pub const SearchWrapper = struct {
    alloc: std.mem.Allocator,

    /// The terminal this search is bound to. This is borrowed, so the
    /// search never frees it. If the terminal is freed first, it sets
    /// this to null to detach the search: calls that need the terminal
    /// then fail cleanly and free releases only search-owned memory.
    terminal: terminal_c.Terminal,

    /// The search state. Null when no needle is set: the search
    /// starts idle and returns to idle when the needle is cleared.
    search: ?TerminalSearch = null,

    /// The scroll policy applied by the select options. Persistent
... (1008 lines truncated)
</file>

<file path="src/terminal/c/selection_gesture.zig">
const std = @import("std");
const testing = std.testing;
const builtin = @import("builtin");
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const SelectionGesture = @import("../SelectionGesture.zig");
const selection_codepoints = @import("../selection_codepoints.zig");
const grid_ref = @import("grid_ref.zig");
const point = @import("../point.zig");
const selection_c = @import("selection.zig");
const terminal_c = @import("terminal.zig");
const types = @import("types.zig");
const Result = @import("result.zig").Result;

const log = std.log.scoped(.selection_gesture_c);

/// C: GhosttySelectionGesture
pub const Gesture = ?*GestureWrapper;

/// C: GhosttySelectionGestureEvent
pub const Event = ?*EventWrapper;

const GestureWrapper = struct {
    alloc: std.mem.Allocator,
    gesture: SelectionGesture = .init,
};

const EventWrapper = struct {
    alloc: std.mem.Allocator,
    event: union(EventType) {
... (1461 lines truncated)
</file>

<file path="src/terminal/c/selection.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const formatterpkg = @import("../formatter.zig");
const grid_ref = @import("grid_ref.zig");
const point = @import("../point.zig");
const selection_codepoints = @import("../selection_codepoints.zig");
const Selection = @import("../Selection.zig");
const Result = @import("result.zig").Result;
const terminal_c = @import("terminal.zig");

const log = std.log.scoped(.selection_c);

pub const Adjustment = Selection.Adjustment;
pub const Order = Selection.Order;
pub const Format = formatterpkg.Format;

/// C: GhosttySelection
pub const CSelection = extern struct {
    size: usize = @sizeOf(CSelection),
    start: grid_ref.CGridRef,
    end: grid_ref.CGridRef,
    rectangle: bool = false,

    pub fn toZig(self: CSelection) ?Selection {
        const start_pin = self.start.toPin() orelse return null;
        const end_pin = self.end.toPin() orelse return null;
        return Selection.init(start_pin, end_pin, self.rectangle);
    }
... (549 lines truncated)
</file>

<file path="src/terminal/c/sgr.zig">
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const sgr = @import("../sgr.zig");
const Result = @import("result.zig").Result;

const log = std.log.scoped(.sgr);

/// Wrapper around parser that tracks the allocator for C API usage.
const ParserWrapper = struct {
    parser: sgr.Parser,
    alloc: Allocator,
};

/// C: GhosttySgrParser
pub const Parser = ?*ParserWrapper;

pub fn new(
    alloc_: ?*const CAllocator,
    result: *Parser,
) callconv(lib.calling_conv) Result {
    const alloc = lib.alloc.default(alloc_);
    const ptr = alloc.create(ParserWrapper) catch
        return .out_of_memory;
    ptr.* = .{
        .parser = .empty,
        .alloc = alloc,
    };
... (139 lines truncated)
</file>

<file path="src/terminal/c/size_report.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const terminal_size_report = @import("../size_report.zig");
const Result = @import("result.zig").Result;

/// C: GhosttySizeReportStyle
pub const Style = terminal_size_report.Style;

/// C: GhosttySizeReportSize
pub const Size = terminal_size_report.Size;

pub fn encode(
    style: Style,
    size: Size,
    out_: ?[*]u8,
    out_len: usize,
    out_written: *usize,
) callconv(lib.calling_conv) Result {
    var writer: std.Io.Writer = .fixed(if (out_) |out| out[0..out_len] else &.{});
    terminal_size_report.encode(&writer, style, size) catch |err| switch (err) {
        error.WriteFailed => {
            var discarding: std.Io.Writer.Discarding = .init(&.{});
            terminal_size_report.encode(&discarding.writer, style, size) catch unreachable;
            out_written.* = @intCast(discarding.count);
            return .out_of_space;
        },
    };

    out_written.* = writer.end;
    return .success;
... (53 lines truncated)
</file>

<file path="src/terminal/c/snapshot.zig">
//! C ABI wrappers for snapshot encoding and incremental restoration.

const std = @import("std");
const testing = std.testing;
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const io_c = @import("io.zig");
const Result = @import("result.zig").Result;
const snapshot_core = @import("../snapshot/main.zig");
const apc = @import("../apc.zig");

/// Snapshot readers accept the largest default APC payload. Deriving this from
/// the APC protocols keeps snapshot validation in sync as protocols change.
/// Opt-in decoded-terminal retention reuses this configured validation bound
/// as its runtime tracking limit.
const default_max_continuation_bytes = apc.Protocol.maxDefaultBytes();
const terminal_c = @import("terminal.zig");

/// C: GhosttySnapshotDecoderOption.
///
/// Options configure validation and returned-terminal policy before snapshot
/// decoding begins.
pub const DecoderOption = enum(c_int) {
    max_continuation_bytes = 0,
    retain_continuation = 1,
    compress_history = 2,
    _,
};

/// C: GhosttySnapshotDecoderData.
... (1621 lines truncated)
</file>

<file path="src/terminal/c/style.zig">
const std = @import("std");
const assert = std.debug.assert;
const testing = std.testing;
const lib = @import("../lib.zig");
const style = @import("../style.zig");
const color = @import("../color.zig");
const sgr = @import("../sgr.zig");

/// C: GhosttyStyleColorTag
pub const ColorTag = enum(c_int) {
    none = 0,
    palette = 1,
    rgb = 2,
};

/// C: GhosttyStyleColorValue
pub const ColorValue = extern union {
    palette: u8,
    rgb: color.RGB.C,
    _padding: u64,
};

/// C: GhosttyStyleColor
pub const Color = extern struct {
    tag: ColorTag,
    value: ColorValue,

    // fromColor converts the tag as a plain integer, which requires
    // the internal and C tag values to line up.
    comptime {
... (173 lines truncated)
</file>

<file path="src/terminal/c/sys.zig">
const std = @import("std");
const builtin = @import("builtin");
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
const terminal_sys = @import("../sys.zig");
const stderr = @import("../../os/stderr.zig");
const Result = @import("result.zig").Result;

/// C: GhosttySysImage
pub const Image = extern struct {
    width: u32,
    height: u32,
    data: ?[*]u8,
    data_len: usize,
};

/// C: GhosttySysDecodePngFn
pub const DecodePngFn = *const fn (
    ?*anyopaque,
    *const CAllocator,
    [*]const u8,
    usize,
    *Image,
) callconv(lib.calling_conv) bool;

/// C: GhosttySysRandomSecureFn
pub const RandomSecureFn = *const fn (
    ?*anyopaque,
    [*]u8,
    usize,
... (473 lines truncated)
</file>

<file path="src/terminal/c/terminal.zig">
const builtin = @import("builtin");
const std = @import("std");
const testing = std.testing;
const build_options = @import("terminal_options");
const lib = @import("../lib.zig");
const CAllocator = lib.alloc.Allocator;
pub const ZigTerminal = @import("../Terminal.zig");
const Action = @import("../stream.zig").Action;
const osc = @import("../osc.zig");
const Stream = @import("../stream_terminal.zig").Stream;
const Screen = @import("../Screen.zig");
const ScreenSet = @import("../ScreenSet.zig");
const PageList = @import("../PageList.zig");
const apc = @import("../apc.zig");
const kitty = @import("../kitty/key.zig");
const kitty_gfx_c = @import("kitty_graphics.zig");
const modes = @import("../modes.zig");
const mouse = @import("../mouse.zig");
const point = @import("../point.zig");
const size = @import("../size.zig");
const device_attributes = @import("../device_attributes.zig");
const device_status = @import("../device_status.zig");
const size_report = @import("../size_report.zig");
const cell_c = @import("cell.zig");
const row_c = @import("row.zig");
const grid_ref_c = @import("grid_ref.zig");
const grid_ref_tracked_c = @import("grid_ref_tracked.zig");
const search_c = @import("search.zig");
const selection_c = @import("selection.zig");
const style_c = @import("style.zig");
... (6935 lines truncated)
</file>

<file path="src/terminal/c/types-schema-verify.py">
def load_native_manifest(path: Path) -> bytes
⋮----
library = ctypes.CDLL(str(path.resolve()))
type_json = library.ghostty_type_json
⋮----
result = type_json()
⋮----
def load_wasm_manifest(path: Path) -> bytes
⋮----
engine = wasmtime.Engine()
module = wasmtime.Module.from_file(engine, str(path))
store = wasmtime.Store(engine)
instance = wasmtime.Instance(store, module, [])
exports = instance.exports(store)
memory = exports["memory"]
type_json = exports["ghostty_type_json"]
⋮----
pointer = type_json(store)
data = memory.read(store, pointer, memory.data_len(store))
terminator = data.find(b"\0")
⋮----
def load_manifest(path: Path) -> dict[str, Any]
⋮----
encoded = (
value = json.loads(encoded)
⋮----
def format_path(parts: list[object]) -> str
⋮----
def validate(schema_path: Path, library_path: Path) -> None
⋮----
... (14 lines truncated)
</file>

<file path="src/terminal/c/types.schema.json">
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "libghostty-vt ABI type manifest",
  "description": "Schema for the JSON returned by ghostty_type_json.",
  "type": "object",
  "additionalProperties": false,
  "required": ["schema", "abi", "library_version", "commit", "dirty", "types"],
  "properties": {
    "schema": {
      "const": 1
    },
    "abi": {
      "$ref": "#/$defs/abi"
    },
    "library_version": {
      "type": "string",
      "minLength": 1
    },
    "commit": {
      "type": ["string", "null"],
      "minLength": 1
    },
    "dirty": {
      "type": ["boolean", "null"]
    },
    "types": {
      "type": "object",
      "minProperties": 1,
      "propertyNames": {
        "pattern": "^Ghostty[A-Za-z0-9_]+$"
... (477 lines truncated)
</file>

<file path="src/terminal/c/types.zig">
//! Comptime-generated ABI metadata for the public libghostty-vt C types.
//!
//! The manifest is embedded in the library and returned by
//! `ghostty_type_json`. It is intended for FFI consumers that cannot use the
//! C headers directly, most notably WebAssembly hosts. Its format is defined
//! by `types.schema.json`.
const std = @import("std");
const builtin = @import("builtin");
const build_options = @import("terminal_options");
const lib = @import("../lib.zig");
const c_abi = @import("../../lib/c_abi.zig");

const color = @import("../color.zig");
const clipboard = @import("../clipboard.zig");
const device_status = @import("../device_status.zig");
const focus_pkg = @import("../focus.zig");
const formatter_pkg = @import("../formatter.zig");
const modes_pkg = @import("../modes.zig");
const mouse_pkg = @import("../mouse.zig");
const page = @import("../page.zig");
const point = @import("../point.zig");
const Selection = @import("../Selection.zig");
const sgr = @import("../sgr.zig");

const input_config = @import("../../input/config.zig");
const input_key = @import("../../input/key.zig");
const input_mouse = @import("../../input/mouse.zig");

const build_info = @import("build_info.zig");
const cell = @import("cell.zig");
... (1205 lines truncated)
</file>

<file path="src/terminal/c/unicode.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const unicode_pkg = @import("../../unicode/main.zig");

pub fn codepoint_width(cp: u32) callconv(lib.calling_conv) u8 {
    if (cp > 0x10FFFF) return 1;
    return unicode_pkg.codepointWidth(@intCast(cp));
}

pub fn grapheme_width(
    cps: ?[*]const u32,
    len: usize,
    width: ?*u8,
) callconv(lib.calling_conv) usize {
    if (len == 0) {
        if (width) |ptr| ptr.* = 0;
        return 0;
    }

    const ptr = cps orelse {
        if (width) |out| out.* = 0;
        return 0;
    };
    const result = unicode_pkg.graphemeWidth(u32, ptr[0..len]);
    if (width) |out| out.* = result.width;
    return result.len;
}

test "codepoint_width narrow" {
    const testing = std.testing;
... (56 lines truncated)
</file>

<file path="src/terminal/compress/AGENTS.md">
# Terminal Compression

Guidance for the codecs and the compressed page representation
(`Page.zig`) in this directory. These compress terminal page backing
memory (`terminal.Page`).

## Priorities

When making tradeoffs, in order:

1. **Compression ratio on page-shaped data.** Encoded bytes are retained
   scrollback memory, and raw `terminal.Page` backing memory is the only
   thing we actually compress. Ratio on text files or synthetic data is a
   secondary signal.
2. **Decompression throughput.** Pages are compressed once when they go
   cold but restored on demand (scrollback access, search, inspection), so
   restore latency is felt directly.
3. **Compression throughput.** Runs on idle pages in the background; being
   fast is nice, being slow is tolerable.

## Testing

- Targeted tests: `zig build test -Dtest-filter=<codec>`
- Prefer `zig build test-lib-vt -Dtest-filter=<codec>` when practical;
  this code ships in libghostty-vt.
- Codecs must keep building for `wasm32-freestanding` (libghostty-vt):
  no libc, no `src/simd` (Highway) dependencies. Verify with
  `zig build -Demit-lib-vt -Dtarget=wasm32-freestanding -Doptimize=ReleaseSmall`.
- Every codec needs a differential property suite: round-trip identity,
  an independent format walker, wrong-size output rejection, and
... (61 lines truncated)
</file>

<file path="src/terminal/compress/lz4_differential.zig">
//! Differential and property tests for the LZ4 block codec.
//!
//! Every generated input must compress into a block which:
//!
//!   1. fits within `compressBound`,
//!   2. is structurally valid LZ4 with the stricter guarantees our
//!      compressor documents (final five bytes are literals, matches start
//!      at least twelve bytes before the end), verified by an independent
//!      walker which shares no code with the codec,
//!   3. decompresses to exactly the original bytes, and
//!   4. is rejected when decompressed into a buffer of the wrong size.
//!
//! Valid blocks are additionally mutated (bit flips, splices, truncations)
//! and fed to the decompressor, which must fail cleanly or succeed, but
//! never read or write out of bounds. The unit-test build enables runtime
//! safety, so any out-of-bounds slice access fails the test.
//!
//! The light suite below runs as a normal unit test and finishes quickly.
//! The exhaustive suite multiplies the same properties across far more
//! sizes, periods, seeds, and mutations; it is slow and therefore skipped
//! unless the environment variable `GHOSTTY_LZ4_SLOW` is set:
//!
//!     GHOSTTY_LZ4_SLOW=1 zig build test -Dtest-filter="lz4 differential"
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const lz4 = @import("lz4.zig");

/// Number of trailing block bytes which must be literals, mirroring the
/// documented guarantee of the compressor. Kept as an independent constant
... (464 lines truncated)
</file>

<file path="src/terminal/compress/lz4.zig">
//! An allocation-free implementation of the raw LZ4 block format.
//!
//! LZ4 has two relevant layers: the block format describes the compressed
//! bytes, while the frame format adds headers, sizes, checksums, and support
//! for a stream of blocks. Terminal pages already have their own ownership
//! and metadata, so this implements only blocks. In particular, an encoded
//! block does not contain its decompressed size. The caller must store that
//! separately and provide an exactly sized buffer when decoding.
//!
//! A block is a series of sequences. Each non-final sequence has this shape:
//!
//!     token | literal length extensions | literals | offset | match length extensions
//!
//! The token's high nibble contains the literal length and its low nibble
//! contains the match length minus four. A nibble value of 15 means that the
//! length continues in extension bytes at the corresponding point in the
//! sequence. Each extension byte adds to the length; a value of 255 means
//! another byte follows. The literal bytes are copied directly. The two-byte
//! little-endian offset then points backwards in the already decompressed
//! output to the match bytes.
//!
//! The last sequence is special: it contains literals only and ends directly
//! after them. The reference format also requires the last five input bytes to
//! be literals and the final match to begin at least twelve bytes before the
//! end of the input. The compressor observes these restrictions so its output
//! can be consumed by optimized LZ4 decoders which copy in larger units.
//!
//! Compression uses the fast LZ4 strategy: hash each four-byte input sequence
//! and test recent positions as match candidates. Two 16-bit positions fit in
//! each hash-table entry because the format cannot refer further than 64 KiB
... (862 lines truncated)
</file>

<file path="src/terminal/compress/Page.zig">
//! A compressed terminal page which retains its resident virtual mapping.
//!
//! Terminal pages have two kinds of state: the large `Page.memory` allocation
//! and a comparatively small `Page` value containing offsets, dimensions,
//! dirty state, and allocator metadata. Not all of the latter state lives in
//! the backing memory, so preserving only the memory bytes is insufficient.
//! We preserve the complete `Page` value instead. This follows the same model
//! as `Page.cloneBuf`: page internals use offsets, so a shallow page copy remains
//! valid when its memory contents are restored at the same address.
//!
//! The resident memory is deliberately not freed by this type. `PageList`
//! keeps the virtual range allocated while asking the operating system to
//! discard its physical pages. Keeping the range has two useful properties:
//! the embedded page never contains a dangling pointer, and restoring the page
//! does not require a fallible allocation.
//!
//! The intended state transition is:
//!
//! 1. Create this value while the source page is resident.
//! 2. Ask the OS to decommit the source page's memory.
//! 3. Replace the PageList node's resident state with this value.
//! 4. To restore, recommit the retained range and call `restore`.
//! 5. After committing the resident state, call `deinit` to free the encoded
//!    bytes.
//!
//! If decommit is unavailable or fails, the caller should deinitialize the
//! compressed candidate and leave the source page resident. This type does not
//! perform any virtual-memory operations itself.
//!
//! The planned native implementation uses `MADV_DONTNEED` on Linux and pairs
... (383 lines truncated)
</file>

<file path="src/terminal/kitty/clipboard_command.zig">
//! Kitty clipboard protocol (OSC 5522) request decoding.
//!
//! OSC 5522 format: `<OSC>5522;metadata;payload<ST>`
//!
//! Per the spec: "metadata is a colon separated list of key-value
//! pairs and payload is base64 encoded data."
//!
//! This contains the logic for parsing this.

const std = @import("std");
const Allocator = std.mem.Allocator;
const simd = @import("../../simd/main.zig");
const clipboard = @import("../clipboard.zig");
const protocol = @import("../osc/parsers/kitty_clipboard_protocol.zig");

const Operation = protocol.Operation;

/// Maximum id length, nothing specified but this is the limit used
/// in Kitty's source so we'll match it.
pub const max_id_len = 512;

/// Maximum decoded password length. Kitty has no limit. Passwords are
/// UUID-sized in practice so anything longer simply never matches a
/// stored grant anyway.
pub const max_pw_len = 128;

/// Maximum decoded MIME type length. Kitty has no limit but real MIME
/// types are tiny; anything longer drops the packet.
pub const max_mime_len = 256;

... (473 lines truncated)
</file>

<file path="src/terminal/kitty/clipboard_grants.zig">
//! Kitty clipboard protocol (OSC 5522) session password grants:
//! requests carrying a granted password skip the permission prompt, and
//! paste events mint one-time passwords.

const std = @import("std");
const Allocator = std.mem.Allocator;
const clipboard_command = @import("clipboard_command.zig");
const sys = @import("../sys.zig");

const max_pw_len = clipboard_command.max_pw_len;

/// Session password grants, used to skip permission prompts for
/// requests carrying a known pw. Callers can choose to scope these
/// however they want, e.g. Kitty does it per window and the spec
/// doesn't demand anything.
pub const Grants = struct {
    entries: std.ArrayListUnmanaged(Entry) = .empty,

    const max_entries = 32;

    pub const Direction = enum { read, write };

    const Entry = struct {
        /// Owned by the allocator passed to grant.
        pw: []const u8,
        read: bool = false,
        write: bool = false,
        one_time: bool = false,
    };

... (209 lines truncated)
</file>

<file path="src/terminal/kitty/clipboard_response.zig">
//! Kitty clipboard protocol (OSC 5522) response encoding.

const std = @import("std");
const clipboard = @import("../clipboard.zig");
const oscpkg = @import("../osc.zig");
const protocol = @import("../osc/parsers/kitty_clipboard_protocol.zig");

const b64 = std.base64.standard.Encoder;
const Content = clipboard.Content;
const Operation = protocol.Operation;
const Status = protocol.Status;
const Terminator = oscpkg.Terminator;

/// Maximum raw (pre-base64) bytes per DATA packet in read responses.
/// This is specified by the protocol.
pub const read_chunk_size = 4096;

/// Maximum requested MIME types served by a single read request.
/// Requests beyond this simply see no DATA packets for the extras,
/// which is how the protocol communicates an unavailable type anyway.
pub const max_read_mimes = 4;

/// The special MIME type that requests the list of available types.
pub const targets_mime = ".";

/// Maximum MIME types reported in a paste event's targets listing.
pub const max_listing_mimes = 16;

/// A single response packet.
pub const Response = struct {
... (440 lines truncated)
</file>

<file path="src/terminal/kitty/clipboard_write.zig">
//! Kitty clipboard protocol (OSC 5522) write transactions: the
//! stateful accumulation of wdata chunks and walias aliases until the
//! commit packet arrives. See clipboard.zig for the protocol overview.

const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const simd = @import("../../simd/main.zig");
const clipboard = @import("../clipboard.zig");
const clipboard_command = @import("clipboard_command.zig");

const Metadata = clipboard_command.Metadata;
const Payload = clipboard_command.Payload;
const max_mime_len = clipboard_command.max_mime_len;

const log = std.log.scoped(.kitty_clipboard);

/// Default maximum total decoded bytes accumulated by one write
/// transaction. Embedders can override this per-transaction via
/// WriteState.Options (Ghostty exposes it as the
/// `clipboard-write-limit-bytes` configuration).
pub const max_write_size = 64 * 1024 * 1024;

/// Maximum MIME types and aliases per write transaction.
pub const max_write_mimes = 64;
pub const max_write_aliases = 64;

/// One MIME representation of committed clipboard data. This is the
/// same type the clipboard write effect consumes so committed contents
/// can be passed through directly.
... (669 lines truncated)
</file>

<file path="src/terminal/kitty/clipboard.zig">
//! Kitty clipboard protocol (OSC 5522).
//!
//! This implements the protocol semantics on top of the raw OSC capture:
//! src/terminal/osc/parsers/kitty_clipboard_protocol.zig:
//!
//! The behavior here is modeled on the kitty reference implementation
//! (kitty/clipboard.py) rather than only the prose spec, since the two
//! disagree in places. Notable reference behaviors we reproduce:
//!
//!   * Malformed metadata (any record without '=', including an empty
//!     metadata section) and an unknown or missing `type` silently drop
//!     the request with no response.
//!   * All base64 (payloads and the `mime`, `name`, and `pw` metadata
//!     values) is strict RFC 4648 per the spec's "Encoding of payloads"
//!     section: characters outside the standard alphabet (including
//!     whitespace) and incorrect padding are rejected, never silently
//!     skipped. An invalid value on `wdata` or `walias` aborts an
//!     in-flight write with EINVAL; an invalid `read` is dropped with
//!     no response since reads have no error status.
//!   * Decoded metadata and MIME-list payloads must be valid UTF-8. An
//!     invalid value on `wdata` or `walias`, or a `walias` without a
//!     target MIME type, aborts an in-flight write with EINVAL.
//!   * The `wdata` payloads for one MIME type form a single base64
//!     stream split at arbitrary packet boundaries; only the
//!     concatenation must be correctly padded. Like kitty (which
//!     resets its streaming decoder on EOF), a packet ending exactly
//!     at terminal padding restarts the stream, so independently
//!     encoded chunks also work.
//!   * `mime`, `name`, and `pw` metadata values are base64-encoded UTF-8;
//!     everything else is verbatim. Unknown keys are ignored.
... (53 lines truncated)
</file>

<file path="src/terminal/kitty/color.zig">
const std = @import("std");
const lib = @import("../lib.zig");
const terminal = @import("../main.zig");
const RGB = terminal.color.RGB;
const Terminator = terminal.osc.Terminator;

pub const OSC = struct {
    pub const Request = union(enum) {
        query: Kind,
        set: struct { key: Kind, color: RGB },
        reset: Kind,
    };

    /// list of requests
    list: std.ArrayList(Request),

    /// We must reply with the same string terminator (ST) as used in the
    /// request.
    terminator: Terminator = .st,

    pub fn deinit(self: *OSC, alloc: std.mem.Allocator) void {
        self.list.deinit(alloc);
    }

    /// We don't currently support encoding this to C in any way.
    pub const C = void;

    pub fn cval(_: OSC) C {
        return {};
    }
... (79 lines truncated)
</file>

<file path="src/terminal/kitty/dnd_command.zig">
const std = @import("std");

/// Decoded OSC 72 metadata.
pub const Metadata = struct {
    /// Event type (`t`). Null when the metadata had no `t` key; such
    /// commands parse successfully but are ignored, matching kitty.
    type: ?EventType = null,

    /// Chunking flag (`m`): true when more chunks follow.
    more: bool = false,

    /// Multiplexer client ID (`i`), echoed in every response so a
    /// terminal multiplexer can route responses to the correct client.
    client_id: u32 = 0,

    /// Operation (`o`): meaning depends on the event type, commonly
    /// 0=none/reject, 1=copy, 2=move, 3=copy or move.
    operation: u32 = 0,

    /// `x`, `y`, `X`, `Y` keys.
    cell_x: i32 = 0,
    cell_y: i32 = 0,
    pixel_x: i32 = 0,
    pixel_y: i32 = 0,

    /// Parse raw OSC 72 metadata (the part before the first `;`).
    /// Returns null when malformed; callers should ignore the command,
    /// matching kitty which rejects the entire command on any error.
    pub fn parse(raw: []const u8) ?Metadata {
        var result: Metadata = .{};
... (407 lines truncated)
</file>

<file path="src/terminal/kitty/dnd_drop.zig">
//! Kitty drag and drop protocol (OSC 72) state machine.

const std = @import("std");
const Allocator = std.mem.Allocator;

const assert = @import("../../quirks.zig").inlineAssert;
const osc = @import("../osc.zig");
const command = @import("dnd_command.zig");
const response = @import("dnd_response.zig");

const Metadata = command.Metadata;
const Operation = command.Operation;
const Operations = command.Operations;

const log = std.log.scoped(.kitty_dnd);

/// Maximum accumulated size of a client-sent MIME list (the accepted
/// list of a `t=m` status update). Matches kitty's MIME_LIST_SIZE_CAP.
pub const max_mime_list_bytes = 1024 * 1024;

/// Process one OSC 72 command received from the client, writing any
/// responses to the writer. Returns the state change the embedder may
/// need to act on, if any.
pub fn handleCommand(
    slot: *?*State,
    alloc: Allocator,
    writer: *std.Io.Writer,
    v: osc.Command.KittyDndProtocol,
) (Allocator.Error || std.Io.Writer.Error)!?Event {
    const raw = Metadata.parse(v.metadata) orelse {
... (686 lines truncated)
</file>

<file path="src/terminal/kitty/dnd_response.zig">
const std = @import("std");
const Terminator = @import("../osc.zig").Terminator;

/// The maximum raw bytes per base64-encoded chunk, chosen by kitty so a
/// chunk is exactly 4096 base64 characters (the protocol's chunk limit).
pub const max_chunk_raw = 3072;

/// The maximum bytes per plain-text (non-base64) chunk.
pub const max_chunk_plain = 4096;

/// Error names used in protocol error payloads. The wire encoding is
/// the tag name itself. This matches kitty's get_errno_name vocabulary,
/// which extends the spec's list with EISDIR, ENOSPC, and OK.
pub const Errno = enum {
    OK,
    EPERM,
    ENOENT,
    EIO,
    EINVAL,
    EMFILE,
    ENOMEM,
    EFBIG,
    EISDIR,
    ENOSPC,
    EUNKNOWN,
};

/// The payload encoding for a message.
pub const Encoding = enum {
    /// Payload bytes are sent as-is (MIME lists, error strings).
... (219 lines truncated)
</file>

<file path="src/terminal/kitty/dnd_test.zig">
//! End-to-end tests for the OSC 72 protocol state machine, validating
//! wire behavior against kitty's implementation (using kitty_tests/dnd.py as
//! an oracle for the expected bytes).
//!
//! It isn't normal for us to have dedicated test files but in this case
//! the dnd protocol is complicated enough that I wanted full e2e covering
//! the full machine.

const std = @import("std");
const testing = std.testing;

const osc = @import("../osc.zig");
const dnd = @import("dnd.zig");

/// A test harness holding the lazily allocated protocol state and an
/// output collector.
const Harness = struct {
    state: ?*dnd.State = null,
    output: std.Io.Writer.Allocating,

    fn init() Harness {
        return .{ .output = .init(testing.allocator) };
    }

    fn deinit(self: *Harness) void {
        if (self.state) |state| state.destroy(testing.allocator);
        self.output.deinit();
    }

    /// The registered state; asserts a client has registered.
... (597 lines truncated)
</file>

<file path="src/terminal/kitty/dnd.zig">
//! Kitty drag and drop protocol (OSC 72).
//!
//! Specification: https://sw.kovidgoyal.net/kitty/dnd-protocol/
//!
//! The protocol lets a program running in the terminal participate in
//! native OS drag and drop. A client registers to accept drops (t=a);
//! the terminal then forwards native drag movement (t=m) and drops
//! (t=M) to it and serves the dropped data on request (t=r), instead
//! of the traditional behavior of pasting dropped paths or text.
//!
//! ## Divergences
//!
//! These will be fixed in the future:
//!
//!   * Dropped data is captured eagerly at drop time from a curated
//!     set of representations the embedder can serve (typically
//!     text/uri-list and text/plain), rather than fetched from the OS
//!     on demand. Consequently the native drag session concludes at
//!     drop time and the client's concluding operation (t=r with
//!     x=y=Y=0) only frees the held data, and kitty's 128-entry
//!     request queue and EMFILE overflow handling are unnecessary
//!     because requests are served synchronously in order.
//!   * Every client is treated as local: machine IDs (t=a:x=1) are
//!     accepted and ignored, responses never carry the X=1 remote
//!     marker, and remote file transfer requests (t=r with y or Y
//!     keys) are answered with EINVAL. A remote client (e.g. over
//!     ssh) can still receive text drops; only file-content transfer
//!     is unavailable.
//!   * The terminal never initiates drags (drag out): enabling and
//!     disabling offers (t=o:x=1, t=o:x=2) are accepted and ignored,
... (40 lines truncated)
</file>

<file path="src/terminal/kitty/graphics_animation.zig">
//! Kitty graphics protocol animation support.
//!
//! https://sw.kovidgoyal.net/kitty/graphics-protocol/#animation
//!
//! An animation is a set of frames attached to an existing image.
//! Frame 1 (the "root frame") is the image's own base data. Frames
//! 2..N are stored here. Unlike Kitty, which stores frames as delta
//! rectangles in a disk cache and composes them lazily, we compose
//! every frame eagerly into a full image-sized RGBA buffer at load
//! time. This trades some memory for a much simpler model: a frame is
//! always ready to display and there are no reference chains to
//! maintain, coalesce, or garbage collect. Frame storage is bounded
//! by the same byte limit as image storage.
//!
//! To keep composition to a single pixel format, an image is
//! converted to RGBA the first time an animation command composes
//! into it, and all transmitted frame data is converted to RGBA
//! before composition. Blending an opaque (alpha=255) source pixel
//! degenerates to a copy, so this loses no information relative to
//! Kitty's separate RGB/RGBA paths. The pixel-level primitives
//! (conversion, fill, rectangle composition) live in
//! graphics_pixel.zig.

const std = @import("std");
const Allocator = std.mem.Allocator;

/// The gap assigned to a newly created frame when the command doesn't
/// specify one (z omitted or z=0). Taken from Kitty (DEFAULT_GAP).
pub const default_gap_ms: u32 = 40;

... (120 lines truncated)
</file>

<file path="src/terminal/kitty/graphics_command.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const simd = @import("../../simd/main.zig");
const lib = @import("../lib.zig");

const log = std.log.scoped(.kitty_gfx);

/// The key-value pairs for the control information for a command. The
/// recognized keys are always single ASCII letters and the values are either
/// single characters or 32-bit unsigned integers. Unknown non-letter keys are
/// ignored, matching how unknown letter keys are ignored when building a
/// command.
///
/// This is deliberately a dense value table plus a presence bitmap. There are
/// only 52 possible keys(technically KIP has fever than 52 possible .. at the moment of writing), so a lookup is one machine-word bit test followed by
/// an indexed load. The values are undefined until their presence bit is set.
///
/// Other alternatives were considered and should probably be revisited in the
/// future. Some of them were:
/// A `[52]?u32` table is 416 bytes versus 216 bytes for this layout, and
/// its larger copies erased the smaller lookup code.
/// `std.EnumMap` added optional-return lowering,
/// `std.StaticBitSet(52)` kept the same size but generated larger code
/// for the packed mask. Passing the table by pointer removed the copies
/// but did not improve end-to-end throughput. Keep this representation
/// unless a new benchmark shows an improvement in the zig compilers codegen.
///
/// For the value itself: if it is a single printable ASCII character it is the
/// ASCII code. Otherwise, it is parsed as a 32-bit unsigned integer.
... (1843 lines truncated)
</file>

<file path="src/terminal/kitty/graphics_exec.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;

const Terminal = @import("../Terminal.zig");
const command = @import("graphics_command.zig");
const image = @import("graphics_image.zig");
const animation = @import("graphics_animation.zig");
const pixel = @import("graphics_pixel.zig");
const Command = command.Command;
const Response = command.Response;
const LoadingImage = image.LoadingImage;
const Image = image.Image;
const ImageStorage = @import("graphics_storage.zig").ImageStorage;

const log = std.log.scoped(.kitty_gfx);

/// Execute a Kitty graphics command against the given terminal. This
/// will never fail, but the response may indicate an error and the
/// terminal state may not be updated to reflect the command. This will
/// never put the terminal in an unrecoverable state, however.
///
/// The allocator must be the same allocator that was used to build
/// the command.
pub fn execute(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) ?Response {
... (3574 lines truncated)
</file>

<file path="src/terminal/kitty/graphics_image.zig">
const std = @import("std");
const builtin = @import("builtin");
const wuffs = @import("wuffs");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const posix = std.posix;

const fastmem = @import("../../fastmem.zig");
const animation = @import("graphics_animation.zig");
const command = @import("graphics_command.zig");
const kitty_windows = @import("windows.zig");
const PageList = @import("../PageList.zig");
const sys = @import("../sys.zig");
const LimitedAllocator = @import("../../datastruct/main.zig").LimitedAllocator;

const log = std.log.scoped(.kitty_gfx);

/// Maximum width or height of an image. Taken directly from Kitty.
const max_dimension = 10000;

/// Maximum size in bytes, taken from Kitty.
const max_size = 400 * 1024 * 1024; // 400MB

/// An image that is still being loaded. The image should be initialized
/// using init on the first chunk and then addData for each subsequent
/// chunk. Once all chunks have been added, complete should be called
/// to finalize the image.
pub const LoadingImage = struct {
    /// The in-progress image. The first chunk must have all the metadata
... (2176 lines truncated)
</file>

<file path="src/terminal/kitty/graphics_pixel.zig">
//! Pixel-buffer operations for the Kitty graphics protocol: format
//! conversion to RGBA, background fill, and rectangle composition.
//! These are the primitives behind animation frame loading (a=f) and
//! frame composition (a=c). See graphics_animation.zig for the
//! animation model built on top of them.

const std = @import("std");
const Allocator = std.mem.Allocator;
const wuffs = @import("wuffs");
const command = @import("graphics_command.zig");

/// Convert pixel data in the given format to a freshly allocated RGBA
/// buffer. The caller owns the result; the input is not freed.
///
/// The input length must be a multiple of the format's bytes per
/// pixel; image loading validates data length against the image
/// dimensions before storing it.
pub fn rgbaFromFormat(
    alloc: Allocator,
    format: command.Transmission.Format,
    data: []const u8,
) Allocator.Error![]u8 {
    const result = switch (format) {
        .rgba => return try alloc.dupe(u8, data),
        .rgb => wuffs.swizzle.rgbToRgba(alloc, data),
        .gray => wuffs.swizzle.gToRgba(alloc, data),
        .gray_alpha => wuffs.swizzle.gaToRgba(alloc, data),

        // PNG is decoded to RGBA during image loading.
        .png => unreachable,
... (206 lines truncated)
</file>

<file path="src/terminal/kitty/graphics_render.zig">
const std = @import("std");
const testing = std.testing;
const terminal = @import("../main.zig");

/// A render placement is a way to position a Kitty graphics image onto
/// the screen. It is broken down into the fields that make it easier to
/// position the image using a renderer.
pub const Placement = struct {
    /// The top-left corner of the image in grid coordinates.
    top_left: terminal.Pin,

    /// The offset in pixels from the top-left corner of the grid cell.
    offset_x: u32 = 0,
    offset_y: u32 = 0,

    /// The source rectangle of the image to render. This doesn't have to
    /// match the size the destination size and the renderer is expected
    /// to scale the image to fit the destination size.
    source_x: u32 = 0,
    source_y: u32 = 0,
    source_width: u32 = 0,
    source_height: u32 = 0,

    /// The final width/height of the image in pixels.
    dest_width: u32 = 0,
    dest_height: u32 = 0,
};
</file>

<file path="src/terminal/kitty/graphics_storage.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;

const terminal = @import("../main.zig");
const point = @import("../point.zig");
const size = @import("../size.zig");
const animation = @import("graphics_animation.zig");
const pixel = @import("graphics_pixel.zig");
const command = @import("graphics_command.zig");
const PageList = @import("../PageList.zig");
const Screen = @import("../Screen.zig");
const LoadingImage = @import("graphics_image.zig").LoadingImage;
const Image = @import("graphics_image.zig").Image;
const Rect = @import("graphics_image.zig").Rect;
const Command = command.Command;

const log = std.log.scoped(.kitty_gfx);

/// Process-global counter backing all generation stamps (see
/// ImageStorage.generation and Image.generation). This is global rather
/// than per-storage so that stamps are unique across every storage in
/// the process: two mutation events never produce the same value, even
/// across separate screens (main vs. alt), storage resets, or separate
/// terminals. This lets consumers use a generation value alone as a
/// cache key without any ambiguity.
///
/// Thread-safe because separate terminals may mutate their storages
/// from different threads. On single-threaded targets this lowers to
... (4635 lines truncated)
</file>

<file path="src/terminal/kitty/graphics_unicode.zig">
//! This file contains various logic and data for working with the
//! Kitty graphics protocol unicode placeholder, virtual placement feature.

const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const testing = std.testing;
const terminal = @import("../main.zig");
const kitty_gfx = terminal.kitty.graphics;
const Image = kitty_gfx.Image;
const ImageStorage = kitty_gfx.ImageStorage;
const RenderPlacement = kitty_gfx.RenderPlacement;

const log = std.log.scoped(.kitty_gfx);

/// Codepoint for the unicode placeholder character.
pub const placeholder: u21 = 0x10EEEE;

/// Returns an iterator that iterates over all of the virtual placements
/// in the given pin. If `limit` is provided, the iterator will stop
/// when it reaches that pin (inclusive). If `limit` is not provided,
/// the iterator will continue until the end of the page list.
pub fn placementIterator(
    pin: terminal.Pin,
    limit: ?terminal.Pin,
) PlacementIterator {
    var row_it = pin.rowIterator(.right_down, limit);
    const row = row_it.next();
    return .{ .row_it = row_it, .row = row };
}

... (1320 lines truncated)
</file>

<file path="src/terminal/kitty/graphics.zig">
//! Kitty graphics protocol support.
//!
//! Documentation:
//! https://sw.kovidgoyal.net/kitty/graphics-protocol
//!
//! Performance:
//! The performance of this particular subsystem of Ghostty is not great.
//! We can avoid a lot more allocations, we can replace some C code (which
//! implicitly allocates) with native Zig, we can improve the data structures
//! to avoid repeated lookups, etc. I tried to avoid pessimization but my
//! aim to ship a v1 of this implementation came at some cost. I learned a lot
//! though and I think we can go back through and fix this up.

const render = @import("graphics_render.zig");
const command = @import("graphics_command.zig");
const exec = @import("graphics_exec.zig");
const image = @import("graphics_image.zig");
const storage = @import("graphics_storage.zig");
pub const animation = @import("graphics_animation.zig");
pub const pixel = @import("graphics_pixel.zig");
pub const unicode = @import("graphics_unicode.zig");
pub const Animation = animation.Animation;
pub const Command = command.Command;
pub const CommandParser = command.Parser;
pub const Image = image.Image;
pub const LoadingImage = image.LoadingImage;
pub const ImageStorage = storage.ImageStorage;
pub const RenderPlacement = render.Placement;
pub const Response = command.Response;
pub const nextGeneration = storage.nextGeneration;
... (7 lines truncated)
</file>

<file path="src/terminal/kitty/key.zig">
//! Kitty keyboard protocol support.

const std = @import("std");

/// Stack for the key flags. This implements the push/pop behavior
/// of the CSI > u and CSI < u sequences. We implement the stack as
/// fixed size to avoid heap allocation.
pub const FlagStack = struct {
    const len = 8;

    flags: [len]Flags = @splat(.disabled),
    idx: u3 = 0,

    /// Return the current stack value
    pub fn current(self: FlagStack) Flags {
        return self.flags[self.idx];
    }

    /// Perform the "set" operation as described in the spec for
    /// the CSI = u sequence.
    pub fn set(
        self: *FlagStack,
        mode: SetMode,
        v: Flags,
    ) void {
        switch (mode) {
            .set => self.flags[self.idx] = v,
            .@"or" => self.flags[self.idx] = @bitCast(
                self.flags[self.idx].int() | v.int(),
            ),
... (140 lines truncated)
</file>

<file path="src/terminal/kitty/windows.zig">
//! Windows path checks for the Kitty graphics protocol file and
//! temporary file mediums.
//!
//! On POSIX the file transmission blocklist is a few prefixes
//! (`/proc`, `/sys`, `/dev`) applied to the canonical path of the
//! opened file. Windows needs more care because some paths are
//! dangerous to even open: a UNC path makes this process resolve and
//! authenticate to the named SMB server, and the Win32 device and NT
//! object namespaces reach raw volumes and named pipes, where the
//! open or the read can block.
//!
//! Everything here is pure string logic, so it is tested on every host.

const std = @import("std");

pub const Error = error{
    /// A UNC path such as `\\server\share`, in any mix of `\` and `/`.
    /// Opening it resolves the host name and authenticates to the
    /// server over SMB.
    UncPath,

    /// A Win32 device path (`\\.\`, `\\?\`) or an NT object path
    /// (`\??\`). These reach raw volumes, named pipes, and through
    /// `GLOBALROOT` any kernel object.
    DevicePath,

    /// A component names a reserved DOS device such as CON or COM1.
    /// Windows resolves these to the device from inside any directory.
    ReservedDeviceName,

... (248 lines truncated)
</file>

<file path="src/terminal/osc/parsers/change_window_icon.zig">
const std = @import("std");
const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

/// Parse OSC 1
pub fn parse(parser: *Parser, _: ?u8) ?*Command {
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    cap.writer.writeByte(0) catch {
        parser.state = .invalid;
        return null;
    };
    const data = cap.trailing();
    parser.command = .{
        .change_window_icon = data[0 .. data.len - 1 :0],
    };
    return &parser.command;
}

test "OSC 1: change_window_icon" {
    const testing = std.testing;

    var p: Parser = .init(null);
    p.next('1');
    p.next(';');
    p.next('a');
    p.next('b');
    const cmd = p.end(null).?.*;
... (4 lines truncated)
</file>

<file path="src/terminal/osc/parsers/change_window_title.zig">
const std = @import("std");

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

/// Parse OSC 0 and OSC 2
pub fn parse(parser: *Parser, _: ?u8) ?*Command {
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    cap.writer.writeByte(0) catch {
        parser.state = .invalid;
        return null;
    };
    const data = cap.trailing();
    parser.command = .{
        .change_window_title = data[0 .. data.len - 1 :0],
    };
    return &parser.command;
}

test "OSC 0: change_window_title" {
    const testing = std.testing;

    var p: Parser = .init(null);
    p.next('0');
    p.next(';');
    p.next('a');
    p.next('b');
... (90 lines truncated)
</file>

<file path="src/terminal/osc/parsers/clipboard_operation.zig">
const std = @import("std");

const assert = @import("../../../quirks.zig").inlineAssert;

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

/// Parse OSC 52
pub fn parse(parser: *Parser, terminator_ch: ?u8) ?*Command {
    assert(parser.state == .@"52");
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    cap.writeByte(0) catch {
        parser.state = .invalid;
        return null;
    };
    const data = cap.trailing();
    if (data.len == 1) {
        parser.state = .invalid;
        return null;
    }
    if (data[0] == ';') {
        parser.command = .{
            .clipboard_contents = .{
                .kind = 'c',
                .data = data[1 .. data.len - 1 :0],
                .terminator = .init(terminator_ch),
            },
... (93 lines truncated)
</file>

<file path="src/terminal/osc/parsers/color.zig">
const std = @import("std");
const lib = @import("../../lib.zig");
const Allocator = std.mem.Allocator;

const DynamicColor = @import("../../color.zig").Dynamic;
const SpecialColor = @import("../../color.zig").Special;
const RGB = @import("../../color.zig").RGB;
const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;
const SegmentedList = @import("../../../datastruct/segmented_list.zig").SegmentedList;

const log = std.log.scoped(.osc_color);

const ParseError = Allocator.Error || error{
    MissingOperation,
};

/// The possible operations we support for colors.
pub const Operation = enum {
    osc_4,
    osc_5,
    osc_10,
    osc_11,
    osc_12,
    osc_13,
    osc_14,
    osc_15,
    osc_16,
    osc_17,
    osc_18,
... (773 lines truncated)
</file>

<file path="src/terminal/osc/parsers/context_signal.zig">
//! OSC 3008: Hierarchical Context Signalling (UAPI spec)
//! Specification: https://uapi-group.org/specifications/specs/osc_context/
//!
//! OSC 3008 allows programs to signal context changes to the terminal emulator.
//! Each context has an identifier and metadata fields. Contexts are hierarchical
//! and form a stack.

const std = @import("std");
const lib = @import("../../lib.zig");
const Parser = @import("../../osc.zig").Parser;
const OSCCommand = @import("../../osc.zig").Command;

const log = std.log.scoped(.osc_context_signal);

/// Maximum length of a context identifier (per spec).
const max_context_id_len = 64;

/// A single OSC 3008 context signal command.
pub const Command = struct {
    pub const C = void;

    action: Action,
    /// The context identifier. Must be 1-64 characters in the 32..126 byte range.
    id: []const u8,
    /// Raw unparsed metadata fields after the context ID.
    /// Fields are semicolon-separated key=value pairs.
    /// Parsed lazily via `readOption`.
    metadata: []const u8,

    pub const Action = enum {
... (522 lines truncated)
</file>

<file path="src/terminal/osc/parsers/hyperlink.zig">
const std = @import("std");

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

const log = std.log.scoped(.osc_hyperlink);

/// Parse OSC 8 hyperlinks
pub fn parse(parser: *Parser, _: ?u8) ?*Command {
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    cap.writer.writeByte(0) catch {
        parser.state = .invalid;
        return null;
    };
    const data = cap.trailing();
    const s = std.mem.indexOfScalar(u8, data, ';') orelse {
        parser.state = .invalid;
        return null;
    };

    parser.command = .{
        .hyperlink_start = .{
            .uri = data[s + 1 .. data.len - 1 :0],
        },
    };

    data[s] = 0;
... (135 lines truncated)
</file>

<file path="src/terminal/osc/parsers/iterm2.zig">
const std = @import("std");

const assert = @import("../../../quirks.zig").inlineAssert;
const simd = @import("../../../simd/main.zig");

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

const log = std.log.scoped(.osc_iterm2);

const Key = enum {
    AddAnnotation,
    AddHiddenAnnotation,
    Block,
    Button,
    ClearCapturedOutput,
    ClearScrollback,
    Copy,
    CopyToClipboard,
    CurrentDir,
    CursorShape,
    Custom,
    Disinter,
    EndCopy,
    File,
    FileEnd,
    FilePart,
    HighlightCursorLine,
    MultipartFile,
    OpenURL,
... (406 lines truncated)
</file>

<file path="src/terminal/osc/parsers/kitty_clipboard_protocol.zig">
//! Kitty's clipboard protocol (OSC 5522)
//! Specification: https://sw.kovidgoyal.net/kitty/clipboard/
//! https://rockorager.dev/misc/bracketed-paste-mime/

const std = @import("std");
const build_options = @import("terminal_options");

const assert = @import("../../../quirks.zig").inlineAssert;

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;
const Terminator = @import("../../osc.zig").Terminator;
const kitty_metadata = @import("../kitty_metadata.zig");
const encoding = @import("../encoding.zig");

const log = std.log.scoped(.kitty_clipboard_protocol);

pub const OSC = struct {
    /// The raw metadata that was received. It can be parsed by using the `readOption` method.
    metadata: []const u8,
    /// The raw payload. It may be Base64 encoded, check the `e` option.
    payload: ?[]const u8,
    /// The terminator that was used in case we need to send a response.
    terminator: Terminator,

    pub const C = void;

    pub fn cval(_: OSC) C {
        return {};
    }
... (652 lines truncated)
</file>

<file path="src/terminal/osc/parsers/kitty_color.zig">
const std = @import("std");

const assert = @import("../../../quirks.zig").inlineAssert;

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;
const kitty_color = @import("../../kitty/color.zig");
const RGB = @import("../../color.zig").RGB;

const log = std.log.scoped(.osc_kitty_color);

/// Parse OSC 21, the Kitty Color Protocol.
pub fn parse(parser: *Parser, terminator_ch: ?u8) ?*Command {
    assert(parser.state == .@"21");

    const alloc = parser.alloc orelse {
        parser.state = .invalid;
        return null;
    };
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    parser.command = .{
        .kitty_color_protocol = .{
            .list = .empty,
            .terminator = .init(terminator_ch),
        },
    };
    const list = &parser.command.kitty_color_protocol.list;
... (183 lines truncated)
</file>

<file path="src/terminal/osc/parsers/kitty_desktop_notification.zig">
//! Kitty's desktop notification protocol (OSC 99)
//! Specification: https://sw.kovidgoyal.net/kitty/desktop-notifications/

const std = @import("std");
const lib = @import("../../lib.zig");

const assert = @import("../../../quirks.zig").inlineAssert;

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;
const Terminator = @import("../../osc.zig").Terminator;
const kitty_metadata = @import("../kitty_metadata.zig");
const encoding = @import("../encoding.zig");

const log = std.log.scoped(.kitty_desktop_notification);

pub const MAX_PLAIN_PAYLOAD_BYTES = 2048;
pub const MAX_ENCODED_PAYLOAD_BYTES = 4096;

pub const OSC = struct {
    /// The raw metadata that was received. It can be parsed by using the `readOption` method.
    metadata: []const u8,
    /// The raw payload. It may be Base64 encoded, check the `e` option.
    payload: []const u8,
    /// The terminator that was used in case we need to send a response.
    terminator: Terminator,

    /// Decode an option from the metadata.
    pub fn readOption(self: OSC, comptime key: Option) key.Type() {
        return key.read(self.metadata);
... (1185 lines truncated)
</file>

<file path="src/terminal/osc/parsers/kitty_dnd_protocol.zig">
//! Kitty's drag and drop protocol (OSC 72)
//!
//! This only captures the raw metadata and payload for the OSC. The
//! actual protocol grammar (metadata keys, event types, chunking) is
//! implemented in `terminal/kitty/dnd.zig` and its submodules, since the
//! protocol requires stateful handling that doesn't belong in the
//! stateless OSC parser.
//!
//! Specification: https://sw.kovidgoyal.net/kitty/dnd-protocol/

const std = @import("std");

const assert = @import("../../../quirks.zig").inlineAssert;

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;
const Terminator = @import("../../osc.zig").Terminator;

pub const OSC = struct {
    /// The raw metadata that was received. Parse with
    /// `kitty.dnd.Metadata.parse`.
    metadata: []const u8,

    /// The raw payload. Its meaning and encoding depend on the event
    /// type (`t` metadata key). Null when the OSC had no `;` after the
    /// metadata; an empty payload is distinct from no payload.
    payload: ?[]const u8,

    /// The terminator used for this OSC, so any response can match it.
    terminator: Terminator,
... (109 lines truncated)
</file>

<file path="src/terminal/osc/parsers/kitty_text_sizing.zig">
//! Kitty's text sizing protocol (OSC 66)
//! Specification: https://sw.kovidgoyal.net/kitty/text-sizing-protocol/

const std = @import("std");

const assert = @import("../../../quirks.zig").inlineAssert;

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;
const encoding = @import("../encoding.zig");
const lib = @import("../../lib.zig");

const log = std.log.scoped(.kitty_text_sizing);

pub const max_payload_length = 4096;

pub const VAlign = lib.Enum(lib.target, &.{
    "top",
    "bottom",
    "center",
});

pub const HAlign = lib.Enum(lib.target, &.{
    "left",
    "right",
    "center",
});

pub const OSC = struct {
    scale: u3 = 1, // 1 - 7
... (236 lines truncated)
</file>

<file path="src/terminal/osc/parsers/mouse_shape.zig">
const std = @import("std");

const assert = @import("../../../quirks.zig").inlineAssert;

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

// Parse OSC 22
pub fn parse(parser: *Parser, _: ?u8) ?*Command {
    assert(parser.state == .@"22");
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    cap.writer.writeByte(0) catch {
        parser.state = .invalid;
        return null;
    };
    const data = cap.trailing();
    parser.command = .{
        .mouse_shape = .{
            .value = data[0 .. data.len - 1 :0],
        },
    };
    return &parser.command;
}

test "OSC 22: pointer cursor" {
    const testing = std.testing;

... (10 lines truncated)
</file>

<file path="src/terminal/osc/parsers/osc9.zig">
const std = @import("std");
const lib = @import("../../lib.zig");

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

/// Parse OSC 9, which could be an iTerm2 notification or a ConEmu extension.
pub fn parse(parser: *Parser, _: ?u8) ?*Command {
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    const writer = cap.writer;

    // Check first to see if this is a ConEmu OSC
    // https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC
    conemu: {
        var data = cap.trailing();
        if (data.len == 0) break :conemu;
        switch (data[0]) {
            // Check for OSC 9;1 9;10 9;11 9;12
            '1' => {
                if (data.len < 2) break :conemu;
                switch (data[1]) {
                    // OSC 9;1 sleep
                    ';' => {
                        parser.command = .{
                            .conemu_sleep = .{
                                .duration_ms = if (lib.parseInt(u16, data[2..], 10)) |num| @min(num, 10_000) else |_| 100,
                            },
... (1127 lines truncated)
</file>

<file path="src/terminal/osc/parsers/report_pwd.zig">
const std = @import("std");

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

/// Parse OSC 7
pub fn parse(parser: *Parser, _: ?u8) ?*Command {
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    cap.writer.writeByte(0) catch {
        parser.state = .invalid;
        return null;
    };
    const data = cap.trailing();
    parser.command = .{
        .report_pwd = .{
            .value = data[0 .. data.len - 1 :0],
        },
    };
    return &parser.command;
}

test "OSC 7: report pwd" {
    const testing = std.testing;

    var p: Parser = .init(null);

    const input = "7;file:///tmp/example";
... (19 lines truncated)
</file>

<file path="src/terminal/osc/parsers/rxvt_extension.zig">
const std = @import("std");

const Parser = @import("../../osc.zig").Parser;
const Command = @import("../../osc.zig").Command;

const log = std.log.scoped(.osc_rxvt_extension);

/// Parse OSC 777
pub fn parse(parser: *Parser, _: ?u8) ?*Command {
    const cap = if (parser.capture) |*c| c else {
        parser.state = .invalid;
        return null;
    };
    // ensure that we are sentinel terminated
    cap.writer.writeByte(0) catch {
        parser.state = .invalid;
        return null;
    };
    const data = cap.trailing();
    const k = std.mem.indexOfScalar(u8, data, ';') orelse {
        parser.state = .invalid;
        return null;
    };
    const ext = data[0..k];
    if (!std.mem.eql(u8, ext, "notify")) {
        log.warn("unknown rxvt extension: {s}", .{ext});
        parser.state = .invalid;
        return null;
    }
    const t = std.mem.indexOfScalarPos(u8, data, k + 1, ';') orelse {
... (30 lines truncated)
</file>

<file path="src/terminal/osc/parsers/semantic_prompt.zig">
//! https://gitlab.freedesktop.org/Per_Bothner/specifications/blob/master/proposals/semantic-prompts.md
const std = @import("std");

const lib = @import("../../lib.zig");
const Parser = @import("../../osc.zig").Parser;
const OSCCommand = @import("../../osc.zig").Command;
const string_encoding = @import("../../../os/string_encoding.zig");

const log = std.log.scoped(.osc_semantic_prompt);

/// A single semantic prompt command.
///
/// Technically according to the spec, not all commands have options
/// but it is easier to be "liberal in what we accept" here since
/// all except one do and the spec does also say to ignore unknown
/// options. So, I think this is a fair interpretation.
pub const Command = struct {
    pub const C = void;

    action: Action,
    options_unvalidated: []const u8,

    pub const Action = enum {
        fresh_line, // 'L'
        fresh_line_new_prompt, // 'A'
        new_command, // 'N'
        prompt_start, // 'P'
        end_prompt_start_input, // 'B'
        end_prompt_start_input_terminate_eol, // 'I'
        end_input_start_output, // 'C'
... (1270 lines truncated)
</file>

<file path="src/terminal/osc/parsers/unknown.zig">
const std = @import("std");

const assert = @import("../../../quirks.zig").inlineAssert;

const osc = @import("../../osc.zig");
const Parser = osc.Parser;
const Command = osc.Command;

/// Build `Command.unknown` from the bytes collected for a sequence whose
/// number the parser does not implement. Only reached when
/// `Parser.unknown_max_bytes` is nonzero.
pub fn parse(parser: *Parser, terminator_ch: ?u8) ?*Command {
    assert(parser.state == .unknown or parser.state == .unknown_truncated);

    const cap = &parser.capture.?;
    parser.command = .{ .unknown = .{
        .content = cap.trailing(),
        .truncated = parser.state == .unknown_truncated,
        .terminator = .init(terminator_ch),
    } };
    return &parser.command;
}

const testing = std.testing;

test "OSC unknown: prefix state names are the bytes consumed" {
    // beginUnknown recovers the consumed identifier from the prefix state's
    // name, so every prefix state must be reachable by feeding its name.
    inline for (@typeInfo(Parser.State).@"enum".fields) |field| {
        const state: Parser.State = @enumFromInt(field.value);
... (323 lines truncated)
</file>

<file path="src/terminal/osc/encoding.zig">
//! Specialized encodings used in some OSC protocols.
const std = @import("std");

/// Kitty defines "Escape code safe UTF-8" as valid UTF-8 with the
/// additional requirement of not containing any C0 escape codes
/// (0x00-0x1f), DEL (0x7f) and C1 escape codes (0x80-0x9f).
///
/// Used by OSC 66 (text sizing) and OSC 99 (Kitty notifications).
///
/// See: https://sw.kovidgoyal.net/kitty/desktop-notifications/#safe-utf8
pub fn isSafeUtf8(s: []const u8) bool {
    const utf8 = std.unicode.Utf8View.init(s) catch {
        @branchHint(.cold);
        return false;
    };

    var it = utf8.iterator();
    while (it.nextCodepoint()) |cp| switch (cp) {
        0x00...0x1f, 0x7f, 0x80...0x9f => {
            @branchHint(.cold);
            return false;
        },
        else => {},
    };

    return true;
}

test isSafeUtf8 {
    const testing = std.testing;
... (9 lines truncated)
</file>

<file path="src/terminal/osc/kitty_metadata.zig">
//! Helpers for parsing metadata shared by Kitty OSC protocols.
//!
//! Kitty OSC 99 and OSC 5522 encode metadata as colon-separated `key=value`
//! fields. The iterator in this module lazily searches that metadata for one
//! key, preserving the order of repeated values without allocating.
//!
//! Parsing is intentionally tolerant. Whitespace around keys and values is
//! trimmed, while malformed fields, non-matching keys, and invalid values are
//! skipped. Returned values are slices of the original metadata and remain
//! valid only as long as that input remains valid.

const std = @import("std");

/// Return an iterator over values whose key exactly matches `key`.
///
/// If `valid_value_characters` is non-null, every byte in a returned value must
/// appear in that character set. Passing null disables value validation. Both
/// arguments are comptime-known so each protocol can specialize the iterator
/// for its metadata grammar without storing a key or validator at runtime.
pub fn ValueIterator(
    comptime key: []const u8,
    comptime valid_value_characters: ?[]const u8,
) type {
    return struct {
        const Self = @This();

        metadata: []const u8,
        pos: usize,

        /// Initialize an iterator borrowing `metadata`.
... (65 lines truncated)
</file>

<file path="src/terminal/osc/parsers.zig">
const std = @import("std");

pub const change_window_icon = @import("parsers/change_window_icon.zig");
pub const context_signal = @import("parsers/context_signal.zig");
pub const change_window_title = @import("parsers/change_window_title.zig");
pub const clipboard_operation = @import("parsers/clipboard_operation.zig");
pub const color = @import("parsers/color.zig");
pub const hyperlink = @import("parsers/hyperlink.zig");
pub const iterm2 = @import("parsers/iterm2.zig");
pub const kitty_clipboard_protocol = @import("parsers/kitty_clipboard_protocol.zig");
pub const kitty_color = @import("parsers/kitty_color.zig");
pub const kitty_dnd_protocol = @import("parsers/kitty_dnd_protocol.zig");
pub const kitty_desktop_notification = @import("parsers/kitty_desktop_notification.zig");
pub const kitty_text_sizing = @import("parsers/kitty_text_sizing.zig");
pub const mouse_shape = @import("parsers/mouse_shape.zig");
pub const osc9 = @import("parsers/osc9.zig");
pub const report_pwd = @import("parsers/report_pwd.zig");
pub const rxvt_extension = @import("parsers/rxvt_extension.zig");
pub const semantic_prompt = @import("parsers/semantic_prompt.zig");
pub const unknown = @import("parsers/unknown.zig");

test {
    std.testing.refAllDecls(@This());
}
</file>

<file path="src/terminal/res/glitch.txt">
Ḡ̴͎͍̜͎͔͕̩̗͕͖̟̜͑̊̌̇̑͒͋͑̄̈́͐̈́́̽͌͂̎̀̔͋̓́̅̌̇͘̕͜͝͝h̶̡̞̫͉̳̬̜̱̥͕͑̾͛̒̆̒̉̒̑͂̄͘ͅǫ̷̨̥͔͔͖̭͚͙̯̟̭̘͇̫̰͚̺̳̙̳̟͚̫̱̹̱͒̂̑͒͜͠ͅş̴̖̰̜̱̹͙̅͒̀̏͆̐̋͂̓͋̃̈̔̂̈͛̐̿̔́̔̄͑̇͑̋̈́͌͋̾̃̽̈́̕͘̚͘͘͘͠͠t̵̢̜̱̦͇͉̬̮̼͖̳̗̥̝̬͇͕̥̜͕̳̱̥̮͉̮̩̘̰̪̤͉͎̲͈͍̳̟̠͈̝̫͋̊̀͐̍̅̀̄̃̈́̔̇̈́̄̃̽̂̌̅̄̋͒̃̈́̍̀̍̇̽̐͊̾̆̅̈̿̓͒̄̾͌̚͝͝͝͝͝t̴̥̼̳̗̬̬͔͎̯͉͇̮̰͖͇̝͔̳̳̗̰͇͎͉̬͇̝̺̯͎͖͔̍͆͒̊̒̔̊̈́̿̊̅͂̐͋̿͂̈̒̄͜͠͠ÿ̴̢̗̜̥͇͖̰͎̝̹̗̪̙̞̣̳͎̯̹͚̲̝̗̳̳̗̖͎̗̬͈͙̝̟͍̥̤͖͇̰͈̺͛̒̂͌̌̏̈̾̓̈́̿͐̂̓̔̓̂̈́͑͛͊͋̔̿̊͑͌̊̏͘͘̕͘͠͝
</file>

<file path="src/terminal/res/rgb.txt">
255 250 250		snow
248 248 255		ghost white
248 248 255		GhostWhite
245 245 245		white smoke
245 245 245		WhiteSmoke
220 220 220		gainsboro
255 250 240		floral white
255 250 240		FloralWhite
253 245 230		old lace
253 245 230		OldLace
250 240 230		linen
250 235 215		antique white
250 235 215		AntiqueWhite
255 239 213		papaya whip
255 239 213		PapayaWhip
255 235 205		blanched almond
255 235 205		BlanchedAlmond
255 228 196		bisque
255 218 185		peach puff
255 218 185		PeachPuff
255 222 173		navajo white
255 222 173		NavajoWhite
255 228 181		moccasin
255 248 220		cornsilk
255 255 240		ivory
255 250 205		lemon chiffon
255 250 205		LemonChiffon
255 245 238		seashell
240 255 240		honeydew
245 255 250		mint cream
... (753 lines truncated)
</file>

<file path="src/terminal/search/active.zig">
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const point = @import("../point.zig");
const size = @import("../size.zig");
const FlattenedHighlight = @import("../highlight.zig").Flattened;
const PageList = @import("../PageList.zig");
const SlidingWindow = @import("sliding_window.zig").SlidingWindow;
const Terminal = @import("../Terminal.zig");

/// Searches for a substring within the active area of a PageList.
///
/// The distinction for "active area" is important because it is the
/// only part of a PageList that is mutable. Therefore, its the only part
/// of the terminal that needs to be repeatedly searched as the contents
/// change.
///
/// This struct specializes in searching only within that active area,
/// and handling the active area moving as new lines are added to the bottom.
pub const ActiveSearch = struct {
    window: SlidingWindow,

    pub fn init(
        alloc: Allocator,
        needle: []const u8,
    ) Allocator.Error!ActiveSearch {
        // We just do a forward search since the active area is usually
        // pretty small so search results are instant anyways. This avoids
        // a small amount of work to reverse things.
        var window: SlidingWindow = try .init(alloc, .forward, needle);
... (148 lines truncated)
</file>

<file path="src/terminal/search/pagelist.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const testing = std.testing;
const terminal = @import("../main.zig");
const point = terminal.point;
const size = terminal.size;
const FlattenedHighlight = @import("../highlight.zig").Flattened;
const Page = terminal.Page;
const PageList = terminal.PageList;
const Pin = PageList.Pin;
const Selection = terminal.Selection;
const Screen = terminal.Screen;
const Terminal = @import("../Terminal.zig");
const SlidingWindow = @import("sliding_window.zig").SlidingWindow;

/// Searches for a term in a PageList structure.
///
/// This searches in reverse order starting from the given node.
///
/// This assumes that nodes do not change contents. For nodes that change
/// contents, look at ActiveSearch, which is designed to re-search the active
/// area since it assumed to change. When integrating ActiveSearch with
/// PageListSearch, the caller should start the PageListSearch from the
/// returned node from ActiveSearch.update().
///
/// Concurrent access to a PageList or nodes in a PageList are not allowed,
/// so the caller should ensure that necessary locks are held. Each function
/// documents whether it accesses the PageList or not. For example, you can
/// safely call `next()` without holding a lock, but you must hold a lock
/// while calling `feed()`.
... (592 lines truncated)
</file>

<file path="src/terminal/search/screen.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const testing = std.testing;
const tripwire = @import("../../tripwire.zig");
const Allocator = std.mem.Allocator;
const point = @import("../point.zig");
const highlight = @import("../highlight.zig");
const size = @import("../size.zig");
const FlattenedHighlight = highlight.Flattened;
const TrackedHighlight = highlight.Tracked;
const PageList = @import("../PageList.zig");
const Pin = PageList.Pin;
const Screen = @import("../Screen.zig");
const Terminal = @import("../Terminal.zig");
const ActiveSearch = @import("active.zig").ActiveSearch;
const PageListSearch = @import("pagelist.zig").PageListSearch;
const SlidingWindow = @import("sliding_window.zig").SlidingWindow;

const log = std.log.scoped(.search_screen);

const reloadActive_tw = tripwire.module(enum {
    history_append_new,
    history_append_existing,
}, ScreenSearch.reloadActive);

/// Searches for a needle within a Screen, handling active area updates,
/// pages being pruned from the screen (e.g. scrollback limits), and more.
///
/// Unlike our lower-level searchers (like ActiveSearch and PageListSearch),
/// this will cache and store all search results so the caller can re-access
... (2097 lines truncated)
</file>

<file path="src/terminal/search/sliding_window.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const CircBuf = @import("../../datastruct/main.zig").CircBuf;
const terminal = @import("../main.zig");
const point = terminal.point;
const size = terminal.size;
const PageList = terminal.PageList;
const Pin = PageList.Pin;
const Selection = terminal.Selection;
const Screen = terminal.Screen;
const Terminal = terminal.Terminal;
const PageFormatter = @import("../formatter.zig").PageFormatter;
const FlattenedHighlight = terminal.highlight.Flattened;

/// Searches page nodes via a sliding window. The sliding window maintains
/// the invariant that data isn't pruned until (1) we've searched it and
/// (2) we've accounted for overlaps across pages to fit the needle.
///
/// The sliding window is first initialized empty. Pages are then appended
/// in the order to search them. The sliding window supports both a forward
/// and reverse order specified via `init`. The pages should be appended
/// in the correct order matching the search direction.
///
/// All appends grow the window. The window is only pruned when a search
/// is done (positive or negative match) via `next()`.
///
/// To avoid unnecessary memory growth, the recommended usage is to
/// call `next()` until it returns null and then `append` the next page
/// and repeat the process. This will always maintain the minimum
... (1769 lines truncated)
</file>

<file path="src/terminal/search/terminal.zig">
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const point = @import("../point.zig");
const FlattenedHighlight = @import("../highlight.zig").Flattened;
const ScreenSet = @import("../ScreenSet.zig");
const Terminal = @import("../Terminal.zig");

const ScreenSearch = @import("screen.zig").ScreenSearch;
const ViewportSearch = @import("viewport.zig").ViewportSearch;

const log = std.log.scoped(.search_terminal);

/// Searches for a needle within an entire Terminal, orchestrating a
/// ScreenSearch per live screen plus a viewport search for the active
/// screen.
///
/// This reconciles per-screen searchers against the terminal's active
/// ScreenSet, retains results across primary/alt screen switches, and
/// recovers from resize/reflow, resets, scrollback pruning, etc.
///
/// The main ownership contract is that this is safe to call concurrently
/// with Terminal IO as long as you're not calling a function that takes
/// a terminal as an argument. Each function has more specific details about
/// its behavior.
pub const TerminalSearch = struct {
    /// Allocator used for all search state.
    alloc: Allocator,

    /// Active viewport search for the active screen.
... (738 lines truncated)
</file>

<file path="src/terminal/search/Thread.zig">
//! Search thread that handles searching a terminal for a string match.
//! This is expected to run on a dedicated thread to try to prevent too much
//! overhead to other terminal read/write operations.
//!
//! The current architecture of search does acquire global locks for accessing
//! terminal data, so there's still added contention, but we do our best to
//! minimize this by trading off memory usage (copying data to minimize lock
//! time).
pub const Thread = @This();

const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const Mutex = std.Io.Mutex;
const global = @import("../../global.zig");
const xev = global.xev;
const internal_os = @import("../../os/main.zig");
const BlockingQueue = @import("../../datastruct/main.zig").BlockingQueue;
const MessageData = @import("../../datastruct/main.zig").MessageData;
const point = @import("../point.zig");
const FlattenedHighlight = @import("../highlight.zig").Flattened;
const UntrackedHighlight = @import("../highlight.zig").Untracked;
const ScreenSet = @import("../ScreenSet.zig");
const Terminal = @import("../Terminal.zig");

const ScreenSearch = @import("screen.zig").ScreenSearch;
const TerminalSearch = @import("terminal.zig").TerminalSearch;

const log = std.log.scoped(.search_thread);
... (652 lines truncated)
</file>

<file path="src/terminal/search/viewport.zig">
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const point = @import("../point.zig");
const size = @import("../size.zig");
const FlattenedHighlight = @import("../highlight.zig").Flattened;
const PageList = @import("../PageList.zig");
const SlidingWindow = @import("sliding_window.zig").SlidingWindow;
const Terminal = @import("../Terminal.zig");

/// Searches for a substring within the viewport of a PageList.
///
/// This contains logic to efficiently detect when the viewport changes
/// and only re-search when necessary.
///
/// The specialization for "viewport" is because the viewport is the
/// only part of the search where the user can actively see the results,
/// usually. In that case, it is more efficient to re-search only the
/// viewport rather than store all the results for the entire screen.
///
/// Note that this searches all the pages that viewport covers, so
/// this can include extra matches outside the viewport if the data
/// lives in the same page.
pub const ViewportSearch = struct {
    window: SlidingWindow,
    fingerprint: Fingerprint = .{},

    /// If this is null, then active dirty tracking is disabled and if the
    /// viewport overlaps the active area we always re-search. If this is
... (420 lines truncated)
</file>

<file path="src/terminal/snapshot/testdata/checkpoint-ready-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: checkpoint_record
# Kaitai params: 5
# Kaitai offset: 3
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
61 62 63 05 00 00 00 00 00 e4 20 ef 0a # 0x00000000
</file>

<file path="src/terminal/snapshot/testdata/complete-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: ghostty_snapshot
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: snapshot envelope
47 48 4f 53 54 53 4e 50 01 00 # 0x00000000

# offset 0x0000000a: terminal record, payload 952 bytes
01 00 b8 03 00 00 e3 5f 8b cc 02 00 03 00 20 03 # 0x0000000a
00 00 58 02 00 00 00 00 02 00 00 00 01 00 00 01 # 0x0000001a
00 02 00 65 00 00 00 01 01 01 00 00 00 00 00 08 # 0x0000002a
00 04 22 00 64 10 00 00 00 04 22 00 64 00 00 00 # 0x0000003a
00 04 22 00 64 00 00 00 00 00 00 00 00 00 00 00 # 0x0000004a
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 # 0x0000005a
00 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff # 0x0000006a
ff 00 1d 1f 21 cc 66 66 b5 bd 68 f0 c6 74 81 a2 # 0x0000007a
be b2 94 bb 8a be b7 c5 c8 c6 66 66 66 d5 4e 53 # 0x0000008a
b9 ca 4a e7 c5 47 7a a6 da c3 97 d8 70 c0 b1 ea # 0x0000009a
ea ea 00 00 00 00 00 5f 00 00 87 00 00 af 00 00 # 0x000000aa
d7 00 00 ff 00 5f 00 00 5f 5f 00 5f 87 00 5f af # 0x000000ba
00 5f d7 00 5f ff 00 87 00 00 87 5f 00 87 87 00 # 0x000000ca
87 af 00 87 d7 00 87 ff 00 af 00 00 af 5f 00 af # 0x000000da
87 00 af af 00 af d7 00 af ff 00 d7 00 00 d7 5f # 0x000000ea
00 d7 87 00 d7 af 00 d7 d7 00 d7 ff 00 ff 00 00 # 0x000000fa
ff 5f 00 ff 87 00 ff af 00 ff d7 00 ff ff 5f 00 # 0x0000010a
00 5f 00 5f 5f 00 87 5f 00 af 5f 00 d7 5f 00 ff # 0x0000011a
... (91 lines truncated)
</file>

<file path="src/terminal/snapshot/testdata/continuation-apc-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: continuation_record
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1

# Incomplete Kitty APC payload.
07 00 07 00 00 00 bd ff a8 ff 1b 5f 47 64 61 74 61
</file>

<file path="src/terminal/snapshot/testdata/continuation-csi-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: continuation_record
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1

# Incomplete SGR CSI.
07 00 04 00 00 00 30 d5 20 17 1b 5b 33 31
</file>

<file path="src/terminal/snapshot/testdata/continuation-dcs-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: continuation_record
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1

# Incomplete supported DCS payload.
07 00 07 00 00 00 63 ae 0a 1d 1b 50 71 64 61 74 61
</file>

<file path="src/terminal/snapshot/testdata/continuation-esc-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: continuation_record
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1

# Bare ESC leaves the VT parser unfinished.
07 00 01 00 00 00 1c d9 1d 17 1b
</file>

<file path="src/terminal/snapshot/testdata/continuation-ground-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: continuation_record
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1

# Empty payload is the explicit ground-state assertion.
07 00 00 00 00 00 27 80 63 d1
</file>

<file path="src/terminal/snapshot/testdata/continuation-osc-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: continuation_record
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1

# Incomplete title OSC.
07 00 09 00 00 00 39 7d 6e 08 1b 5d 32 3b 74 69 74 6c 65
</file>

<file path="src/terminal/snapshot/testdata/continuation-utf8-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: continuation_record
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1

# Partial four-byte UTF-8 codepoint.
07 00 03 00 00 00 b8 07 2a 22 f0 9f 98
</file>

<file path="src/terminal/snapshot/testdata/envelope-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: envelope
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
47 48 4f 53 54 53 4e 50 01 00 # 0x00000000
</file>

<file path="src/terminal/snapshot/testdata/grid-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: grid
# Kaitai params: 4 3
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
34 03 00 04 01 00 00 00 94 00 00 00 00 00 00 00 # 0x00000000
48 00 00 e1 01 00 00 00 00 00 00 3b 03 00 1e 00 # 0x00000010
00 00 00 00 00 00 ab ee 32 03 00 10 00 00 00 00 # 0x00000020
00 00 00 0c 00 00 00 03 00 68 00 69 10 02 00 16 # 0x00000030
04 21 00 01 00 00 00 00 00 02 00 02 00 01 03 00 # 0x00000040
00 02 03 00 00 # 0x00000050
</file>

<file path="src/terminal/snapshot/testdata/history-header-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: history_payload
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
01 00 04 03 02 01 # 0x00000000
</file>

<file path="src/terminal/snapshot/testdata/hyperlink-explicit-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: hyperlink
# Kaitai params: false false
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
02 02 00 00 00 69 64 03 00 00 00 75 72 69 # 0x00000000
</file>

<file path="src/terminal/snapshot/testdata/hyperlink-implicit-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: hyperlink
# Kaitai params: false false
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
01 04 03 02 01 03 00 00 00 75 72 69 # 0x00000000
</file>

<file path="src/terminal/snapshot/testdata/page-empty-record-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: page_record
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
03 00 1b 00 00 00 5e 0d 0a d4 01 00 01 00 00 00 # 0x00000000
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 # 0x00000010
00 00 00 00 00 # 0x00000020
</file>

<file path="src/terminal/snapshot/testdata/page-header-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: page_header
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
02 01 04 03 06 05 08 07 0a 09 0c 0b 10 0f 0e 0d # 0x00000000
14 13 12 11 # 0x00000010
</file>

<file path="src/terminal/snapshot/testdata/page-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: page_payload
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: PAGE header
03 00 02 00 02 00 02 00 08 00 00 02 80 00 00 00 # 0x00000000
00 01 00 00 # 0x00000010

# offset 0x00000014: style and hyperlink tables, rows, and cells
01 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 # 0x00000014
00 00 03 00 00 00 00 00 01 2a 00 00 00 00 00 00 # 0x00000024
00 00 00 00 01 00 02 01 00 00 00 61 05 00 00 00 # 0x00000034
61 6c 70 68 61 03 00 01 04 03 02 01 04 00 00 00 # 0x00000044
62 65 74 61 34 03 00 04 01 00 04 00 b4 01 00 00 # 0x00000054
00 00 0c 00 68 03 00 1e 00 00 04 00 20 01 00 3b # 0x00000064
03 00 e1 01 00 00 00 00 00 00 ab ee 32 03 00 10 # 0x00000074
00 00 00 00 00 00 00 0c 00 00 01 00 00 00 01 00 # 0x00000084
00 00 02 00 01 03 00 00 02 03 00 00 # 0x00000094
</file>

<file path="src/terminal/snapshot/testdata/record-page-header-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: record_header
# Kaitai params: 3
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
03 00 18 00 00 00 1b 44 78 71 # 0x00000000
</file>

<file path="src/terminal/snapshot/testdata/screen-header-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: screen_header
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
01 00 03 02 08 07 06 05 04 03 02 01 05 04 07 06 # 0x00000000
03 19 00 00 00 00 01 7f 00 00 02 12 34 56 ff 03 # 0x00000010
00 00 0d 0c 0b 0a e4 3d 02 07 01 02 04 08 10 1f # 0x00000020
00 11 02 03 01 # 0x00000030
</file>

<file path="src/terminal/snapshot/testdata/screen-saved-cursor-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: saved_cursor
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
02 01 04 03 00 00 00 00 00 00 00 00 00 00 00 00 # 0x00000000
00 00 00 00 07 e4 3d # 0x00000010
</file>

<file path="src/terminal/snapshot/testdata/style-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: style
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
00 00 00 00 01 7f 00 00 02 12 34 56 ff 03 00 00 # 0x00000000
</file>

<file path="src/terminal/snapshot/testdata/terminal-header-v1.hex">
# Ghostty snapshot fixture
# Kaitai type: terminal_header
# Kaitai params:
# Kaitai offset: 0
# Wire version: 1
# Generated by its snapshot test; review before replacing.
# On mismatch, the candidate is copied to the repository root.

# offset 0x00000000: encoded bytes
02 01 04 03 08 07 06 05 0c 0b 0a 09 01 00 02 00 # 0x00000000
03 00 04 00 01 01 00 02 00 41 00 00 00 01 03 02 # 0x00000010
02 01 04 04 01 21 01 01 00 00 00 00 00 00 00 00 # 0x00000020
00 00 00 00 02 00 00 01 00 00 00 00 02 00 00 01 # 0x00000030
01 02 03 00 00 00 00 00 00 00 00 01 04 05 06 01 # 0x00000040
07 08 09 01 0a 0b 0c ff ff ff ff ff ff ff ff 08 # 0x00000050
07 06 05 04 03 02 01 # 0x00000060
</file>

<file path="src/terminal/snapshot/AGENTS.md">
# Terminal Binary Snapshot

- Apply the robustness principle: "be conservative in what you do, be liberal
  in what you accept from others."
  - Validate on encode
  - Gracefully degrade on decode, for example invalid styles degrade to
    ignoring the style.
</file>

<file path="src/terminal/snapshot/checkpoint.zig">
//! READY and FINISH snapshot marker records.
//!
//! READY separates the renderable terminal state from the history sequences.
//! FINISH terminates one snapshot; bytes after it belong to the containing
//! transport. Both markers have empty payloads, independently framed and
//! protected by the same CRC32C as every other record.
//!
//! ## Binary Format
//!
//! READY and FINISH contain only their record headers. Their declared payload
//! length must be zero.

const std = @import("std");
const test_fixture = @import("fixture.zig");
const record = @import("record.zig");

/// Selects one of the two marker positions in a snapshot.
pub const Kind = enum {
    ready,
    finish,

    fn tag(self: Kind) record.Tag {
        return switch (self) {
            .ready => .ready,
            .finish => .finish,
        };
    }
};

pub const EncodeError = record.Writer.FinishError;
... (148 lines truncated)
</file>

<file path="src/terminal/snapshot/continuation.zig">
//! Continuation record type.
//!
//! Continuation uses the standard record header. All trailing bytes
//! are payload bytes for the continuation state.
//!
//! A continuation's payload must be the minimal bytes to go from
//! a ground state to a non-ground state in a VT emulator. Any extra
//! bytes are treated as a validation error.

const std = @import("std");
const Allocator = std.mem.Allocator;
const record = @import("record.zig");
const stream_continuation = @import("../stream_continuation.zig");
const test_fixture = @import("fixture.zig");

/// A borrowed continuation value supplied to encode, or an allocator-owned
/// value stored in a decoded complete snapshot.
pub const Value = union(enum) {
    /// Neither the VT parser nor UTF-8 decoder has unfinished state.
    ground,

    /// Canonical replay-safe PTY bytes. Empty is equivalent to `ground`.
    bytes: []const u8,
};

pub const ValidateError = stream_continuation.ValidateError || error{
    /// The common record's u32 payload length cannot represent these bytes.
    Overflow,
};

... (291 lines truncated)
</file>

<file path="src/terminal/snapshot/envelope.zig">
//! Snapshot envelope.
//!
//! Every snapshot binary blob begins with exactly one envelope at byte zero.
//! It is followed by a set of records. Each record provides their own
//! tag, payload length, CRC, etc.
//!
//! The envelope identifies the bytes as a terminal snapshot and selects the
//! single version governing the entire blob. A decoder validates both fields
//! before reading any records.
//!
//! The envelope is exactly ten bytes. All integers are unsigned and
//! little-endian.
//!
//! | Offset | Size | Field                |
//! | -----: | ---: | :------------------- |
//! |      0 |    8 | Magic (`GHOSTSNP`)   |
//! |      8 |    2 | Version (`u16`)      |

const std = @import("std");
const test_fixture = @import("fixture.zig");
const io = @import("io.zig");

/// Identifies a Ghostty terminal snapshot and rejects unrelated input before
/// any record decoding begins. All eight bytes are part of the wire value.
pub const magic = "GHOSTSNP";

/// The complete compatibility boundary for snapshot layout and behavior.
/// Version 1 readers require this value to match exactly.
pub const version: u16 = 1;

... (75 lines truncated)
</file>

<file path="src/terminal/snapshot/fixture.zig">
//! Test-only support for reviewable snapshot golden fixtures.
//!
//! Snapshot compatibility references are stored as annotated hexadecimal text
//! under `testdata/`. Each byte is written as exactly two hexadecimal digits.
//! Whitespace is insignificant, and `#` begins a comment through the end of the
//! line. This permits field, record, and absolute-offset annotations without
//! changing the bytes embedded by a test.
//!
//! `parse` validates and decodes an `@embedFile` at comptime. Tests should
//! encode their native value, compare the generated bytes with that embedded
//! reference using `expectEqual`, and then decode the reference itself. This
//! keeps encoding regression coverage separate from backwards-decoding
//! coverage.
//!
//! `expectEqual` formats a fresh candidate on every run. Matching candidates
//! remain in the test's temporary directory. A mismatch copies the candidate
//! to the repository root, reports its path and first differing byte, and
//! fails without modifying the checked-in reference. After reviewing an
//! intentional wire change, a maintainer manually replaces the reference.
//! Fixture filenames include the snapshot version so a future format adds new
//! references instead of overwriting compatibility data for an older version.
//!
//! A typical fixed-value test looks like this:
//!
//! ```zig
//! const fixture = @import("fixture.zig");
//!
//! const reference = fixture.parse(
//!     @embedFile("testdata/example-v1.hex"),
//! );
... (450 lines truncated)
</file>

<file path="src/terminal/snapshot/grid.zig">
//! Grid (rows, cells, and grapheme suffixes) encoding.
//!
//! A grid contains the rows and cells of a terminal page. Its dimensions are
//! supplied by the containing record rather than repeated here. The encoder
//! writes exactly `rows` row records followed by one grapheme suffix section.
//!
//! All records are tightly packed with no padding between them. All integers
//! are unsigned and little-endian.
//!
//! The layout is designed so the common case decodes with bulk copies: cells
//! are fixed-size words, trailing default cells are elided per row, and the
//! variable-length grapheme suffixes live outside the row data.
//!
//! ```text
//! +---------------------------+
//! | Row 0                     |
//! +---------------------------+
//! | ...                       |
//! +---------------------------+
//! | Row (rows - 1)            |
//! +---------------------------+
//! | Grapheme suffix section   |
//! +---------------------------+
//! ```
//!
//! ## Row
//!
//! Each row has the following format:
//!
//! | Offset | Size              | Field                      |
... (2374 lines truncated)
</file>

<file path="src/terminal/snapshot/history.zig">
//! HISTORY record payload encoding.
//!
//! One HISTORY record describes the complete history for a previously encoded
//! screen. It is followed immediately by the number of complete PAGE records
//! declared by `page_count`. Those pages contain the history older than the
//! first page in the corresponding SCREEN sequence and are ordered from newest
//! to oldest.
//!
//! Every encoded SCREEN has one corresponding HISTORY record. A screen with no
//! older pages uses a zero page count and has no following PAGE records.
//!
//! The first SCREEN page may begin above the active area. Those incidental
//! history rows are already present at READY and are not repeated after
//! HISTORY. The corresponding SCREEN header declares the complete logical
//! history extent, including both that resident overlap and the following PAGE
//! records.
//!
//! All integers are unsigned and little-endian.
//!
//! ## Binary Format
//!
//! A HISTORY record is followed immediately by its declared PAGE records:
//!
//! ```text
//! +----------------------+
//! | HISTORY record       |
//! +----------------------+
//! | PAGE record 0        | newest
//! +----------------------+
//! | ...                  |
... (802 lines truncated)
</file>

<file path="src/terminal/snapshot/hyperlink.zig">
//! Snapshot hyperlink entry encoding.
//!
//! Each entry contains a URI and either an implicit numeric ID or an explicit
//! byte-string ID. Implicit IDs are generated by the terminal when the source
//! hyperlink has no explicit ID. A record can use these entries to build a
//! hyperlink table and assign indexes according to that record's format.
//! Indexing and ordering are properties of the containing record rather than
//! this codec.
//!
//! URIs and explicit IDs are non-empty arbitrary byte strings. Their lengths
//! are retained on the wire; they are not NUL-terminated and need not contain
//! UTF-8. Native page storage requires every allocated hyperlink string to
//! contain at least one byte. Encoding and standalone decoding reject empty
//! strings; PAGE decoding consumes but ignores entries it cannot represent.
//!
//! All integers are unsigned and little-endian.
//!
//! ## Implicit ID
//!
//! | Offset | Size      | Field              |
//! | -----: | --------: | :----------------- |
//! |      0 |         1 | Kind, `1`          |
//! |      1 |         4 | Implicit ID (`u32`) |
//! |      5 |         4 | URI length (`u32`) |
//! |      9 | `uri_len` | URI bytes          |
//!
//! ## Explicit ID
//!
//! | Offset       | Size      | Field                      |
//! | -----------: | --------: | :------------------------- |
... (464 lines truncated)
</file>

<file path="src/terminal/snapshot/io.zig">
//! Wire-format I/O helpers.
//!
//! These are sometimes very thin layers over standard `std.Io.Writer`
//! but its to help ensure consistency in our behavior and avoid some
//! pitfalls.

const std = @import("std");
const testing = std.testing;

/// writeInt ensures we write in little-endian since that is our
/// standard form.
pub fn writeInt(
    writer: *std.Io.Writer,
    comptime T: type,
    value: T,
) std.Io.Writer.Error!void {
    try writer.writeInt(T, value, .little);
}

/// Read a little-endian integer.
///
/// This avoids `takeInt` because at the time of writing this the underlying
/// implementation uses `takeArray` which asserts that the reader buffer
/// is as large as T. Our approach works with caller-selected buffers that
/// may be smaller.
pub fn readInt(
    reader: *std.Io.Reader,
    comptime T: type,
) std.Io.Reader.Error!T {
    var buf: [@sizeOf(T)]u8 = undefined;
... (26 lines truncated)
</file>

<file path="src/terminal/snapshot/main.zig">
//! Terminal snapshot binary representation and codecs.
//!
//! This is NOT a full transport-ready format to implement generic replay
//! software such as multiplexers, recorders (e.g. asciinema), etc. The goal
//! of this package is to provide a documented, binary-compatible representation
//! for a terminal state.
//!
//! We call this a "snapshot." The snapshot is purposely laid out in a way
//! that prioritizes making a terminal functional as quickly as possible.
//! To do that, it sends the active terminal state followed by a READY record,
//! then complete history.
//!
//! READY denotes that enough state has been sent down to render the
//! terminal and reconstruct its unfinished VT Stream state.
//!
//! After READY, we send history pages (scrollback). Finally, the
//! snapshot ends with an empty FINISH marker.
//!
//! ## Snapshot Format
//!
//! This documents snapshot format 1. Version 1 is the work-in-progress
//! format that we intended to continue to break until we can promise
//! binary compatibility.
//!
//! A snapshot is one envelope followed by a sequence of records. The envelope
//! occurs once at byte zero. Every record is independently framed as a fixed
//! header followed by the number of payload bytes declared by that header.
//!
//! ```text
//! +------------------+
... (171 lines truncated)
</file>

<file path="src/terminal/snapshot/page.zig">
//! PAGE record payload encoding.
//!
//! One PAGE record represents a set of rows/columns in the terminal.
//! In libghostty, this happens to map internally to a very specific
//! data structure called a "page" (hence the name), but consumers of
//! the format don't need to reproduce that.
//!
//! The important thing is that one page is fully self-contained: it has
//! a dimension (cols x rows), a set of styles, hyperlinks, cells, etc.
//! and depends on no external state to decode that with some exceptions
//! like assets such as images.
//!
//! A page could have a dimension that doesn't match the terminal
//! dimensions, e.g. for lazy resize/reflow. Callers must be prepared for
//! that.
//!
//! ## Binary Format
//!
//! Every PAGE payload begins with a fixed header, followed by a
//! payload of styles, hyperlinks, and rows and columns.
//!
//! All integers are unsigned and little-endian.
//!
//! ### Header
//!
//! | Offset | Size | Field                              |
//! | -----: | ---: | :--------------------------------- |
//! |      0 |    2 | Logical columns (`u16`)            |
//! |      2 |    2 | Logical rows (`u16`)               |
//! |      4 |    2 | Non-default style count (`u16`)    |
... (1799 lines truncated)
</file>

<file path="src/terminal/snapshot/record.zig">
//! Snapshot record framing.
//!
//! Records begin immediately after the single snapshot envelope and continue
//! back-to-back until FINISH. Each record has one fixed-size header followed
//! by exactly `payload_len` bytes. The payload length limits the record reader
//! so malformed payloads cannot consume bytes from the following record.
//!
//! The CRC covers the first six header bytes (tag and payload length)
//! followed by the payload. The CRC field itself is not included for obvious
//! reasons. All integers are unsigned and little-endian.
//!
//! | Offset | Size          | Field                  |
//! | -----: | ------------: | :--------------------- |
//! |      0 |             2 | Tag (`u16`)            |
//! |      2 |             4 | Payload length (`u32`) |
//! |      6 |             4 | CRC32C (`u32`)         |
//! |     10 | `payload_len` | Payload                |
//!
//! Supported tags are in `Tag`.

const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const test_fixture = @import("fixture.zig");
const io = @import("io.zig");

/// CRC32C as specified by the snapshot format. This is the parameter set
/// Zig's standard library names after its iSCSI use, backed by dedicated
/// CRC32C instructions where the target has them.
pub const Crc32c = @import("../../crc32c.zig").Crc32c;
... (572 lines truncated)
</file>

<file path="src/terminal/snapshot/screen.zig">
//! SCREEN record payload encoding.
//!
//! One SCREEN record represents the live state for one terminal screen. The
//! record is followed immediately by the number of complete PAGE records
//! declared by `page_count`. They are the minimal suffix of native pages needed
//! to cover the active area and are ordered from oldest to newest. A decoder
//! uses the declared count, rather than another record tag, to find the end of
//! the screen's page sequence.
//!
//! The final screen-height rows are the active area. When its boundary falls
//! inside the first encoded page, that page also contains an incidental history
//! prefix. `history_rows` declares the complete logical history extent so a
//! client can size its scrollbar at READY without waiting for HISTORY. A client
//! may expose or ignore the resident overlap carried by SCREEN. The extent is
//! advisory; native row totals remain derived from decoded PAGE records.
//!
//! Screen dimensions are terminal-wide state and are not repeated here. Page
//! capacities, native page IDs and pointers, history availability, selection,
//! viewport, dirty state, and derived semantic-prompt state are also omitted.
//!
//! All integers are unsigned and little-endian.
//!
//! ## Binary Format
//!
//! A SCREEN record is followed immediately by its declared PAGE records:
//!
//! ```text
//!  +----------------------+
//!  | SCREEN record        |
//!  +----------------------+
... (2431 lines truncated)
</file>

<file path="src/terminal/snapshot/snapshot.ksy">
meta:
  id: ghostty_snapshot
  title: Ghostty terminal snapshot
  application: Ghostty
  license: MIT
  endian: le
doc: |
  Ghostty terminal snapshot format version 1.

  A complete snapshot contains an envelope, terminal-wide state, one or two
  renderable screen sequences, one raw standard-Stream CONTINUATION, a READY
  marker, matching history sequences, and a FINISH marker. SCREEN pages
  are oldest-to-newest. HISTORY pages are newest-to-oldest. FINISH terminates the
  snapshot; bytes that follow belong to the containing transport and are outside
  this schema. Each SCREEN declares its complete logical history extent before
  READY.

  Record CRC32C values are represented here but cannot be calculated by
  portable Kaitai Struct expressions. The adjacent verify-kaitai.py script
  validates those values after parsing.
seq:
  - id: envelope
    type: envelope
  - id: terminal
    type: terminal_record
  - id: screens
    type: screen_sequence
    repeat: expr
    repeat-expr: terminal.payload.header.screen_count
  - id: continuation
... (1044 lines truncated)
</file>

<file path="src/terminal/snapshot/snapshot.zig">
//! Complete terminal snapshot encoding and restoration.

const std = @import("std");
const build_options = @import("terminal_options");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const checkpoint = @import("checkpoint.zig");
const continuation = @import("continuation.zig");
const envelope = @import("envelope.zig");
const test_fixture = @import("fixture.zig");
const history = @import("history.zig");
const page = @import("page.zig");
const record = @import("record.zig");
const screen = @import("screen.zig");
const size = @import("../size.zig");
const terminal = @import("terminal.zig");
const Terminal = @import("../Terminal.zig");
const TerminalStream = @import("../stream_terminal.zig").Stream;
const terminal_kitty = @import("../kitty.zig");
const TerminalPageList = @import("../PageList.zig");
const TerminalScreen = @import("../Screen.zig");
const TerminalScreenKey = @import("../ScreenSet.zig").Key;

/// Re-export continuation to make it a bit more ergonomic to reference.
pub const Continuation = continuation.Value;

/// Errors possible while encoding one complete terminal snapshot.
pub const EncodeError = terminal.EncodeError ||
    screen.EncodeError ||
    history.EncodeError ||
... (2091 lines truncated)
</file>

<file path="src/terminal/snapshot/style.zig">
//! Snapshot style entry encoding.
//!
//! Each entry describes one terminal style. A record can use these entries to
//! build a style table and assign indexes according to that record's format.
//! Indexing, ordering, etc. are properties of the containing record.
//!
//! Styles are encoded field by field from the terminal's native `Style` type.
//! The native packed representation is deliberately not part of the snapshot
//! format. This gives flexibility for changing one side or the other.
//!
//! All integers are unsigned and little-endian.
//!
//! | Offset | Size | Field                     |
//! | -----: | ---: | :------------------------ |
//! |      0 |    4 | Foreground color          |
//! |      4 |    4 | Background color          |
//! |      8 |    4 | Underline color           |
//! |     12 |    2 | Style flags (`u16`)       |
//! |     14 |    2 | Reserved, must be zero    |
//!
//! The trailing reserved field is explicit wire padding that rounds each
//! style entry from 14 bytes to 16 bytes. This makes entry offsets and byte
//! counts straightforward.
//!
//! Each color begins with a one-byte kind followed by three data bytes:
//!
//! | Kind | Meaning | Data bytes                         |
//! | ---: | :------ | :--------------------------------- |
//! |    0 | None    | All zero                           |
//! |    1 | Palette | Palette index, then two zero bytes |
... (394 lines truncated)
</file>

<file path="src/terminal/snapshot/terminal.zig">
//! TERMINAL record payload encoding.
//!
//! One TERMINAL record contains terminal-wide state shared by every screen. It
//! is the first record in a snapshot and declares which SCREEN sequences follow
//! it. Screen contents, cursors, and history are encoded by `screen.zig` and
//! `history.zig`.
//!
//! Snapshot version 1 supports the primary screen and an optional alternate
//! screen. `screen_count` is therefore one or two. SCREEN records identify
//! their destination by key and may appear in either order. Canonical encoders
//! write primary first, then alternate when present. `active_screen_key` must
//! name one of those declared screens.
//!
//! All integers are unsigned and little-endian.
//!
//! ## Binary Format
//!
//! The payload begins with a fixed header followed by terminal-wide variable
//! state. The enclosing record supplies the payload boundary.
//!
//! ```text
//!   0 +--------------------------+
//!     | Header                   |
//! 103 +--------------------------+
//!     | Tab stops                |
//!     | ceil(columns / 8) bytes  |
//!     +--------------------------+
//!     | Original palette         |
//!     | 256 * RGB                |
//!     +--------------------------+
... (1821 lines truncated)
</file>

<file path="src/terminal/snapshot/verify-kaitai.py">
SNAPSHOT_DIR = Path(__file__).resolve().parent
SCHEMA_PATH = SNAPSHOT_DIR / "snapshot.ksy"
TESTDATA_DIR = SNAPSHOT_DIR / "testdata"
SNAPSHOT_ENVELOPE_SIZE = 10
RECORD_HEADER_SIZE = struct.calcsize("<HII")
⋮----
@dataclass(frozen=True)
class Fixture
⋮----
path: Path
type_name: str
params: tuple[object, ...]
offset: int
data: bytes
⋮----
def load_fixture(path: Path) -> Fixture
⋮----
metadata: dict[str, str] = {}
chunks: list[str] = []
⋮----
comment = comment.strip()
⋮----
data = bytes.fromhex(" ".join(chunks))
⋮----
required = {"type", "params", "offset"}
⋮----
missing = sorted(required - metadata.keys())
extra = sorted(metadata.keys() - required)
⋮----
params: list[object] = []
... (90 lines truncated)
</file>

<file path="src/terminal/tmux/control.zig">
//! This file contains the implementation for tmux control mode. See
//! tmux(1) for more information on control mode. Some basics are documented
//! here but this is not meant to be a comprehensive source of protocol
//! documentation.

const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = @import("../../quirks.zig").inlineAssert;
const oni = @import("oniguruma");

const log = std.log.scoped(.terminal_tmux);

/// A tmux control mode parser. This takes in output from tmux control
/// mode and parses it into a structured notifications.
///
/// It is up to the caller to establish the connection to the tmux
/// control mode session in some way (e.g. via exec, a network socket,
/// whatever). This is fully agnostic to how the data is received and sent.
pub const Parser = struct {
    /// Current state of the client.
    state: State = .idle,

    /// The buffer used to store in-progress notifications, output, etc.
    buffer: std.Io.Writer.Allocating,

    /// The maximum size in bytes of the buffer. This is used to limit
    /// memory usage. If the buffer exceeds this size, the client will
    /// enter a broken state (the control mode session will be forcibly
    /// exited and future data dropped).
    max_bytes: usize = 1024 * 1024,
... (855 lines truncated)
</file>

<file path="src/terminal/tmux/layout.zig">
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;

/// A tmux layout.
///
/// This is a tree structure so by definition it pretty much needs to be
/// allocated. We leave allocation up to the user of this struct, but
/// a general recommendation is to use an arena allocator for simplicity
/// in freeing the entire layout at once.
pub const Layout = struct {
    /// Width, height of the node
    width: usize,
    height: usize,

    /// X and Y offset from the top-left corner of the window.
    x: usize,
    y: usize,

    /// The content of this node, either a pane (leaf) or more nodes
    /// (split) horizontally or vertically.
    content: Content,

    pub const Content = union(enum) {
        pane: usize,
        horizontal: []const Layout,
        vertical: []const Layout,
    };

... (609 lines truncated)
</file>

<file path="src/terminal/tmux/output.zig">
const std = @import("std");
const testing = std.testing;

pub const ParseError = error{
    MissingEntry,
    ExtraEntry,
    FormatError,
};

/// Parse the output from a command with the given format struct
/// (returned usually by FormatStruct). The format struct is expected
/// to be in the order of the variables used in the format string and
/// the variables are expected to be plain variables (no conditionals,
/// extra formatting, etc.). Each variable is expected to be separated
/// by a single `delimiter` character.
pub fn parseFormatStruct(
    comptime T: type,
    str: []const u8,
    delimiter: u8,
) ParseError!T {
    // Parse all our fields
    const fields = @typeInfo(T).@"struct".fields;
    var it = std.mem.splitScalar(u8, str, delimiter);
    var result: T = undefined;
    inline for (fields) |field| {
        const part = it.next() orelse return error.MissingEntry;
        @field(result, field.name) = Variable.parse(
            @field(Variable, field.name),
            part,
        ) catch return error.FormatError;
... (544 lines truncated)
</file>

<file path="src/terminal/tmux/viewer.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const testing = std.testing;
const assert = @import("../../quirks.zig").inlineAssert;
const size = @import("../size.zig");
const CircBuf = @import("../../datastruct/main.zig").CircBuf;
const CursorStyle = @import("../cursor.zig").Style;
const Screen = @import("../Screen.zig");
const ScreenSet = @import("../ScreenSet.zig");
const Terminal = @import("../Terminal.zig");
const Layout = @import("layout.zig").Layout;
const control = @import("control.zig");
const output = @import("output.zig");

const log = std.log.scoped(.terminal_tmux_viewer);

// TODO: A list of TODOs as I think about them.
// - We need to make startup more robust so session and block can happen
//   out of order.
// - We need to ignore `output` for panes that aren't yet initialized
//   (until capture-panes are complete).
// - We should note what the active window pane is on the tmux side;
//   we can use this at least for initial focus.

// NOTE: There is some fragility here that can possibly break if tmux
// changes their implementation. In particular, the order of notifications
// and assurances about what is sent when are based on reading the tmux
// source code as of Dec, 2025. These aren't documented as fixed.
//
... (2282 lines truncated)
</file>

<file path="src/terminal/ansi.zig">
const lib = @import("lib.zig");

/// C0 (7-bit) control characters from ANSI.
///
/// This is not complete, control characters are only added to this
/// as the terminal emulator handles them.
pub const C0 = enum(u7) {
    /// Null
    NUL = 0x00,
    /// Start of heading
    SOH = 0x01,
    /// Start of text
    STX = 0x02,
    /// Enquiry
    ENQ = 0x05,
    /// Bell
    BEL = 0x07,
    /// Backspace
    BS = 0x08,
    // Horizontal tab
    HT = 0x09,
    /// Line feed
    LF = 0x0A,
    /// Vertical Tab
    VT = 0x0B,
    /// Form feed
    FF = 0x0C,
    /// Carriage return
    CR = 0x0D,
    /// Shift out
... (80 lines truncated)
</file>

<file path="src/terminal/apc.zig">
const std = @import("std");
const build_options = @import("terminal_options");
const Allocator = std.mem.Allocator;

pub const glyph = @import("apc/glyph.zig");
const kitty_gfx = @import("kitty/graphics.zig");

const log = std.log.scoped(.terminal_apc);

/// APC command handler. This should be hooked into a terminal.Stream handler.
/// The start/feed/end functions are meant to be called from the terminal.Stream
/// apcStart, apcPut, and apcEnd functions, respectively.
pub const Handler = struct {
    state: State = .inactive,

    /// Maximum content bytes retained for unsupported APC identifiers. Zero
    /// drops and ignores unknown APC values.
    unknown_max_bytes: usize = 0,

    /// Maximum bytes each APC protocol can buffer. This is to prevent
    /// malicious input from causing us to allocate too much memory.
    /// If you want to be lazy and set a single value for all protocols,
    /// use `.initFull`.
    max_bytes: std.EnumMap(Protocol, usize) = .initFullWith(.{
        .kitty = Protocol.defaultMaxBytes(.kitty),
        .glyph = Protocol.defaultMaxBytes(.glyph),
    }),

    /// Protocols recognized by this APC handler. When a protocol is absent,
    /// matching APC sequences are ignored and are not reported as unknown.
... (737 lines truncated)
</file>

<file path="src/terminal/bitmap_allocator.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const size = @import("size.zig");
const getOffset = size.getOffset;
const Offset = size.Offset;
const OffsetBuf = size.OffsetBuf;
const alignForward = std.mem.alignForward;

/// A relatively naive bitmap allocator that uses memory offsets against
/// a fixed backing buffer so that the backing buffer can be easily moved
/// without having to update pointers.
///
/// The chunk size determines the size of each chunk in bytes. This is the
/// minimum distributed unit of memory. For example, if you request a
/// 1-byte allocation, you'll use a chunk of chunk_size bytes. Likewise,
/// if your chunk size is 4, and you request a 5-byte allocation, you'll
/// use 2 chunks.
///
/// The allocator is susceptible to fragmentation. If you allocate and free
/// memory in a way that leaves small holes in the memory, you may not be
/// able to allocate large chunks of memory even if there is enough free
/// memory in aggregate. To avoid fragmentation, use a chunk size that is
/// large enough to cover most of your allocations.
///
// Notes for contributors: this is highly contributor friendly part of
// the code. If you can improve this, add tests, show benchmarks, then
// please do so!
pub fn BitmapAllocator(comptime chunk_size: comptime_int) type {
    return struct {
... (1192 lines truncated)
</file>

<file path="src/terminal/build_options.zig">
const std = @import("std");

/// Options set by Zig build.zig and exposed via `terminal_options`.
pub const Options = struct {
    pub const Artifact = enum {
        /// Ghostty application
        ghostty,

        /// libghostty-vt, Zig module
        lib,
    };

    /// The target artifact to build. This will gate some functionality.
    artifact: Artifact,

    /// Whether Oniguruma regex support is available. If this isn't
    /// available, some features will be disabled. This may be outdated,
    /// but the specific disabled features are:
    ///
    /// - Kitty graphics protocol
    /// - Tmux control mode
    ///
    oniguruma: bool,

    /// Whether to build SIMD-accelerated code paths. This pulls in more
    /// build-time dependencies and adds libc as a runtime dependency,
    /// but results in significant performance improvements.
    simd: bool,

    /// True if we should enable the "slow" runtime safety checks. These
... (304 lines truncated)
</file>

<file path="src/terminal/charsets.zig">
const std = @import("std");
const build_options = @import("terminal_options");
const assert = @import("../quirks.zig").inlineAssert;
const LibEnum = @import("../lib/enum.zig").Enum;

/// The available charset slots for a terminal.
pub const Slots = LibEnum(
    if (build_options.c_abi) .c else .zig,
    &.{ "G0", "G1", "G2", "G3" },
);

/// The name of the active slots.
pub const ActiveSlot = LibEnum(
    if (build_options.c_abi) .c else .zig,
    &.{ "GL", "GR" },
);

/// The list of supported character sets and their associated tables.
pub const Charset = LibEnum(
    if (build_options.c_abi) .c else .zig,
    &.{ "utf8", "ascii", "british", "dec_special" },
);

/// The table for the given charset. This returns a pointer to a
/// slice that is guaranteed to be 255 chars that can be used to map
/// ASCII to the given charset.
pub inline fn table(set: Charset) []const u16 {
    return switch (set) {
        .british => &british,
        .dec_special => &dec_special,
... (86 lines truncated)
</file>

<file path="src/terminal/clipboard.zig">
const std = @import("std");

/// The clipboard destination for a write.
pub const Location = enum(c_int) {
    standard = 0,
    selection = 1,
    primary = 2,
    _,
};

/// MIME types that name plain text across the platforms terminals run
/// on. We accept the union everywhere since serving text under any of these
/// names is harmless.
pub fn isTextMime(mime: []const u8) bool {
    const names: []const []const u8 = &.{
        "text/plain",
        "text/plain;charset=utf-8",
        "UTF8_STRING",
        "TEXT",
        "STRING",
    };
    for (names) |n| if (std.mem.eql(u8, mime, n)) return true;
    return false;
}

/// A single representation of clipboard data.
///
/// The MIME type and data are borrowed and only valid for the duration of a
/// clipboard write callback. Data is binary-safe.
pub const Content = struct {
... (227 lines truncated)
</file>

<file path="src/terminal/color.zig">
const colorpkg = @This();

const std = @import("std");
const lib = @import("lib.zig");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const assert = @import("../quirks.zig").inlineAssert;
const fraction = @import("fraction.zig");
const x11_color = @import("x11_color.zig");

/// The default palette.
pub const default: Palette = default: {
    var result: Palette = undefined;

    // Named values
    var i: u8 = 0;
    while (i < 16) : (i += 1) {
        result[i] = Name.default(@enumFromInt(i)) catch unreachable;
    }

    // Cube
    assert(i == 16);
    var r: u8 = 0;
    while (r < 6) : (r += 1) {
        var g: u8 = 0;
        while (g < 6) : (g += 1) {
            var b: u8 = 0;
            while (b < 6) : (b += 1) {
                result[i] = .{
                    .r = if (r == 0) 0 else (r * 40 + 55),
... (1446 lines truncated)
</file>

<file path="src/terminal/compress.zig">
//! Compression primitives used by the terminal.
//!
//! This namespace contains only the representation and codecs. Policy about
//! which pages to compress, when to decommit their resident memory, and when
//! to restore them belongs to `PageList`.

/// The raw LZ4 block codec used for terminal page memory.
pub const lz4 = @import("compress/lz4.zig");

/// A compressed terminal page which retains its original virtual mapping.
pub const Page = @import("compress/Page.zig");

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/terminal/csi.zig">
const lib = @import("lib.zig");

/// Modes for the ED CSI command.
pub const EraseDisplay = enum(u8) {
    below = 0,
    above = 1,
    complete = 2,
    scrollback = 3,

    /// This is an extension added by Kitty to move the viewport into the
    /// scrollback and then erase the display.
    scroll_complete = 22,
};

/// Modes for the EL CSI command.
pub const EraseLine = enum(u8) {
    right = 0,
    left = 1,
    complete = 2,
    right_unless_pending_wrap = 4,

    // Non-exhaustive so that @intToEnum never fails since the inputs are
    // user-generated.
    _,
};

/// Modes for the TBC (tab clear) command.
pub const TabClear = enum(u8) {
    current = 0,
    all = 3,
... (26 lines truncated)
</file>

<file path="src/terminal/cursor.zig">
const lib = @import("../lib/main.zig");

/// The visual style of the cursor. Whether or not it blinks
/// is determined by mode 12 (modes.zig). This mode is synchronized
/// with CSI q, the same as xterm.
///
/// Bar, block, and underline correspond to DECSCUSR 5/6, 1/2, and 3/4.
/// Hollow block is Ghostty-specific and is reported as DECSCUSR 1 or 2.
pub const Style = lib.Enum(.zig, &.{
    // DECSCUSR 5, 6
    "bar",

    // DECSCUSR 1, 2
    "block",

    // DECSCUSR 3, 4
    "underline",

    // The cursor styles below aren't known by DESCUSR and are custom
    // implemented in Ghostty. They are reported as some standard style
    // if requested, though.
    // Hollow block cursor. This is a block cursor with the center empty.
    // Reported as DECSCUSR 1 or 2 (block).
    "block_hollow",
});
</file>

<file path="src/terminal/dcs.zig">
const std = @import("std");
const build_options = @import("terminal_options");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const terminal = @import("main.zig");
const DCS = terminal.DCS;

const log = std.log.scoped(.terminal_dcs);

/// DCS command handler. This should be hooked into a terminal.Stream handler.
/// The hook/put/unhook functions are meant to be called from the
/// terminal.stream dcsHook, dcsPut, and dcsUnhook functions, respectively.
pub const Handler = struct {
    state: State = .{ .inactive = {} },

    /// Maximum bytes any DCS command can take. This is to prevent
    /// malicious input from causing us to allocate too much memory.
    /// This is arbitrarily set to 1MB today, increase if needed.
    max_bytes: usize = 1024 * 1024,

    pub fn deinit(self: *Handler) void {
        self.discard();
    }

    pub fn hook(self: *Handler, alloc: Allocator, dcs: DCS) ?Command {
        assert(self.state == .inactive);

        // Initialize our state to ignore in case of error
        self.state = .ignore;

... (542 lines truncated)
</file>

<file path="src/terminal/device_attributes.zig">
const std = @import("std");
const testing = std.testing;
const lib = @import("lib.zig");

/// The device attribute request type (CSI c).
pub const Req = lib.Enum(lib.target, &.{
    "primary", // Blank
    "secondary", // >
    "tertiary", // =
});

/// Response data for all device attribute queries.
pub const Attributes = struct {
    /// Reply to CSI c (DA1).
    primary: Primary = .{},

    /// Reply to CSI > c (DA2).
    secondary: Secondary = .{},

    /// Reply to CSI = c (DA3).
    tertiary: Tertiary = .{},

    /// Encode the response for the given request type into the writer.
    pub fn encode(
        self: Attributes,
        req: Req,
        writer: *std.Io.Writer,
    ) std.Io.Writer.Error!void {
        switch (req) {
            .primary => try self.primary.encode(writer),
... (198 lines truncated)
</file>

<file path="src/terminal/device_status.zig">
const std = @import("std");
const lib = @import("lib.zig");

/// The color scheme reported in response to a CSI ? 996 n query.
pub const ColorScheme = lib.Enum(lib.target, &.{
    "light",
    "dark",
});

/// The visibility state reported in response to a CSI ? 998 n query or when
/// DEC mode 2033 is enabled.
pub const Visibility = lib.Enum(lib.target, &.{
    "potentially_visible",
    "not_visible",
});

/// Maximum number of bytes that `encodeColorSchemeReport` will write.
pub const max_color_scheme_report_encode_size = max: {
    var result: usize = 0;
    for (@typeInfo(ColorScheme).@"enum".fields) |field| {
        var discarding: std.Io.Writer.Discarding = .init(&.{});
        encodeColorSchemeReport(
            &discarding.writer,
            @enumFromInt(field.value),
        ) catch unreachable;
        result = @max(result, @as(usize, @intCast(discarding.count)));
    }

    break :max result;
};
... (115 lines truncated)
</file>

<file path="src/terminal/focus.zig">
const std = @import("std");
const lib = @import("lib.zig");

/// Maximum number of bytes that `encode` will write. Any users of this
/// should be resilient to this changing, so this is always a specific
/// value (e.g. we don't add unnecessary padding).
pub const max_encode_size = 3;

/// A focus event that can be reported to the application running in the
/// terminal when focus reporting mode (mode 1004) is enabled.
pub const Event = lib.Enum(lib.target, &.{
    "gained",
    "lost",
});

/// Encode a focus in/out report (CSI I / CSI O).
pub fn encode(
    writer: *std.Io.Writer,
    event: Event,
) std.Io.Writer.Error!void {
    try writer.writeAll(switch (event) {
        .gained => "\x1B[I",
        .lost => "\x1B[O",
    });
}

test "encode focus gained" {
    var buf: [max_encode_size]u8 = undefined;
    var writer: std.Io.Writer = .fixed(&buf);
    try encode(&writer, .gained);
... (10 lines truncated)
</file>

<file path="src/terminal/formatter.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const fastprint = @import("../fastprint.zig");
const lib = @import("lib.zig");
const Allocator = std.mem.Allocator;
const color = @import("color.zig");
const size = @import("size.zig");
const charsets = @import("charsets.zig");
const hyperlink = @import("hyperlink.zig");
const kitty = @import("kitty.zig");
const modespkg = @import("modes.zig");
const Screen = @import("Screen.zig");
const Terminal = @import("Terminal.zig");
const Cell = @import("page.zig").Cell;
const Coordinate = @import("point.zig").Coordinate;
const Page = @import("page.zig").Page;
const PageList = @import("PageList.zig");
const Pin = PageList.Pin;
const Row = @import("page.zig").Row;
const Selection = @import("Selection.zig");
const Style = @import("style.zig").Style;

/// Formats available.
pub const Format = lib.Enum(lib.target, &.{
    // Plain text.
    "plain",

    // Include VT sequences to preserve colors, styles, URLs, etc.
    // This is predominantly SGR sequences but may contain others as needed.
    //
... (7001 lines truncated)
</file>

<file path="src/terminal/fraction.zig">
//! Parsing of decimal fractions in the unit interval [0, 1].
//!
//! Escape sequences that carry fractional parameters (XTerm `rgbi:`
//! color specifications, glyph protocol padding) only ever need plain
//! decimal values such as "0.5". Using `std.fmt.parseFloat` for these
//! pulls the full correctly-rounded float parser and its lookup tables
//! into the binary (~26KB). This implements only the restricted subset
//! we need.
const std = @import("std");
const assert = std.debug.assert;

/// Parse a decimal fraction in the range [0, 1] inclusive.
///
/// Accepts an optional leading `+` or `-` sign followed by decimal
/// digits with an optional decimal point ("0.5", ".5", "1.", "1"); at
/// least one digit is required. Exponent and hexadecimal float syntax
/// are not supported. Returns null for invalid syntax and for any value
/// outside [0, 1] (so negative values other than -0 are rejected).
///
/// Results are correctly rounded for inputs of up to 15 fractional
/// digits; further digits are validated but ignored, which can move the
/// result by less than 1e-15.
pub fn parse(value: []const u8) ?f64 {
    var v = value;
    var negative = false;
    if (v.len > 0) switch (v[0]) {
        '+' => v = v[1..],
        '-' => {
            negative = true;
            v = v[1..];
... (113 lines truncated)
</file>

<file path="src/terminal/hash_map.zig">
//! This file contains a fork of the Zig stdlib HashMap implementation tuned
//! for use with our terminal page representation.
//!
//! The main goal we need to achieve that wasn't possible with the stdlib
//! HashMap is to utilize offsets rather than full pointers so that we can
//! copy around the entire backing memory and keep the hash map working.
//!
//! Additionally, for serialization/deserialization purposes, we need to be
//! able to create a HashMap instance and manually set the offsets up. The
//! stdlib HashMap does not export Metadata so this isn't possible.
//!
//! Also, I want to be able to understand possible capacity for a given K,V
//! type and fixed memory amount. The stdlib HashMap doesn't publish its
//! internal allocation size calculation.
//!
//! Finally, I removed many of the APIs that we'll never require for our
//! usage just so that this file is smaller, easier to understand, and has
//! less opportunity for bugs.
//!
//! Besides these shortcomings, the stdlib HashMap has some great qualities
//! that we want to keep, namely the fact that it is backed by a single large
//! allocation rather than pointers to separate allocations. This is important
//! because our terminal page representation is backed by a single large
//! allocation so we can give the HashMap a slice of memory to operate in.
//!
//! This fork diverges from the stdlib in one significant way: removal uses
//! backward-shift deletion (Knuth vol. 3, section 6.4, algorithm R) rather
//! than tombstones. A fixed-capacity map cannot outgrow tombstone buildup
//! the way an allocating map does, so tombstones require either unbounded
//! probe lengths or periodic in-place rebuilds with subtle bookkeeping.
... (1889 lines truncated)
</file>

<file path="src/terminal/highlight.zig">
//! Highlights are any contiguous sequences of cells that should
//! be called out in some way, most commonly for text selection but
//! also search results or any other purpose.
//!
//! Within the terminal package, a highlight is a generic concept
//! that represents a range of cells.

// NOTE: The plan is for highlights to ultimately replace Selection
// completely. Selection is deeply tied to various parts of the Ghostty
// internals so this may take some time.

const std = @import("std");
const Allocator = std.mem.Allocator;
const size = @import("size.zig");
const PageList = @import("PageList.zig");
const PageChunk = PageList.PageIterator.Chunk;
const Pin = PageList.Pin;
const Screen = @import("Screen.zig");

/// An untracked highlight is a highlight that stores its highlighted
/// area as a top-left and bottom-right screen pin. Since it is untracked,
/// the pins are only valid for the current terminal state and may not
/// be safe to use after any terminal modifications.
///
/// For rectangle highlights/selections, the downstream consumer of this
/// code is expected to interpret the pins in whatever shape they want.
/// For example, a rectangular selection would interpret the pins as
/// setting the x bounds for each row between start.y and end.y.
///
/// To simplify all operations, start MUST be before or equal to end.
... (184 lines truncated)
</file>

<file path="src/terminal/hyperlink.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const hash_map = @import("hash_map.zig");
const AutoOffsetHashMap = hash_map.AutoOffsetHashMap;
const pagepkg = @import("page.zig");
const size = @import("size.zig");
const Offset = size.Offset;
const Cell = pagepkg.Cell;
const Page = pagepkg.Page;
const RefCountedSet = @import("ref_counted_set.zig").RefCountedSet;
const Wyhash = std.hash.Wyhash;
const autoHash = std.hash.autoHash;
const autoHashStrat = std.hash.autoHashStrat;

/// The unique identifier for a hyperlink. This is at most the number of cells
/// that can fit in a single terminal page, since each cell can only contain
/// at most one hyperlink.
pub const Id = size.HyperlinkCountInt;

// The mapping of cell to hyperlink. We use an offset hash map to save space
// since its very unlikely a cell is a hyperlink, so its a waste to store
// the hyperlink ID in the cell itself.
pub const Map = AutoOffsetHashMap(Offset(Cell), Id, 80);

/// A fully decoded hyperlink that may or may not have its
/// memory within a page. The memory location of this is dependent
/// on the context so users should check with the source of the
/// hyperlink.
pub const Hyperlink = struct {
    id: Hyperlink.Id,
... (211 lines truncated)
</file>

<file path="src/terminal/kitty.zig">
//! Types and functions related to Kitty protocols.

const build_options = @import("terminal_options");

const key = @import("kitty/key.zig");
pub const clipboard = @import("kitty/clipboard.zig");
pub const color = @import("kitty/color.zig");
pub const dnd = @import("kitty/dnd.zig");
pub const graphics = if (build_options.kitty_graphics) @import("kitty/graphics.zig") else struct {};

pub const KeyFlags = key.Flags;
pub const KeyFlagStack = key.FlagStack;
pub const KeySetMode = key.SetMode;

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/terminal/lib.zig">
const std = @import("std");
const build_options = @import("terminal_options");
const lib = @import("../lib/main.zig");

/// The target for the terminal lib in particular.
pub const target: lib.Target = if (build_options.c_abi) .c else .zig;

/// The calling convention to use for C APIs.
///
/// This is always .c for now. I want to make this "Zig" when we're not
/// building the C ABI but there are bigger issues we need to resolve to
/// make that possible (change it and see for yourself).
pub const calling_conv: std.builtin.CallingConvention = .c;

/// Forwarded decls from lib that are used.
pub const alloc = lib.allocator;
pub const TinyIo = lib.TinyIo;
pub const Buffer = lib.Buffer;
pub const Enum = lib.Enum;
pub const parseInt = lib.parseInt;
pub const TaggedUnion = lib.TaggedUnion;
pub const Struct = lib.Struct;
pub const String = lib.String;
pub const checkGhosttyHEnum = lib.checkGhosttyHEnum;
pub const structSizedFieldFits = lib.structSizedFieldFits;
</file>

<file path="src/terminal/main.zig">
const charsets = @import("charsets.zig");
const stream = @import("stream.zig");
const ansi = @import("ansi.zig");
const csi = @import("csi.zig");
const render = @import("render.zig");
const stream_terminal = @import("stream_terminal.zig");
const style = @import("style.zig");
pub const apc = @import("apc.zig");
pub const dcs = @import("dcs.zig");
pub const osc = @import("osc.zig");
pub const point = @import("point.zig");
pub const color = @import("color.zig");
pub const xt_checksum = @import("xt_checksum.zig");
pub const clipboard = @import("clipboard.zig");
pub const device_attributes = @import("device_attributes.zig");
pub const device_status = @import("device_status.zig");
pub const focus = @import("focus.zig");
pub const formatter = @import("formatter.zig");
pub const highlight = @import("highlight.zig");
pub const kitty = @import("kitty.zig");
pub const modes = @import("modes.zig");
pub const page = @import("page.zig");
pub const parse_table = @import("parse_table.zig");
pub const paste = @import("paste.zig");
pub const search = @import("search.zig");
pub const snapshot = @import("snapshot/main.zig");
pub const sgr = @import("sgr.zig");
pub const size = @import("size.zig");
pub const size_report = @import("size_report.zig");
pub const sys = @import("sys.zig");
... (77 lines truncated)
</file>

<file path="src/terminal/mem.zig">
//! Virtual-memory operations shared by terminal page owners.
//!
//! Terminal pages use page-aligned, page-multiple mappings. This module can
//! discard the physical pages behind one of those mappings without releasing
//! its virtual address range, then prepare the same range for reuse. It does
//! not allocate memory or decide which terminal pages should be discarded.
//!
//! Decommit releases physical pages only. The address range and its memory
//! accounting (the Linux VMA, the Windows commit charge) stay with the
//! process, so a read after decommit returns zeros or the old contents rather
//! than faulting, and recommit has nothing to acquire that could fail.
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const windows = @import("../os/windows.zig");

const log = std.log.scoped(.terminal_mem);

/// What guarantee decommit must provide when the OS cannot discard a mapping.
pub const DecommitMode = enum {
    /// The dirty prefix must read as zero after this call, even when physical
    /// reclamation is unavailable. Bytes after the prefix must already be zero.
    zero,

    /// Physical-memory reclamation is required. Do not touch the mapping when
    /// reclamation is unsupported or fails; report the failure to the caller.
    strict,
};

/// Return whether this target can reclaim physical memory for `mode` while
... (231 lines truncated)
</file>

<file path="src/terminal/modes.zig">
//! This file contains all the terminal modes that we support
//! and various support types for them: an enum of supported modes,
//! a packed struct to store mode values, a more generalized state
//! struct to store values plus handle save/restore, and much more.
//!
//! There is pretty heavy comptime usage and type generation here.
//! I don't love to have this sort of complexity but its a good way
//! to ensure all our various types and logic remain in sync.

const std = @import("std");
const builtin = @import("builtin");
const build_options = @import("terminal_options");
const testing = std.testing;
const ComptimeIntSet = @import("../datastruct/main.zig").ComptimeIntSet;

/// A struct that maintains the state of all the settable modes.
pub const ModeState = struct {
    /// The values of the current modes.
    values: ModePacked = .{},

    /// The saved values. We only allow saving each mode once.
    /// This is in line with other terminals that implement XTSAVE
    /// and XTRESTORE. We can improve this in the future if it becomes
    /// a real-world issue but we need to be aware of a DoS vector.
    saved: ModePacked = .{},

    /// The default values for the modes. This is used to reset
    /// the modes to their default values during reset.
    default: ModePacked = .{},

... (528 lines truncated)
</file>

<file path="src/terminal/mouse.zig">
const std = @import("std");
const build_options = @import("terminal_options");
const lib = @import("lib.zig");
const compat_testing = @import("../lib/compat/testing.zig");

/// The event types that can be reported for mouse-related activities.
/// These are all mutually exclusive (hence in a single enum).
pub const Event = lib.Enum(lib.target, &.{
    "none",
    "x10", // 9
    "normal", // 1000
    "button", // 1002
    "any", // 1003
});

/// Returns true if this event sends motion events.
pub fn eventSendsMotion(event: Event) bool {
    return event == .button or event == .any;
}

/// The format of mouse events when enabled.
/// These are all mutually exclusive (hence in a single enum).
pub const Format = lib.Enum(lib.target, &.{
    "x10",
    "utf8", // 1005
    "sgr", // 1006
    "urxvt", // 1015
    "sgr_pixels", // 1016
});

... (140 lines truncated)
</file>

<file path="src/terminal/osc.zig">
//! OSC (Operating System Command) related functions and types.
//!
//! OSC is another set of control sequences for terminal programs that start with
//! "ESC ]". Unlike CSI or standard ESC sequences, they may contain strings
//! and other irregular formatting so a dedicated parser is created to handle it.
const osc = @This();

const std = @import("std");
const builtin = @import("builtin");
const build_options = @import("terminal_options");
const mem = std.mem;
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = mem.Allocator;
const lib = @import("lib.zig");
const LibEnum = lib.Enum;
const kitty_color = @import("kitty/color.zig");
const parsers = @import("osc/parsers.zig");
const encoding = @import("osc/encoding.zig");

pub const color = parsers.color;
pub const semantic_prompt = parsers.semantic_prompt;

const log = std.log.scoped(.osc);

pub const Command = union(Key) {
    /// This generally shouldn't ever be set except as an initial zero value.
    /// Ignore it.
    invalid,

    /// Set the window title of the terminal
... (1256 lines truncated)
</file>

<file path="src/terminal/page.zig">
const std = @import("std");
const builtin = @import("builtin");
const build_options = @import("terminal_options");
const lib = @import("../lib/main.zig");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const assert = @import("../quirks.zig").inlineAssert;
const testing = std.testing;
const posix = std.posix;
const windows = @import("../os/windows.zig");
const fastmem = @import("../fastmem.zig");
const color = @import("color.zig");
const hyperlink = @import("hyperlink.zig");
const kitty = @import("kitty.zig");
const stylepkg = @import("style.zig");
const Style = stylepkg.Style;
const StyleId = stylepkg.Id;
const StyleSet = stylepkg.Set;
const size = @import("size.zig");
const getOffset = size.getOffset;
const Offset = size.Offset;
const OffsetBuf = size.OffsetBuf;
const BitmapAllocator = @import("bitmap_allocator.zig").BitmapAllocator;
const hash_map = @import("hash_map.zig");
const AutoOffsetHashMap = hash_map.AutoOffsetHashMap;
const alignForward = std.mem.alignForward;

const log = std.log.scoped(.page);

/// Page-aligned allocator used for terminal page backing memory. Pages
... (4506 lines truncated)
</file>

<file path="src/terminal/PageList.zig">
//! Maintains a linked list of pages to make up a terminal screen
//! and provides higher level operations on top of those pages to
//! make it slightly easier to work with.
const PageList = @This();

const std = @import("std");
const builtin = @import("builtin");
const build_options = @import("terminal_options");
const Allocator = std.mem.Allocator;
const assert = @import("../quirks.zig").inlineAssert;
const fastmem = @import("../fastmem.zig");
const simd = @import("../simd/main.zig");
const tripwire = @import("../tripwire.zig");
const DoublyLinkedList = @import("../datastruct/main.zig").IntrusiveDoublyLinkedList;
const datastruct = @import("../datastruct/main.zig");
const color = @import("color.zig");
const compression = @import("compress.zig");
const highlight = @import("highlight.zig");
const hyperlink = @import("hyperlink.zig");
const kitty = @import("kitty.zig");
const terminal_mem = @import("mem.zig");
const point = @import("point.zig");
const pagepkg = @import("page.zig");
const stylepkg = @import("style.zig");
const size = @import("size.zig");
const OffsetBuf = size.OffsetBuf;
const Capacity = pagepkg.Capacity;
const Page = pagepkg.Page;
const Row = pagepkg.Row;

... (20776 lines truncated)
</file>

<file path="src/terminal/parse_table.zig">
//! The primary export of this file is "table", which contains a
//! comptime-generated state transition table for VT emulation.
//!
//! This is based on the vt100.net state machine:
//! https://vt100.net/emu/dec_ansi_parser
//! But has some modifications:
//!
//!   * csi_param accepts the colon character (':') since the SGR command
//!     accepts colon as a valid parameter value.
//!

const std = @import("std");
const parser = @import("Parser.zig");
const State = parser.State;
const Action = parser.TransitionAction;

/// The state transition table. The type is [u8][State]Transition but
/// comptime-generated to be exactly-sized.
pub const table = genTable();

/// Table is the type of the state table. This is dynamically (comptime)
/// generated to be exactly sized.
pub const Table = genTableType(false);

/// OptionalTable is private to this file. We use this to accumulate and
/// detect invalid transitions created.
const OptionalTable = genTableType(true);

// Transition is the transition to take within the table
pub const Transition = struct {
... (419 lines truncated)
</file>

<file path="src/terminal/Parser.zig">
//! VT-series parser for escape and control sequences.
//!
//! This is implemented directly as the state machine described on
//! vt100.net: https://vt100.net/emu/dec_ansi_parser
const Parser = @This();

const std = @import("std");
const testing = std.testing;
const table = @import("parse_table.zig").table;
const osc = @import("osc.zig");

const log = std.log.scoped(.parser);

/// States for the state machine
pub const State = enum {
    ground,
    escape,
    escape_intermediate,
    csi_entry,
    csi_intermediate,
    csi_param,
    csi_ignore,
    dcs_entry,
    dcs_param,
    dcs_intermediate,
    dcs_passthrough,
    dcs_ignore,
    osc_string,
    sos_pm_apc_string,
};
... (1099 lines truncated)
</file>

<file path="src/terminal/paste.zig">
//! Pasting into a terminal.
//!
//! This is the single place that turns "the user pasted" into bytes for
//! the pty, applying the terminal's current state:
//!
//!   * Mode 5522 (Kitty clipboard protocol paste events) set, a
//!     user-initiated clipboard paste, and the embedder able to serve
//!     the program's follow-up clipboard read: send a paste event
//!     listing the clipboard's MIME types with a fresh one-time password
//!     and record a one-time read grant for it. No data is read.
//!   * Otherwise: write the first text representation, with unsafe bytes
//!     replaced (xterm behavior), framed per mode 2004 (bracketed paste)
//!     or with newlines converted to carriage returns if not.
//!
//! The precedence (5522 event, else 2004 framing, else plain) and the
//! safety rule live only here so every embedder of the terminal shares
//! one implementation.

const std = @import("std");
const Allocator = std.mem.Allocator;

const clipboard = @import("clipboard.zig");
const kitty_clipboard = @import("kitty/clipboard.zig");
const input_paste = @import("../input/paste.zig");
const Terminal = @import("Terminal.zig");

/// Why a paste happened. Only clipboard pastes may become paste
/// events, which is why only they carry a location: it's meaningless
/// for text insertion.
///
... (218 lines truncated)
</file>

<file path="src/terminal/point.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const lib = @import("lib.zig");
const size = @import("size.zig");

/// The possible reference locations for a point. When someone says "(42, 80)"
/// in the context of a terminal, that could mean multiple things: it is in the
/// current visible viewport? the current active area of the screen where the
/// cursor is? the entire scrollback history? etc.
///
/// This tag is used to differentiate those cases.
pub const Tag = lib.Enum(lib.target, &.{
    // Top-left is part of the active area where a running program can
    // jump the cursor and make changes. The active area is the "editable"
    // part of the screen.
    //
    // The bottom-right of the active tag differs from all other tags
    // because it includes the full height (rows) of the screen, including
    // rows that may not be written yet. This is required because the active
    // area is fully "addressable" by the running program (see below) whereas
    // the other tags are used primarily for reading/modifying past-written
    // data so they can't address unwritten rows.
    //
    // Note for those less familiar with terminal functionality: there
    // are escape sequences to move the cursor to any position on
    // the screen, but it is limited to the size of the viewport and
    // the bottommost part of the screen. Terminal programs can't --
    // with sequences at the time of writing this comment -- modify
    // anything in the scrollback, visible viewport (if it differs
    // from the active area), etc.
... (83 lines truncated)
</file>

<file path="src/terminal/ref_counted_set.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const testing = std.testing;

const size = @import("size.zig");
const Offset = size.Offset;
const OffsetBuf = size.OffsetBuf;

/// A reference counted set.
///
/// This set is created with some capacity in mind. You can determine
/// the exact memory requirement of a given capacity by calling `layout`
/// and checking the total size.
///
/// When the set exceeds capacity, an `OutOfMemory` or `NeedsRehash` error
/// is returned from any memory-using methods. The caller is responsible
/// for determining a path forward.
///
/// This set is reference counted. Each item in the set has an associated
/// reference count. The caller is responsible for calling release for an
/// item when it is no longer being used. Items with 0 references will be
/// kept until another item is written to their bucket. This allows items
/// to be resurrected if they are re-added before they get overwritten.
///
/// The backing data structure of this set is an open addressed hash table
/// with linear probing and Robin Hood hashing, and a flat array of items.
///
/// The table maps values to item IDs, which are indices in the item array
/// which contain the item's value and its reference count. Item IDs can be
/// used to efficiently access an item and update its reference count after
... (861 lines truncated)
</file>

<file path="src/terminal/render.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const fastmem = @import("../fastmem.zig");
const lib = @import("lib.zig");
const color = @import("color.zig");
const cursor = @import("cursor.zig");
const highlight = @import("highlight.zig");
const point = @import("point.zig");
const size = @import("size.zig");
const page = @import("page.zig");
const PageList = @import("PageList.zig");
const Selection = @import("Selection.zig");
const Screen = @import("Screen.zig");
const ScreenSet = @import("ScreenSet.zig");
const Style = @import("style.zig").Style;
const Terminal = @import("Terminal.zig");

// Developer note: this is in src/terminal and not src/renderer because
// the goal is that this remains generic to multiple renderers. This can
// aid specifically with libghostty-vt with converting terminal state to
// a renderable form.

/// Contains the state required to render the screen, including optimizing
/// for repeated render calls and only rendering dirty regions.
///
/// Previously, our renderer would use `clone` to clone the screen within
/// the viewport to perform rendering. This worked well enough that we kept
/// it all the way up through the Ghostty 1.2.x series, but the clone time
... (3004 lines truncated)
</file>

<file path="src/terminal/Screen.zig">
const Screen = @This();

const std = @import("std");
const build_options = @import("terminal_options");
const Allocator = std.mem.Allocator;
const assert = @import("../quirks.zig").inlineAssert;
const ansi = @import("ansi.zig");
const charsets = @import("charsets.zig");
const fastmem = @import("../fastmem.zig");
const kitty = @import("kitty.zig");
const lib = @import("lib.zig");
const sgr = @import("sgr.zig");
const tripwire = @import("../tripwire.zig");
const unicode = @import("../unicode/main.zig");
const Selection = @import("Selection.zig");
const PageList = @import("PageList.zig");
const selection_codepoints = @import("selection_codepoints.zig");
const StringMap = @import("StringMap.zig");
const ScreenFormatter = @import("formatter.zig").ScreenFormatter;
const PinMap = @import("formatter.zig").PinMap;
const osc = @import("osc.zig");
const pagepkg = @import("page.zig");
const point = @import("point.zig");
const size = @import("size.zig");
const style = @import("style.zig");
const hyperlink = @import("hyperlink.zig");
const Offset = size.Offset;
const Page = pagepkg.Page;
const Row = pagepkg.Row;
const Cell = pagepkg.Cell;
... (12639 lines truncated)
</file>

<file path="src/terminal/ScreenSet.zig">
/// A ScreenSet holds multiple terminal screens. This is initially created
/// to handle simple primary vs alternate screens, but could be extended
/// in the future to handle N screens.
///
/// One of the goals of this is to allow lazy initialization of screens
/// as needed. The primary screen is always initialized, but the alternate
/// screen may not be until first used.
const ScreenSet = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const lib = @import("lib.zig");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const Screen = @import("Screen.zig");

/// The possible keys for screens in the screen set.
pub const Key = lib.Enum(lib.target, &.{
    "primary",
    "alternate",
});

/// The key value of the currently active screen. Useful for simple
/// comparisons, e.g. "is this screen the primary screen".
active_key: Key,

/// The active screen pointer.
active: *Screen,

/// All screens that are initialized.
... (125 lines truncated)
</file>

<file path="src/terminal/search.zig">
//! Search functionality for the terminal.

pub const options = @import("terminal_options");

pub const Active = @import("search/active.zig").ActiveSearch;
pub const PageList = @import("search/pagelist.zig").PageListSearch;
pub const Screen = @import("search/screen.zig").ScreenSearch;
pub const Terminal = @import("search/terminal.zig").TerminalSearch;
pub const Viewport = @import("search/viewport.zig").ViewportSearch;

// The search thread is not available in libghostty due to the xev dep
// for now.
pub const Thread = switch (options.artifact) {
    .ghostty => @import("search/Thread.zig"),
    .lib => void,
};

test {
    @import("std").testing.refAllDecls(@This());

    // Non-public APIs
    _ = @import("search/sliding_window.zig");
}
</file>

<file path="src/terminal/selection_codepoints.zig">
// This file contains various default word boundaries used for
// selection logic. We put it in a separate file so that different
// subsystems can import it without introducing a number of
// dependencies.

/// Default boundary characters for word selection: ` \t'"│`|:;,()[]{}<>$`
pub const default_word_boundaries = [_]u21{
    0, // null
    ' ', // space
    '\t', // tab
    '\'', // single quote
    '"', // double quote
    '│', // U+2502 box drawing
    '`', // backtick
    '|', // pipe
    ':', // colon
    ';', // semicolon
    ',', // comma
    '(', // left paren
    ')', // right paren
    '[', // left bracket
    ']', // right bracket
    '{', // left brace
    '}', // right brace
    '<', // less than
    '>', // greater than
    '$', // dollar
};

/// Default whitespace characters trimmed from line selections.
... (2 lines truncated)
</file>

<file path="src/terminal/Selection.zig">
//! Represents a single selection within the terminal (i.e. a highlight region).
const Selection = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const lib = @import("lib.zig");
const page = @import("page.zig");
const point = @import("point.zig");
const PageList = @import("PageList.zig");
const Screen = @import("Screen.zig");
const Pin = PageList.Pin;

// NOTE(mitchellh): I'm not very happy with how this is implemented, because
// the ordering operations which are used frequently require using
// pointFromPin which -- at the time of writing this -- is slow. The overall
// style of this struct is due to porting it from the previous implementation
// which had an efficient ordering operation.
//
// While reimplementing this, there were too many callers that already
// depended on this behavior so I kept it despite the inefficiency. In the
// future, we should take a look at this again!

/// The bounds of the selection.
bounds: Bounds,

/// Whether or not this selection refers to a rectangle, rather than whole
/// lines of a buffer. In this mode, start and end refer to the top left and
/// bottom right of the rectangle, or vice versa if the selection is backwards.
rectangle: bool = false,
... (1647 lines truncated)
</file>

<file path="src/terminal/SelectionGesture.zig">
/// SelectionGesture manages gesture-based terminal text selection for one
/// pointer stream: press, drag, release, autoscroll, and pressure/deep-press
/// selection.
///
/// This type owns only the state required to interpret a gesture. It does not
/// modify the terminal selection directly, except for scrolling the viewport
/// during `autoscrollTick`. The caller feeds platform events into this type and
/// applies the returned `Selection` to the active screen when appropriate.
///
/// A typical single-click drag flow looks like this:
///
/// ```zig
/// const selection = try gesture.press(terminal, .{ ... });
/// try terminal.screens.active.select(selection);
/// if (gesture.drag(terminal, .{ ... })) |selection| {
///     try terminal.screens.active.select(selection);
/// }
/// gesture.release(terminal, .{ ... });
/// ```
///
/// Double- and triple-click gestures use the same event flow. Repeated presses
/// inside `Press.repeat_interval` and within `Press.max_distance` increment the
/// internal click count up to three. `Press.behaviors` maps single-, double-,
/// and triple-clicks to behavior. By default, a single press returns null to
/// clear any existing selection, a double-click returns a word selection, and a
/// triple-click returns a line selection. Drags use the behavior selected by the
/// corresponding press. A new press that is too late, too far away, or on
/// another active screen starts a new single-click gesture.
///
/// # Resetting and lifetime
... (2081 lines truncated)
</file>

<file path="src/terminal/sgr.zig">
//! SGR (Select Graphic Rendition) attrinvbute parsing and types.

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const testing = std.testing;
const lib = @import("lib.zig");
const color = @import("color.zig");
const SepList = @import("Parser.zig").Action.CSI.SepList;

/// Attribute type for SGR
pub const Attribute = union(Tag) {
    /// Unset all attributes
    unset,

    /// Unknown attribute, the raw CSI command parameters are here.
    unknown: Unknown,

    /// Bold the text.
    bold,
    reset_bold,

    /// Italic text.
    italic,
    reset_italic,

    /// Faint/dim text.
    /// Note: reset faint is the same SGR code as reset bold
    faint,

    /// Underline the text
... (1085 lines truncated)
</file>

<file path="src/terminal/size_report.zig">
const std = @import("std");
const lib = @import("lib.zig");
const CellCountInt = @import("size.zig").CellCountInt;

/// Output formats for terminal size reports written to the PTY.
pub const Style = lib.Enum(lib.target, &.{
    // In-band size reports (mode 2048)
    "mode_2048",
    // XTWINOPS: report text area size in pixels
    "csi_14_t",
    // XTWINOPS: report cell size in pixels
    "csi_16_t",
    // XTWINOPS: report text area size in characters
    "csi_18_t",
});

/// Runtime size values used to encode terminal size reports.
pub const Size = lib.Struct(lib.target, struct {
    /// Terminal row count in cells.
    rows: CellCountInt,

    /// Terminal column count in cells.
    columns: CellCountInt,

    /// Width of a single terminal cell in pixels.
    cell_width: u32,

    /// Height of a single terminal cell in pixels.
    cell_height: u32,
});
... (131 lines truncated)
</file>

<file path="src/terminal/size.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;

/// The maximum size of a page in bytes. We use a u16 here because any
/// smaller bit size by Zig is upgraded anyways to a u16 on mainstream
/// CPU architectures, and because 65KB is a reasonable page size. To
/// support better configurability, we derive everything from this.
pub const max_page_size = std.math.maxInt(u32);

/// The int type that can contain the maximum memory offset in bytes,
/// derived from the maximum terminal page size.
pub const OffsetInt = std.math.IntFittingRange(0, max_page_size - 1);

/// Int types for maximum values of things. A lot of these sizes are
/// based on "X is enough for any reasonable use case" principles.
// The goal is that a user can have the maxInt amount of all of these
// present at one time and be able to address them in a single Page.zig.

// Total number of cells that are possible in each dimension (row/col).
// Based on 2^16 being enough for any reasonable terminal size and allowing
// IDs to remain 16-bit.
pub const CellCountInt = u16;

// Total number of styles and hyperlinks that are possible in a page.
// We match CellCountInt here because each cell in a single row can have at
// most one style, making it simple to split a page by splitting rows.
//
// Note due to the way RefCountedSet works, we are short one value, but
// this is a theoretical limit we accept. A page with a single row max
// columns wide would be one short of having every cell have a unique style.
... (198 lines truncated)
</file>

<file path="src/terminal/stream_continuation.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const Parser = @import("Parser.zig");
const UTF8Decoder = @import("UTF8Decoder.zig");

/// Errors possible while validating a snapshot continuation.
pub const ValidateError = error{
    /// Nonempty input left both the VT parser and UTF-8 decoder at ground.
    ///
    /// A continuation exists only to reconstruct state that was unfinished at
    /// the snapshot cut. Input that returns to ground is a complete PTY
    /// fragment, not a continuation. Replaying it would repeat work already
    /// represented by the Terminal snapshot. For example, `ESC [ 3 1 m`
    /// completes an SGR command and must not be stored as a continuation.
    NoPendingState,

    /// The input does not begin at its effective replay start.
    ///
    /// A later ESC supersedes earlier VT parser state, and a pending UTF-8
    /// codepoint begins at its lead byte. Any prefix before that effective
    /// start is unnecessary and would disappear when the restored Stream
    /// exports its continuation again. Rejecting the prefix preserves the
    /// byte-identical re-export invariant and prevents unrelated prior input
    /// from being replayed.
    NonCanonicalContinuation,

    /// Replaying the input would perform handler-visible work.
    ///
    /// The Terminal snapshot already contains every mutation committed before
... (577 lines truncated)
</file>

<file path="src/terminal/stream_terminal.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const build_options = @import("terminal_options");
const testing = std.testing;
const apc = @import("apc.zig");
const xt_checksum = @import("xt_checksum.zig");
const clipboard = @import("clipboard.zig");
const csi = @import("csi.zig");
const dcs = @import("dcs.zig");
const device_attributes = @import("device_attributes.zig");
const device_status = @import("device_status.zig");
const stream = @import("stream.zig");
const Action = stream.Action;
const Screen = @import("Screen.zig");
const color = @import("color.zig");
const modes = @import("modes.zig");
const osc = @import("osc.zig");
const osc_color = @import("osc/parsers/color.zig");
const kitty_clipboard = @import("kitty/clipboard.zig");
const kitty_color = @import("kitty/color.zig");
const paste_pkg = @import("paste.zig");
const kitty_dnd = @import("kitty/dnd.zig");
const lib = @import("lib.zig");
const size_report = @import("size_report.zig");
const simd = @import("../simd/main.zig");
const terminfo = @import("../terminfo/main.zig");
const Terminal = @import("Terminal.zig");

const log = std.log.scoped(.stream_terminal);

... (7353 lines truncated)
</file>

<file path="src/terminal/stream.zig">
const streampkg = @This();
const std = @import("std");
const build_options = @import("terminal_options");
const assert = @import("../quirks.zig").inlineAssert;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const simd = @import("../simd/main.zig");
const lib = @import("lib.zig");
const Parser = @import("Parser.zig");
const ansi = @import("ansi.zig");
const charsets = @import("charsets.zig");
const device_attributes = @import("device_attributes.zig");
const xt_checksum = @import("xt_checksum.zig");
const device_status = @import("device_status.zig");
const csi = @import("csi.zig");
const kitty = @import("kitty.zig");
const modes = @import("modes.zig");
const osc = @import("osc.zig");
const sgr = @import("sgr.zig");
const continuationpkg = @import("stream_continuation.zig");
const UTF8Decoder = @import("UTF8Decoder.zig");
const MouseShape = @import("mouse.zig").Shape;

const log = std.log.scoped(.stream);

/// Flip this to true when you want verbose debug output for
/// debugging terminal stream issues. In addition to louder
/// output this will also disable the SIMD optimizations in
/// order to make it easier to see every byte. So if you're
/// debugging an issue in the SIMD code then you'll need to
... (5611 lines truncated)
</file>

<file path="src/terminal/StringMap.zig">
/// A string along with the mapping of each individual byte in the string
/// to the point in the screen.
const StringMap = @This();

const std = @import("std");
const build_options = @import("terminal_options");
const oni = @import("oniguruma");
const point = @import("point.zig");
const PinMap = @import("formatter.zig").PinMap;
const Selection = @import("Selection.zig");
const Screen = @import("Screen.zig");
const Allocator = std.mem.Allocator;

// Retry budget for StringMap regex searches.
//
// Units are Oniguruma retry steps (internal backtracking/retry counter),
// not bytes/characters/time.
const oni_search_retry_limit = 100_000;

string: [:0]const u8,

/// Mapping of string byte offsets to pins. See PinMap for the
/// storage details.
map: PinMap.Map,

pub fn deinit(self: StringMap, alloc: Allocator) void {
    alloc.free(self.string);
    var map = self.map;
    map.deinit(alloc);
}
... (267 lines truncated)
</file>

<file path="src/terminal/style.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const fastprint = @import("../fastprint.zig");
const color = @import("color.zig");
const sgr = @import("sgr.zig");
const page = @import("page.zig");
const size = @import("size.zig");
const Offset = size.Offset;
const OffsetBuf = size.OffsetBuf;
const RefCountedSet = @import("ref_counted_set.zig").RefCountedSet;

/// The unique identifier for a style. This is at most the number of cells
/// that can fit into a terminal page.
pub const Id = size.StyleCountInt;

/// The Id to use for default styling.
pub const default_id: Id = 0;

/// The style attributes for a cell.
pub const Style = struct {
    /// Various colors, all self-explanatory.
    fg_color: Color = .none,
    bg_color: Color = .none,
    underline_color: Color = .none,

    /// On/off attributes that don't require much bit width so we use
    /// a packed struct to make this take up significantly less space.
    flags: Flags = .{},

... (1211 lines truncated)
</file>

<file path="src/terminal/sys.zig">
//! System interface for the terminal package.
//!
//! This provides runtime-swappable function pointers for operations that
//! depend on external implementations (e.g. image decoding). Each function
//! pointer is initialized with a default implementation if available.
//!
//! This exists so that the terminal package doesn't have hard dependencies
//! on specific libraries and enables embedders of the terminal package to
//! swap out implementations as needed at startup to provide their own
//! implementations.
const std = @import("std");
const Allocator = std.mem.Allocator;
const build_options = @import("terminal_options");

/// Decode PNG data into RGBA pixels. If null, PNG decoding is unsupported
/// and the exact semantics are up to callers. For example, the Kitty Graphics
/// Protocol will work but cannot accept PNG images.
pub var decode_png: ?DecodePngFn = png: {
    if (build_options.artifact == .lib) break :png null;
    break :png &decodePngWuffs;
};

pub const DecodeError = Allocator.Error || error{InvalidData};
pub const DecodePngFn = *const fn (Allocator, []const u8) DecodeError!Image;

/// The result of decoding an image. The caller owns the returned data
/// and must free it with the same allocator that was passed to the
/// decode function.
pub const Image = struct {
    width: u32,
... (73 lines truncated)
</file>

<file path="src/terminal/Tabstops.zig">
//! Keep track of the location of tabstops.
//!
//! This is implemented as a bit set. There is a preallocation segment that
//! is used for almost all screen sizes. Then there is a dynamically allocated
//! segment if the screen is larger than the preallocation amount.
//!
//! In reality, tabstops don't need to be the most performant in any metric.
//! This implementation tries to balance denser memory usage (by using a bitset)
//! and minimizing unnecessary allocations.
const Tabstops = @This();

const std = @import("std");
const tripwire = @import("../tripwire.zig");
const Allocator = std.mem.Allocator;
const testing = std.testing;
const assert = @import("../quirks.zig").inlineAssert;

/// Unit is the type we use per tabstop unit (see file docs).
const Unit = u8;
const unit_bits = @bitSizeOf(Unit);

/// The number of columns we preallocate for. This is kind of high which
/// costs us some memory, but this is more columns than my 6k monitor at
/// 12-point font size, so this should prevent allocation in almost all
/// real world scenarios for the price of wasting at most
/// (columns / sizeOf(Unit)) bytes.
const prealloc_columns = 512;

/// The number of entries we need for our preallocation.
const prealloc_count = prealloc_columns / unit_bits;
... (268 lines truncated)
</file>

<file path="src/terminal/Terminal.zig">
//! The primary terminal emulation structure. This represents a single
//! "terminal" containing a grid of characters and exposes various operations
//! on that grid. This also maintains the scrollback buffer.
const Terminal = @This();

const std = @import("std");
const build_options = @import("terminal_options");
const lib = @import("lib.zig");
const assert = @import("../quirks.zig").inlineAssert;
const tripwire = @import("../tripwire.zig");
const testing = std.testing;
const Allocator = std.mem.Allocator;
const simd = @import("../simd/main.zig");
const unicode = @import("../unicode/main.zig");
const uucode = @import("uucode");

const ansi = @import("ansi.zig");
const modespkg = @import("modes.zig");
const charsets = @import("charsets.zig");
const xt_checksum = @import("xt_checksum.zig");
const csi = @import("csi.zig");
const hyperlink = @import("hyperlink.zig");
const glyph = @import("apc/glyph.zig");
const kitty = @import("kitty.zig");
const osc = @import("osc.zig");
const point = @import("point.zig");
const sgr = @import("sgr.zig");
const Tabstops = @import("Tabstops.zig");
const color = @import("color.zig");
const mouse = @import("mouse.zig");
... (16795 lines truncated)
</file>

<file path="src/terminal/tmux.zig">
//! Types and functions related to tmux protocols.

const control = @import("tmux/control.zig");
const layout = @import("tmux/layout.zig");
pub const output = @import("tmux/output.zig");
pub const ControlParser = control.Parser;
pub const ControlNotification = control.Notification;
pub const Layout = layout.Layout;
pub const Viewer = @import("tmux/viewer.zig").Viewer;

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/terminal/UTF8Decoder.zig">
//! DFA-based non-allocating error-replacing UTF-8 decoder.
//!
//! This implementation is based largely on the excellent work of
//! Bjoern Hoehrmann, with slight modifications to support error-
//! replacement.
//!
//! For details on Bjoern's DFA-based UTF-8 decoder, see
//! http://bjoern.hoehrmann.de/utf-8/decoder/dfa (MIT licensed)
const UTF8Decoder = @This();

const std = @import("std");
const testing = std.testing;

const log = std.log.scoped(.utf8decoder);

// zig fmt: off
const char_classes = [_]u4{
   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
   1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,  9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
   7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
   8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
  10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8,
};

const transitions = [_]u8 {
   0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
  12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
... (113 lines truncated)
</file>

<file path="src/terminal/x11_color.zig">
const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const RGB = @import("color.zig").RGB;

/// A single X11 color entry.
pub const Entry = struct {
    /// Color name. Null-terminated so it can be exposed through the C API
    /// without runtime allocation.
    name: [:0]const u8,
    color: RGB,
};

/// All X11 colors in rgb.txt file order.
///
/// This is kept separate from `map` because the C API needs stable file order
/// and null-terminated names. `ColorMap` keys do not provide that contract.
pub const entries: []const Entry = entriesArray();

/// The map of all available X11 colors.
pub const map = colorMap();

pub const ColorMap = std.StaticStringMapWithEql(
    RGB,
    std.static_string_map.eqlAsciiIgnoreCase,
);

fn entriesArray() []const Entry {
    @setEvalBranchQuota(1_000_000);
    const len = std.mem.count(u8, data, "\n");
    var result: [len]Entry = undefined;
... (78 lines truncated)
</file>

<file path="src/terminal/xt_checksum.zig">
//! DECRQCRA (Request Checksum of Rectangular Area) and XTCHECKSUM
//! (select the checksum variant DECRQCRA computes).
//!
//! The checksum follows xterm's `xtermCheckRect`. No real VT420 was
//! available to compare against while this was written, so xterm is the
//! reference:
//!
//! - `xtermCheckRect`: https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411/screen.c#L3162-L3290
//! - `xtermCharSetDec`: https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411/charsets.c#L608
const std = @import("std");
const testing = std.testing;
const PageList = @import("PageList.zig");
const Screen = @import("Screen.zig");
const Selection = @import("Selection.zig");
const Terminal = @import("Terminal.zig");
const pagepkg = @import("page.zig");
const point = @import("point.zig");
const style = @import("style.zig");

/// The XTCHECKSUM (CSI Ps # y) bits. The zero value is the DEC checksum,
/// which is also what a full reset restores.
///
/// These are xterm's `CSBITS`, which it also takes from the
/// `checksumExtension` resource:
///
/// - `CSBITS`: https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411/ptyx.h#L488-L496
/// - XTCHECKSUM: https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411/charproc.c#L6044-L6050
/// - Reset to `checksumExtension`: https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411/charproc.c#L14424-L14426
/// - `checksumExtension` docs: https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411/xterm.man#L2870-L2896
/// - XTCHECKSUM docs: https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411/ctlseqs.ms#L2562-L2569
... (450 lines truncated)
</file>

<file path="src/terminfo/ghostty.zig">
const std = @import("std");
const Source = @import("Source.zig");

/// Ghostty's terminfo entry.
pub const ghostty: Source = .{
    .names = &.{
        // We support the "xterm-" prefix because some poorly behaved programs
        // use this to detect if the terminal supports 256 colors and other
        // features.
        // HACK: This is a hack on a hack...we use "xterm-ghostty" to prevent
        // vim from breaking, and when we do this as the default we break
        // tcell-based applications (lazygit, aerc, etc). tcell has a bug where
        // the primary terminfo name must be the value of TERM.
        // https://github.com/gdamore/tcell/pull/639 fixes the issue but is not
        // merged yet. Consider switching these in the future.
        "xterm-ghostty",

        // The preferred name
        "ghostty",

        // Our "formal" name
        "Ghostty",
    },

    // NOTE: These capabilities are super underdocumented and I'm not 100%
    // I've got the list or my understanding of any in this list fully correct.
    // As we learn more, please update the comments to better explain what
    // anything means.
    //
    // I've marked some capabilities as "???" if I don't understand what they
... (381 lines truncated)
</file>

<file path="src/terminfo/main.zig">
//! Package terminfo provides functionality related to terminfo/termcap files.
//!
//! At the time of writing this comment, the focus is on generating terminfo
//! files so that we can maintain our terminfo in Zig instead of hand-writing
//! the archaic (imo) terminfo format by hand. But eventually we may want to
//! extract this into a more full-featured library on its own.

pub const ghostty = @import("ghostty.zig").ghostty;
pub const version = @import("ghostty.zig").version;
pub const Source = @import("Source.zig");

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/terminfo/Source.zig">
//! Terminfo source format. This can be used to encode terminfo files.
//! This cannot parse terminfo source files yet because it isn't something
//! I need to do but this can be added later.
//!
//! Background: https://invisible-island.net/ncurses/man/terminfo.5.html

const Source = @This();

const std = @import("std");

/// The set of names for the terminal. These match the TERM environment variable
/// and are used to look up this terminal. Historically, the final name in the
/// list was the most common name for the terminal and contains spaces and
/// other characters. See terminfo(5) for details.
names: []const [:0]const u8,

/// The set of capabilities in this terminfo file.
capabilities: []const Capability,

/// A capability in a terminfo file. This also includes any "use" capabilities
/// since they behave just like other capabilities as documented in terminfo(5).
pub const Capability = struct {
    /// The name of capability. This is the "Cap-name" value in terminfo(5).
    name: []const u8,
    value: Value,

    pub const Value = union(enum) {
        /// Canceled value, i.e. suffixed with @
        canceled: void,

... (220 lines truncated)
</file>

<file path="src/termio/backend.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const posix = std.posix;
const renderer = @import("../renderer.zig");
const terminal = @import("../terminal/main.zig");
const termio = @import("../termio.zig");
const ProcessInfo = @import("../pty.zig").ProcessInfo;

// The preallocation size for the write request pool. This should be big
// enough to satisfy most write requests. It must be a power of 2.
const WRITE_REQ_PREALLOC = std.math.pow(usize, 2, 5);

/// The kinds of backends.
pub const Kind = enum { exec };

/// Configuration for the various backend types.
pub const Config = union(Kind) {
    /// Exec uses posix exec to run a command with a pty.
    exec: termio.Exec.Config,
};

/// Backend implementations. A backend is responsible for owning the pty
/// behavior and providing read/write capabilities.
pub const Backend = union(Kind) {
    exec: termio.Exec,

    pub fn deinit(self: *Backend) void {
        switch (self.*) {
            .exec => |*exec| exec.deinit(),
        }
... (100 lines truncated)
</file>

<file path="src/termio/Exec.zig">
//! Exec implements the logic for starting and stopping a subprocess with a
//! pty as well as spinning up the necessary read thread to read from the
//! pty and forward it to the Termio instance.
const Exec = @This();

const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const posix = std.posix;
const global = @import("../global.zig");
const xev = global.xev;
const apprt = @import("../apprt.zig");
const build_config = @import("../build_config.zig");
const configpkg = @import("../config.zig");
const crash = @import("../crash/main.zig");
const fastmem = @import("../fastmem.zig");
const internal_os = @import("../os/main.zig");
const renderer = @import("../renderer.zig");
const shell_integration = @import("shell_integration.zig");
const terminal = @import("../terminal/main.zig");
const termio = @import("../termio.zig");
const Command = @import("../Command.zig");
const ptypkg = @import("../pty.zig");
const Pty = ptypkg.Pty;
const EnvMap = std.process.Environ.Map;
const PasswdEntry = internal_os.passwd.Entry;
const windows = internal_os.windows;
const ProcessInfo = @import("../pty.zig").ProcessInfo;
... (2276 lines truncated)
</file>

<file path="src/termio/mailbox.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const global = @import("../global.zig");
const xev = global.xev;
const renderer = @import("../renderer.zig");
const termio = @import("../termio.zig");
const BlockingQueue = @import("../datastruct/main.zig").BlockingQueue;

const log = std.log.scoped(.io_writer);

/// A queue used for storing messages that is periodically drained.
/// Typically used by a multi-threaded application. The capacity is
/// hardcoded to a value that empirically has made sense for Ghostty usage
/// but I'm open to changing it with good arguments.
const Queue = BlockingQueue(termio.Message, 64);

/// The location to where write-related messages are sent.
pub const Mailbox = union(enum) {
    // /// Write messages to an unbounded list backed by an allocator.
    // /// This is useful for single-threaded applications where you're not
    // /// afraid of running out of memory. You should be careful that you're
    // /// processing this in a timely manner though since some heavy workloads
    // /// will produce a LOT of messages.
    // ///
    // /// At the time of authoring this, the primary use case for this is
    // /// testing more than anything, but it probably will have a use case
    // /// in libghostty eventually.
    // unbounded: std.ArrayList(termio.Message),

    /// Write messages to a SPSC queue for multi-threaded applications.
... (80 lines truncated)
</file>

<file path="src/termio/message.zig">
const std = @import("std");
const Allocator = std.mem.Allocator;
const renderer = @import("../renderer.zig");
const terminal = @import("../terminal/main.zig");
const termio = @import("../termio.zig");
const MessageData = @import("../datastruct/main.zig").MessageData;

/// The messages that can be sent to an IO thread.
///
/// This is not a tiny structure (~40 bytes at the time of writing this comment),
/// but the number of messages we send to the IO thread is also very small.
/// At the current size we can queue 26,000 messages before consuming a MB of RAM.
pub const Message = union(enum) {
    /// Represents a write request. Magic number comes from the largest
    /// other union value. It can be upped if we add a larger union member
    /// in the future.
    pub const WriteReq = MessageData(u8, 38);

    /// Request a color scheme report is sent to the PTY.
    color_scheme_report: struct {
        /// Force write the current color scheme
        force: bool,
    },

    /// Request a visibility report is sent to the PTY.
    visibility_report: struct {
        /// The visibility state to report.
        visible: bool,

        /// Send the report even when mode 2033 is disabled.
... (117 lines truncated)
</file>

<file path="src/termio/Options.zig">
//! The options that are used to configure a terminal IO implementation.

const xev = @import("../global.zig").xev;
const apprt = @import("../apprt.zig");
const renderer = @import("../renderer.zig");
const Config = @import("../config.zig").Config;
const termio = @import("../termio.zig");

/// All size metrics for the terminal.
size: renderer.Size,

/// The full app configuration. This is only available during initialization.
/// The memory it points to is NOT stable after the init call so any values
/// in here must be copied.
full_config: *const Config,

/// The derived configuration for this termio implementation.
config: termio.Termio.DerivedConfig,

/// The backend for termio that implements where reads/writes are sourced.
backend: termio.Backend,

/// The mailbox for the terminal. This is how messages are delivered.
/// If you're using termio.Thread this MUST be "mailbox".
mailbox: termio.Mailbox,

/// The render state. The IO implementation can modify anything here. The
/// surface thread will setup the initial "terminal" pointer but the IO impl
/// is free to change that if that is useful (i.e. doing some sort of dual
/// terminal implementation.)
... (12 lines truncated)
</file>

<file path="src/termio/shell_integration.zig">
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const EnvMap = std.process.Environ.Map;
const config = @import("../config.zig");
const homedir = @import("../os/homedir.zig");
const internal_os = @import("../os/main.zig");
const global = @import("../global.zig");

const log = std.log.scoped(.shell_integration);

/// Shell types we support
pub const Shell = enum {
    bash,
    elvish,
    fish,
    nushell,
    zsh,
};

/// The result of setting up a shell integration.
pub const ShellIntegration = struct {
    /// The successfully-integrated shell.
    shell: Shell,

    /// The command to use to start the shell with the integration.
    /// In most cases this is identical to the command given but for
    /// bash in particular it may be different.
    ///
... (1029 lines truncated)
</file>

<file path="src/termio/stream_handler.zig">
const std = @import("std");
const builtin = @import("builtin");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const global = @import("../global.zig");
const xev = global.xev;
const apprt = @import("../apprt.zig");
const build_config = @import("../build_config.zig");
const configpkg = @import("../config.zig");
const internal_os = @import("../os/main.zig");
const renderer = @import("../renderer.zig");
const termio = @import("../termio.zig");
const terminal = @import("../terminal/main.zig");
const terminfo = @import("../terminfo/main.zig");
const posix = std.posix;

const log = std.log.scoped(.io_handler);

/// This is used as the handler for the terminal.Stream type. This is
/// stateful and is expected to live for the entire lifetime of the terminal.
/// It is NOT VALID to stop a stream handler, create a new one, and use that
/// unless all of the member fields are copied.
pub const StreamHandler = struct {
    alloc: Allocator,
    size: *renderer.Size,
    terminal: *terminal.Terminal,

    /// Mailbox for data to the termio thread.
    termio_mailbox: *termio.Mailbox,

... (1974 lines truncated)
</file>

<file path="src/termio/Termio.zig">
//! Primary terminal IO ("termio") state. This maintains the terminal state,
//! pty, subprocess, etc. This is flexible enough to be used in environments
//! that don't have a pty and simply provides the input/output using raw
//! bytes.
pub const Termio = @This();

const std = @import("std");
const assert = @import("../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const EnvMap = std.process.Environ.Map;
const posix = std.posix;
const termio = @import("../termio.zig");
const StreamHandler = @import("stream_handler.zig").StreamHandler;
const terminalpkg = @import("../terminal/main.zig");
const global = @import("../global.zig");
const xev = global.xev;
const renderer = @import("../renderer.zig");
const apprt = @import("../apprt.zig");
const internal_os = @import("../os/main.zig");
const windows = internal_os.windows;
const configpkg = @import("../config.zig");
const ProcessInfo = @import("../pty.zig").ProcessInfo;
const compat_file = @import("../lib/compat/file.zig");

const log = std.log.scoped(.io_exec);

/// Mutex state argument for queueMessage.
pub const MutexState = enum { locked, unlocked };

... (820 lines truncated)
</file>

<file path="src/termio/Thread.zig">
//! Represents the "writer" thread for terminal IO. The reader side is
//! handled by the Termio struct itself and dependent on the underlying
//! implementation (i.e. if its a pty, manual, etc.).
//!
//! The writer thread does handle writing bytes to the pty but also handles
//! different events such as starting synchronized output, changing some
//! modes (like linefeed), etc. The goal is to offload as much from the
//! reader thread as possible since it is the hot path in parsing VT
//! sequences and updating terminal state.
//!
//! This thread state can only be used by one thread at a time.
pub const Thread = @This();

const std = @import("std");
const ArenaAllocator = std.heap.ArenaAllocator;
const builtin = @import("builtin");
const global = @import("../global.zig");
const xev = global.xev;
const crash = @import("../crash/main.zig");
const internal_os = @import("../os/main.zig");
const termio = @import("../termio.zig");
const renderer = @import("../renderer.zig");

const Allocator = std.mem.Allocator;
const log = std.log.scoped(.io_thread);

/// This stores the information that is coalesced.
const Coalesce = struct {
    /// The number of milliseconds to coalesce certain messages like resize for.
    /// Not all message types are coalesced.
... (516 lines truncated)
</file>

<file path="src/unicode/grapheme.zig">
const std = @import("std");
const table = @import("props_table.zig").table;
const uucode = @import("uucode");

/// Width change requested by a codepoint that continues a grapheme cluster.
pub const GraphemeWidthEffect = enum {
    /// Do not append the codepoint to the cluster and leave break state as it
    /// was before seeing it.
    ignore,

    /// Append the codepoint but leave the current cluster width unchanged.
    no_change,

    /// Make the cluster occupy two terminal cells.
    wide,

    /// Make the cluster occupy one terminal cell.
    narrow,
};

/// Result of measuring the first grapheme cluster in a codepoint slice.
pub const GraphemeWidth = struct {
    /// Number of codepoints consumed from the input slice.
    len: usize,

    /// Display width in terminal cells.
    width: u2,
};

/// Determines if there is a grapheme break between two codepoints. This
... (334 lines truncated)
</file>

<file path="src/unicode/lut.zig">
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;

// This whole file is based on the algorithm described here:
// https://here-be-braces.com/fast-lookup-of-unicode-properties/

/// Creates a type that is able to generate a 3-level lookup table
/// from a Unicode codepoint to a mapping of type Elem. The lookup table
/// generally is expected to be codegen'd and then reloaded, although it
/// can in theory be generated at runtime.
///
/// Context must have two functions:
///   - `get(Context, u21) Elem`: returns the mapping for a given codepoint
///   - `eql(Context, Elem, Elem) bool`: returns true if two mappings are equal
///
pub fn Generator(
    comptime Elem: type,
    comptime Context: type,
) type {
    return struct {
        const Self = @This();

        const block_size = 256;
        const Block = [block_size]u16;

        /// Mapping of a block to its index in the stage2 array.
        const BlockMap = std.HashMap(
            Block,
            u16,
... (159 lines truncated)
</file>

<file path="src/unicode/main.zig">
pub const lut = @import("lut.zig");

const grapheme = @import("grapheme.zig");
pub const table = @import("props_table.zig").table;
pub const Properties = @import("props.zig").Properties;
pub const GraphemeWidthEffect = grapheme.GraphemeWidthEffect;
pub const GraphemeWidth = grapheme.GraphemeWidth;
pub const graphemeBreak = grapheme.graphemeBreak;
pub const graphemeWidth = grapheme.graphemeWidth;
pub const graphemeWidthEffect = grapheme.graphemeWidthEffect;

/// Returns the terminal display width of a codepoint in terminal
/// grid cells: 0, 1, or 2.
///
/// This is the same width table the terminal uses when laying out
/// printed text: 0 for zero-width codepoints (controls, combining
/// marks, default-ignorables, surrogates), 2 for wide codepoints
/// (East Asian Wide/Fullwidth, regional indicators, clamped at 2),
/// and 1 otherwise.
///
/// This operates on a single codepoint and cannot account for
/// grapheme-cluster-level width rules (VS16, combining sequences);
/// callers needing cluster-accurate widths should use graphemeWidth().
/// Summing per-codepoint widths is only correct when mode 2027 is
/// disabled.
pub fn codepointWidth(cp: u21) u2 {
    return table.get(cp).width;
}

test "codepointWidth" {
... (34 lines truncated)
</file>

<file path="src/unicode/props_table.zig">
const Properties = @import("props.zig").Properties;
const lut = @import("lut.zig");

/// The lookup tables for Ghostty.
pub const table = table: {
    // This is only available after running a generator as part of the Ghostty
    // build.zig process, but due to Zig's lazy analysis we can still reference
    // it here.
    //
    // An example process is the `main` in `props_uucode.zig`
    const generated = @import("unicode_tables").Tables(Properties);
    const Tables = lut.Tables(Properties);
    break :table Tables{
        .stage1 = &generated.stage1,
        .stage2 = &generated.stage2,
        .stage3 = &generated.stage3,
    };
};
</file>

<file path="src/unicode/props_uucode.zig">
const props = @This();
const std = @import("std");
const assert = std.debug.assert;
const uucode = @import("uucode");
const lut = @import("lut.zig");
const Properties = @import("props.zig").Properties;

pub fn get(cp: u21) Properties {
    if (cp > uucode.config.max_code_point) return .{
        .width = 1,
        .width_zero_in_grapheme = true,
        .grapheme_break = .other,
        .emoji_vs_base = false,
    };

    return .{
        .width = uucode.get(.width, cp),
        .width_zero_in_grapheme = uucode.get(.wcwidth_zero_in_grapheme, cp),
        .grapheme_break = uucode.get(.grapheme_break_no_control, cp),
        .emoji_vs_base = uucode.get(.is_emoji_vs_base, cp),
    };
}

/// Runnable binary to generate the lookup tables and output to stdout.
pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    const gen: lut.Generator(
        Properties,
        struct {
... (54 lines truncated)
</file>

<file path="src/unicode/props.zig">
//! Property set per codepoint that Ghostty cares about.
//!
//! Adding to this lets you find new properties but also potentially makes
//! our lookup tables less efficient. Any changes to this should run the
//! benchmarks in src/bench to verify that we haven't regressed.

const std = @import("std");
const uucode = @import("uucode");

pub const Properties = packed struct(u16) {
    /// Codepoint width. We clamp to [0, 2] since Ghostty handles control
    /// characters and we max out at 2 for wide characters (i.e. 3-em dash
    /// becomes a 2-em dash).
    width: u2 = 0,

    /// Whether the code point does not contribute to the width of a grapheme
    /// cluster (not used for single code point cells).
    width_zero_in_grapheme: bool = false,

    /// Grapheme break property.
    grapheme_break: uucode.types.GraphemeBreakNoControl = .other,

    /// Emoji VS compatibility
    emoji_vs_base: bool = false,

    /// Explicit padding to give the struct a power-of-two backing integer.
    /// This is a performance workaround: with a non-power-of-two backing
    /// integer (u9), Zig 0.16 lowers loads/stores of this struct through
    /// mismatched exotic-width LLVM integer types (store i9 / load i16),
    /// which blocks LLVM from promoting temporaries to registers and forces
... (34 lines truncated)
</file>

<file path="src/unicode/symbols_table.zig">
const lut = @import("lut.zig");

/// The lookup tables for Ghostty.
pub const table = table: {
    // This is only available after running a generator as part of the Ghostty
    // build.zig process, but due to Zig's lazy analysis we can still reference
    // it here.
    //
    // An example process is the `main` in `symbols_uucode.zig`
    const generated = @import("symbols_tables").Tables(bool);
    const Tables = lut.Tables(bool);
    break :table Tables{
        .stage1 = &generated.stage1,
        .stage2 = &generated.stage2,
        .stage3 = &generated.stage3,
    };
};
</file>

<file path="src/unicode/symbols_uucode.zig">
const std = @import("std");
const uucode = @import("uucode");
const lut = @import("lut.zig");

/// Runnable binary to generate the lookup tables and output to stdout.
pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    const gen: lut.Generator(
        bool,
        struct {
            pub fn get(ctx: @This(), cp: u21) !bool {
                _ = ctx;
                return if (cp > uucode.config.max_code_point)
                    false
                else
                    uucode.get(.is_symbol, @intCast(cp));
            }

            pub fn eql(ctx: @This(), a: bool, b: bool) bool {
                _ = ctx;
                return a == b;
            }
        },
    ) = .{};

    const t = try gen.generate(alloc);
    defer alloc.free(t.stage1);
    defer alloc.free(t.stage2);
    defer alloc.free(t.stage3);
... (37 lines truncated)
</file>

<file path="src/App.zig">
//! App is the primary GUI application for ghostty. This builds the window,
//! sets up the renderer, etc. The primary run loop is started by calling
//! the "run" function.
const App = @This();

const std = @import("std");
const builtin = @import("builtin");
const assert = @import("quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const apprt = @import("apprt.zig");
const Surface = @import("Surface.zig");
const input = @import("input.zig");
const configpkg = @import("config.zig");
const Config = configpkg.Config;
const BlockingQueue = @import("datastruct/main.zig").BlockingQueue;
const renderer = @import("renderer.zig");
const font = @import("font/main.zig");
const global = @import("global.zig");

const log = std.log.scoped(.app);

const SurfaceList = std.ArrayListUnmanaged(*apprt.Surface);

/// General purpose allocator
alloc: Allocator,

/// The list of surfaces that are currently active.
surfaces: SurfaceList,

/// This is true if the app that Ghostty is in is focused. This may
... (611 lines truncated)
</file>

<file path="src/apprt.zig">
//! "apprt" is the "application runtime" package. This abstracts the
//! application runtime and lifecycle management such as creating windows,
//! getting user input (mouse/keyboard), etc.
//!
//! This enables compile-time interfaces to be built to swap out the underlying
//! application runtime. For example: pure macOS Cocoa, GTK+, browser, etc.
//!
//! The goal is to have different implementations share as much of the core
//! logic as possible, and to only reach out to platform-specific implementation
//! code when absolutely necessary.
const build_config = @import("build_config.zig");

const structs = @import("apprt/structs.zig");

pub const action = @import("apprt/action.zig");
pub const ipc = @import("apprt/ipc.zig");
pub const gtk = @import("apprt/gtk.zig");
pub const none = @import("apprt/none.zig");
pub const browser = @import("apprt/browser.zig");
pub const embedded = @import("apprt/embedded.zig");
pub const surface = @import("apprt/surface.zig");

pub const Action = action.Action;
pub const Runtime = @import("apprt/runtime.zig").Runtime;
pub const Target = action.Target;

pub const ContentScale = structs.ContentScale;
pub const Clipboard = structs.Clipboard;
pub const ClipboardContent = structs.ClipboardContent;
pub const ClipboardReadResult = structs.ClipboardReadResult;
... (31 lines truncated)
</file>

<file path="src/build_config.zig">
//! Build options, available at comptime. Used to configure features. This
//! will reproduce some of the fields from builtin and build_options just
//! so we can limit the amount of imports we need AND give us the ability
//! to shim logic and values into them later.
const std = @import("std");
const builtin = @import("builtin");
const options = @import("build_options");
const assert = std.debug.assert;
const apprt = @import("apprt.zig");
const font = @import("font/main.zig");
const rendererpkg = @import("renderer.zig");
const BuildConfig = @import("build/Config.zig");

pub const ReleaseChannel = BuildConfig.ReleaseChannel;

/// The semantic version of this build.
pub const version = options.app_version;
pub const version_string = options.app_version_string;

/// The release channel for this build.
pub const release_channel = std.meta.stringToEnum(ReleaseChannel, @tagName(options.release_channel)).?;

/// The optimization mode as a string.
pub const mode_string = mode: {
    const m = @tagName(builtin.mode);
    if (std.mem.lastIndexOfScalar(u8, m, '.')) |i| break :mode m[i..];
    break :mode m;
};

/// The artifact we're producing. This can be used to determine if we're
... (76 lines truncated)
</file>

<file path="src/cli.zig">
const diags = @import("cli/diagnostics.zig");

pub const args = @import("cli/args.zig");
pub const action = @import("cli/action.zig");
pub const ghostty = @import("cli/ghostty.zig");
pub const CompatibilityHandler = args.CompatibilityHandler;
pub const compatibilityRenamed = args.compatibilityRenamed;
pub const DiagnosticList = diags.DiagnosticList;
pub const Diagnostic = diags.Diagnostic;
pub const Location = diags.Location;

test {
    @import("std").testing.refAllDecls(@This());
}
</file>

<file path="src/Command.zig">
//! Command launches sub-processes. This is an alternate implementation to the
//! Zig std.process.Child since at the time of authoring this, std.process.Child
//! didn't support the options necessary to spawn a shell attached to a pty.
//!
//! Consequently, I didn't implement a lot of features that std.process.Child
//! supports because we didn't need them. Cross-platform subprocessing is not
//! a trivial thing to implement (I've done it in three separate languages now)
//! so if we want to replatform onto std.process.Child I'd love to do that.
//! This was just the fastest way to get something built.
//!
//! Issues with std.process.Child:
//!
//!   * No pre_exec callback for logic after fork but before exec.
//!   * posix_spawn is used for Mac, but doesn't support the necessary
//!     features for tty setup.
//!
//!
//! TODO: This may have changed a lot now with the new I/O implementations in
//! >= 0.16.0, so this might warrant a recheck.
const Command = @This();

const std = @import("std");
const builtin = @import("builtin");
const configpkg = @import("config.zig");
const global = @import("global.zig");
const internal_os = @import("os/main.zig");
const windows = internal_os.windows;
const TempDir = internal_os.TempDir;
const mem = std.mem;
const linux = std.os.linux;
... (1005 lines truncated)
</file>

<file path="src/config.zig">
const builtin = @import("builtin");

const file_load = @import("config/file_load.zig");
const formatter = @import("config/formatter.zig");
const formatter_file = @import("config/formatter_file.zig");
pub const Config = @import("config/Config.zig");
pub const conditional = @import("config/conditional.zig");
pub const io = @import("config/io.zig");
pub const string = @import("config/string.zig");
pub const edit = @import("config/edit.zig");
pub const url = @import("config/url.zig");

pub const ConditionalState = conditional.State;
pub const FileFormatter = formatter_file.FileFormatter;
pub const entryFormatter = formatter.entryFormatter;
pub const formatEntry = formatter.formatEntry;
pub const preferredDefaultFilePath = file_load.preferredDefaultFilePath;

// Field types
pub const BoldColor = Config.BoldColor;
pub const ClipboardAccess = Config.ClipboardAccess;
pub const Command = Config.Command;
pub const ConfirmCloseSurface = Config.ConfirmCloseSurface;
pub const CopyOnSelect = Config.CopyOnSelect;
pub const RightClickAction = Config.RightClickAction;
pub const MiddleClickAction = Config.MiddleClickAction;
pub const CustomShaderAnimation = Config.CustomShaderAnimation;
pub const FontSyntheticStyle = Config.FontSyntheticStyle;
pub const FontShapingBreak = Config.FontShapingBreak;
pub const FontStyle = Config.FontStyle;
... (28 lines truncated)
</file>

<file path="src/crc32c.zig">
//! CRC32C with hardware acceleration.
//!
//! The Zig standard library implementation processes one byte per table
//! lookup (as of Zig 0.16), which is more than an order of magnitude slower
//! than the dedicated CRC32C instructions available on aarch64 (CRC
//! extension) and x86_64 (SSE4.2). This module selects the best backend at
//! compile time.
//!
//! Targets without a dedicated instruction, such as WebAssembly, use a
//! custom implementation that is faster than Zig's stdlib.
//!
//! The resulting value is identical across all backends: this is the
//! iSCSI CRC32C parameter set (reflected, initial and final XOR
//! `0xFFFFFFFF`), matching `std.hash.crc.Crc32Iscsi`.

const std = @import("std");
const builtin = @import("builtin");

const Backend = enum {
    aarch64_crc,
    x86_64_sse42,
    software,
};

const backend: Backend = backend: {
    switch (builtin.cpu.arch) {
        .aarch64,
        .aarch64_be,
        => if (std.Target.aarch64.featureSetHas(
            builtin.cpu.features,
... (395 lines truncated)
</file>

<file path="src/fastmem.zig">
const std = @import("std");
const builtin = @import("builtin");

/// Same as @memmove but prefers libc memmove if it is
/// available because it is generally much faster?.
pub inline fn move(comptime T: type, dest: []T, source: []const T) void {
    if (builtin.link_libc) {
        _ = memmove(dest.ptr, source.ptr, source.len * @sizeOf(T));
    } else {
        @memmove(dest, source);
    }
}

/// Same as @memcpy but prefers libc memcpy if it is available
/// because it is generally much faster.
pub inline fn copy(comptime T: type, dest: []T, source: []const T) void {
    if (builtin.link_libc) {
        _ = memcpy(dest.ptr, source.ptr, source.len * @sizeOf(T));
    } else {
        @memcpy(dest[0..source.len], source);
    }
}

/// Moves the first item to the end.
/// For the reverse of this, use `fastmem.rotateOnceR`.
///
/// Same as std.mem.rotate(T, items, 1) but more efficient by using memmove
/// and a tmp var for the single rotated item instead of 3 calls to reverse.
///
/// e.g. `0 1 2 3` -> `1 2 3 0`.
... (49 lines truncated)
</file>

<file path="src/fastprint.zig">
//! Fastprint has fast printing routines that are significantly
//! faster than going through std.fmt.

const std = @import("std");

/// Print a decimal type T. The buffer is expected to be large enough so if
/// necessary use comptime with a buffer-too-large to determine your
/// max size needed. Returns the length written.
pub fn printDecimal(comptime T: type, buf: []u8, v: T) usize {
    // Note this only supports types as we need them.
    switch (T) {
        u8 => {
            if (v >= 100) {
                buf[0] = '0' + v / 100;
                buf[1..3].* = std.fmt.digits2(v % 100);
                return 3;
            }
            if (v >= 10) {
                buf[0..2].* = std.fmt.digits2(v);
                return 2;
            }
            buf[0] = '0' + v;
            return 1;
        },

        // This can probably be generalized...
        u21 => {
            // Maximum u21 is 2097151: at most 7 digits.
            var tmp: [7]u8 = undefined;
            var val: u32 = v;
... (39 lines truncated)
</file>

<file path="src/file_type.zig">
const std = @import("std");

const type_details: []const struct {
    typ: FileType,
    sigs: []const []const ?u8,
    exts: []const []const u8,
} = &.{
    .{
        .typ = .jpeg,
        .sigs = &.{
            &.{ 0xFF, 0xD8, 0xFF, 0xDB },
            &.{ 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01 },
            &.{ 0xFF, 0xD8, 0xFF, 0xEE },
            &.{ 0xFF, 0xD8, 0xFF, 0xE1, null, null, 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 },
            &.{ 0xFF, 0xD8, 0xFF, 0xE0 },
        },
        .exts = &.{ ".jpg", ".jpeg", ".jfif" },
    },
    .{
        .typ = .png,
        .sigs = &.{&.{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }},
        .exts = &.{".png"},
    },
    .{
        .typ = .gif,
        .sigs = &.{
            &.{ 'G', 'I', 'F', '8', '7', 'a' },
            &.{ 'G', 'I', 'F', '8', '9', 'a' },
        },
        .exts = &.{".gif"},
... (73 lines truncated)
</file>

<file path="src/global.zig">
const std = @import("std");
const builtin = @import("builtin");
const build_config = @import("build_config.zig");
const build_options = @import("build_options");
const cli = @import("cli.zig");
const internal_os = @import("os/main.zig");
const fontconfig = @import("fontconfig");
const glslang = @import("glslang");
const harfbuzz = @import("harfbuzz");
const oni = @import("oniguruma");
const crash = @import("crash/main.zig");
const renderer = @import("renderer.zig");
const apprt = @import("apprt.zig");
const assert = @import("quirks.zig").inlineAssert;
const allocTmpDir = @import("os/file.zig").allocTmpDir;
const freeTmpDir = @import("os/file.zig").freeTmpDir;

// This file should only be imported for certain platforms.
comptime {
    switch (@import("terminal_options").artifact) {
        .ghostty => {},
        // This file is not allowed to be included in libghostty-vt
        .lib => @compileError("global state cannot be used in libghostty-vt"),
    }
}

/// We export the xev backend we want to use so that the rest of
/// Ghostty can import this once and have access to the proper
/// backend.
pub const xev = @import("xev").Dynamic;
... (417 lines truncated)
</file>

<file path="src/helpgen.zig">
//! This program is used to generate the help strings from the configuration
//! file and CLI actions for Ghostty. These can then be used to generate
//! help, docs, website, etc.

const std = @import("std");
const Config = @import("config/Config.zig");
const Action = @import("cli/ghostty.zig").Action;
const KeybindAction = @import("input/Binding.zig").Action;

pub fn main(init: std.process.Init) !void {
    var buf: [4096]u8 = undefined;
    var stdout = std.Io.File.stdout().writerStreaming(init.io, &buf);
    const writer = &stdout.interface;
    try writer.writeAll(
        \\// THIS FILE IS AUTO GENERATED
        \\
        \\
    );

    const alloc = init.arena.allocator();
    try genConfig(alloc, writer);
    try genActions(alloc, writer);
    try genKeybindActions(alloc, writer);
    try stdout.end();
}

fn genConfig(alloc: std.mem.Allocator, writer: *std.Io.Writer) !void {
    var ast = try std.zig.Ast.parse(alloc, @embedFile("config/Config.zig"), .zig);
    defer ast.deinit(alloc);

... (159 lines truncated)
</file>

<file path="src/input.zig">
const std = @import("std");
const builtin = @import("builtin");

const config = @import("input/config.zig");
const mouse = @import("input/mouse.zig");
const key = @import("input/key.zig");
const key_mods = @import("input/key_mods.zig");
const keyboard = @import("input/keyboard.zig");

pub const command = @import("input/command.zig");
pub const function_keys = @import("input/function_keys.zig");
pub const keycodes = @import("input/keycodes.zig");
pub const key_encode = @import("input/key_encode.zig");
pub const kitty = @import("input/kitty.zig");
pub const mouse_encode = @import("input/mouse_encode.zig");
pub const paste = @import("input/paste.zig");

pub const ctrlOrSuper = key.ctrlOrSuper;
pub const Action = key.Action;
pub const Binding = @import("input/Binding.zig");
pub const Command = command.Command;
pub const Link = @import("input/Link.zig");
pub const Key = key.Key;
pub const KeyboardLayout = keyboard.Layout;
pub const KeyEvent = key.KeyEvent;
pub const KeyRemapSet = key_mods.RemapSet;
pub const InspectorMode = Binding.Action.InspectorMode;
pub const Mods = key_mods.Mods;
pub const MouseAction = mouse.Action;
pub const MouseButton = mouse.Button;
... (19 lines truncated)
</file>

<file path="src/lib_vt.zig">
//! This is the public API of the ghostty-vt Zig module.
//!
//! WARNING: The API is not guaranteed to be stable.
//!
//! The functionality is extremely stable, since it is extracted
//! directly from Ghostty which has been used in real world scenarios
//! by thousands of users for years. However, the API itself (functions,
//! types, etc.) may change without warning. We're working on stabilizing
//! this in the future.
const lib = @This();

const std = @import("std");
const builtin = @import("builtin");
const stderr = @import("os/stderr.zig");

// The public API below reproduces a lot of terminal/main.zig but
// is separate because (1) we need our root file to be in `src/`
// so we can access other directories and (2) we may want to withhold
// parts of `terminal` that are not ready for public consumption
// or are too Ghostty-internal.
const terminal = @import("terminal/main.zig");

/// System interface for the terminal package.
///
/// This module provides runtime-swappable function pointers for operations
/// that depend on external implementations. Embedders can use this to
/// provide or override default behaviors. These must be set at startup
/// before any terminal functionality is used.
///
/// This lets libghostty-vt have no runtime dependencies on external
... (558 lines truncated)
</file>

<file path="src/main_bench.zig">
const benchmark = @import("benchmark/main.zig");

comptime {
    // Force-reference our memset override so its export is emitted.
    // See quirks_memset.zig for details on why this exists.
    _ = @import("quirks_memset.zig");
}

pub const main = benchmark.cli.main;
</file>

<file path="src/main_build_data.zig">
//! This CLI is used to generate data that is used by the build process.
//!
//! We used to do this directly in our `build.zig` but the problem with
//! that approach is that any changes to the dependencies of this data would
//! force a rebuild of our build binary. If we're just doing something like
//! running tests and not emitting any of the info below, then that is a
//! complete waste.

const std = @import("std");
const Allocator = std.mem.Allocator;
const cli = @import("cli.zig");

pub const Action = enum {
    // Shell completions
    bash,
    fish,
    zsh,

    // Editor syntax files
    sublime,
    @"vim-syntax",
    @"vim-ftdetect",
    @"vim-ftplugin",
    @"vim-compiler",

    // Other
    terminfo,
};

pub fn main(init: std.process.Init) !void {
... (22 lines truncated)
</file>

<file path="src/main_c.zig">
// This is the main file for the C API. The C API is used to embed Ghostty
// within other applications. Depending on the build settings some APIs
// may not be available (i.e. embedding into macOS exposes various Metal
// support).
//
// This currently isn't supported as a general purpose embedding API.
// This is currently used only to embed ghostty within a macOS app. However,
// it could be expanded to be general purpose in the future.

const std = @import("std");
const assert = @import("quirks.zig").inlineAssert;
const posix = std.posix;
const builtin = @import("builtin");
const build_config = @import("build_config.zig");
const main = @import("main_ghostty.zig");
const global = @import("global.zig");
const apprt = @import("apprt.zig");
const internal_os = @import("os/main.zig");
const windows = @import("os/windows.zig");

// Some comptime assertions that our C API depends on.
comptime {
    // We allow tests to reference this file because we unit test
    // some of the C API. At runtime though we should never get these
    // functions unless we are building libghostty.
    if (!builtin.is_test) {
        assert(apprt.runtime == apprt.embedded);
    }
}

... (236 lines truncated)
</file>

<file path="src/main_gen.zig">
const synthetic = @import("synthetic/main.zig");

comptime {
    // Force-reference our memset override so its export is emitted.
    // See quirks_memset.zig for details on why this exists.
    _ = @import("quirks_memset.zig");
}

pub const main = synthetic.cli.main;
</file>

<file path="src/main_ghostty.zig">
//! The main entrypoint for the `ghostty` application. This also serves
//! as the process initialization code for the `libghostty` library.

const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const posix = std.posix;
const build_config = @import("build_config.zig");
const macos = @import("macos");
const cli = @import("cli.zig");
const renderer = @import("renderer.zig");
const apprt = @import("apprt.zig");

const App = @import("App.zig");
const Ghostty = @import("main_c.zig").Ghostty;
const global = @import("global.zig");

/// The return type for main() depends on the build artifact. The lib build
/// also calls "main" in order to run the CLI actions, but it calls it as
/// an API and not an entrypoint.
const MainReturn = switch (build_config.artifact) {
    .lib => noreturn,
    else => void,
};

pub fn main(minimal: std.process.Init.Minimal) !MainReturn {
    // We first start by initializing our global state. This will setup
    // process-level state we need to run the terminal. The reason we use
    // a global is because the C API needs to be able to access this state;
    // no other Zig code should EVER access the global state.
... (237 lines truncated)
</file>

<file path="src/main_wasm.zig">
// This is the main file for the WASM module. The WASM module has to
// export a C ABI compatible API.
const std = @import("std");
const builtin = @import("builtin");

comptime {
    _ = @import("os/wasm.zig");
    _ = @import("font/main.zig");
    _ = @import("terminal/main.zig");
    _ = @import("config.zig").Wasm;
    _ = @import("App.zig").Wasm;
}

pub const std_options = struct {
    // Set our log level. We try to get as much logging as possible but in
    // ReleaseSmall mode where we're optimizing for space, we elevate the
    // log level.
    pub const log_level: std.log.Level = switch (builtin.mode) {
        .Debug => .debug,
        .ReleaseSmall => .warn,
        else => .info,
    };

    // Set our log function
    pub const logFn = @import("os/wasm/log.zig").log;
};
</file>

<file path="src/main.zig">
const std = @import("std");
const build_config = @import("build_config.zig");

/// See build_config.ExeEntrypoint for why we do this.
const entrypoint = switch (build_config.exe_entrypoint) {
    .ghostty => @import("main_ghostty.zig"),
    .helpgen => @import("helpgen.zig"),
    .mdgen_ghostty_1 => @import("build/mdgen/main_ghostty_1.zig"),
    .mdgen_ghostty_5 => @import("build/mdgen/main_ghostty_5.zig"),
    .webgen_config => @import("build/webgen/main_config.zig"),
    .webgen_actions => @import("build/webgen/main_actions.zig"),
    .webgen_commands => @import("build/webgen/main_commands.zig"),
};

/// The main entrypoint for the program.
pub const main = entrypoint.main;

/// Standard options such as logger overrides.
pub const std_options: std.Options = if (@hasDecl(entrypoint, "std_options"))
    entrypoint.std_options
else
    .{};

comptime {
    // Force-reference our memset override so its export is emitted.
    // See quirks_memset.zig for details on why this exists.
    _ = @import("quirks_memset.zig");
}

test {
... (9 lines truncated)
</file>

<file path="src/math.zig">
/// Matrix type
pub const Mat = [4]F32x4;
pub const F32x4 = @Vector(4, f32);

/// 2D orthographic projection matrix
pub fn ortho2d(left: f32, right: f32, bottom: f32, top: f32) Mat {
    const w = right - left;
    const h = top - bottom;
    return .{
        .{ 2 / w, 0, 0, 0 },
        .{ 0, 2 / h, 0, 0 },
        .{ 0.0, 0.0, -1.0, 0.0 },
        .{ -(right + left) / w, -(top + bottom) / h, 0.0, 1.0 },
    };
}
</file>

<file path="src/pty.c">

</file>

<file path="src/pty.zig">
const std = @import("std");
const builtin = @import("builtin");
const windows = @import("os/main.zig").windows;
const posix = std.posix;
const assert = @import("quirks.zig").inlineAssert;

const log = std.log.scoped(.pty);

/// Redeclare this winsize struct so we can just use a Zig struct. This
/// layout should be correct on all tested platforms. The defaults on this
/// are some reasonable screen size but you should probably not use them.
pub const winsize = extern struct {
    ws_row: u16 = 100,
    ws_col: u16 = 80,
    ws_xpixel: u16 = 800,
    ws_ypixel: u16 = 600,
};

pub const Pty = switch (builtin.os.tag) {
    .windows => WindowsPty,
    .ios => NullPty,
    else => PosixPty,
};

/// The modes of a pty. Not all of these modes are supported on
/// all platforms but all platforms share the same mode struct.
///
/// The default values of fields in this struct are set to the
/// most typical values for a pty. This makes it easier for cross-platform
/// code which doesn't support all of the modes to work correctly.
... (490 lines truncated)
</file>

<file path="src/quirks_memset.zig">
//! Provides a fast `memset` symbol that overrides the slow scalar
//! implementation provided by Zig 0.16's compiler_rt.
//!
//! Consider deleting when upstream ships an optimized compiler_rt
//! memset (tracked by ziglang/zig#32091, maybe fixed at
//! ziglang/zig#35754). To verify it is safe to delete, check that
//! the disassembly of `memset` in a ReleaseFast binary is vectorized
//! (or at least not a byte-at-a-time loop).
//!
//! ## Background
//!
//! Zig 0.16.0 globally disabled LLVM loop auto-vectorization to work
//! around an LLVM 21 miscompilation (llvm/llvm-project#186922, see
//! the 0.16.0 release notes). compiler_rt's memset is a naive
//! byte-at-a-time loop that relied entirely on auto-vectorization,
//! so it now compiles to a scalar loop roughly 24x slower than what
//! Zig 0.15 produced.
//!
//! In benchmarks this made `ghostty-bench +terminal-stream` 2.8x slower on
//! ASCII input (memset was 63% of all executed instructions!).
//!
//! Because compiler_rt's symbol is weak, exporting a strong `memset`
//! from our own code transparently overrides it everywhere. The
//! implementation below is manually vectorized with `@Vector`, which
//! does not depend on the disabled loop vectorizer.
//!
//! Other mem functions deliberately not overridden:
//!
//! - memcpy/memmove: compiler_rt's implementations are manually
//!   vectorized upstream ("memcpyFast") and remain fast.
... (309 lines truncated)
</file>

<file path="src/quirks.zig">
//! Inspired by WebKit's quirks.cpp[1], this file centralizes all our
//! sad environment-specific hacks that we have to do to make things work.
//! This is a last resort; if we can find a general solution to a problem,
//! we of course prefer that, but sometimes other software, fonts, etc. are
//! just broken or weird and we have to work around it.
//!
//! [1]: https://github.com/WebKit/WebKit/blob/main/Source/WebCore/page/Quirks.cpp

const std = @import("std");
const builtin = @import("builtin");

const font = @import("font/main.zig");

/// If true, the default font features should be disabled for the given face.
pub fn disableDefaultFontFeatures(face: *const font.Face) bool {
    _ = face;

    // This function used to do something, but we integrated the logic
    // we checked for directly into our shaping algorithm. It's likely
    // there are other broken fonts for other reasons so I'm keeping this
    // around so its easy to add more checks in the future.
    return false;

    // var buf: [64]u8 = undefined;
    // const name = face.name(&buf) catch |err| switch (err) {
    //     // If the name doesn't fit in buf we know this will be false
    //     // because we have no quirks fonts that are longer than buf!
    //     error.OutOfMemory => return false,
    // };
}
... (28 lines truncated)
</file>

<file path="src/renderer.zig">
//! Renderer implementation and utilities. The renderer is responsible for
//! taking the internal screen state and turning into some output format,
//! usually for a screen.
//!
//! The renderer is closely tied to the windowing system which usually
//! has to prepare the window for the given renderer using system-specific
//! APIs. The renderers in this package assume that the renderer is already
//! setup (OpenGL has a context, Vulkan has a surface, etc.)

const build_config = @import("build_config.zig");

const cursor = @import("renderer/cursor.zig");
const message = @import("renderer/message.zig");
const size = @import("renderer/size.zig");
pub const shadertoy = @import("renderer/shadertoy.zig");
pub const Backend = @import("renderer/backend.zig").Backend;
pub const GenericRenderer = @import("renderer/generic.zig").Renderer;
pub const Metal = @import("renderer/Metal.zig");
pub const OpenGL = @import("renderer/OpenGL.zig");
pub const Options = @import("renderer/Options.zig");
pub const Overlay = @import("renderer/Overlay.zig");
pub const Thread = @import("renderer/Thread.zig");
pub const State = @import("renderer/State.zig");
pub const CursorStyle = cursor.Style;
pub const Message = message.Message;
pub const Size = size.Size;
pub const Coordinate = size.Coordinate;
pub const CellSize = size.CellSize;
pub const ScreenSize = size.ScreenSize;
pub const GridSize = size.GridSize;
... (40 lines truncated)
</file>

<file path="src/surface_mouse.zig">
/// SurfaceMouse represents mouse helper functionality for the core surface.
///
/// It's currently small in scope; its purpose is to isolate mouse logic that
/// has gotten a bit complex (e.g. pointer shape handling for key events), but
/// the intention is to grow it later so that we can better test said logic).
const SurfaceMouse = @This();

const std = @import("std");
const builtin = @import("builtin");
const input = @import("input.zig");
const terminal = @import("terminal/main.zig");
const MouseShape = terminal.MouseShape;

/// For processing key events; the key that was physically pressed on the
/// keyboard.
physical_key: input.Key,

/// The mouse event tracking mode, if any.
mouse_event: terminal.MouseEvent,

/// The current terminal's mouse shape.
mouse_shape: MouseShape,

/// The last mods state when the last mouse button (whatever it was) was
/// pressed or release.
mods: input.Mods,

/// True if the mouse position is currently over a link.
over_link: bool,

... (268 lines truncated)
</file>

<file path="src/Surface.zig">
//! Surface represents a single terminal "surface". A terminal surface is
//! a minimal "widget" where the terminal is drawn and responds to events
//! such as keyboard and mouse. Each surface also creates and owns its pty
//! session.
//!
//! The word "surface" is used because it is left to the higher level
//! application runtime to determine if the surface is a window, a tab,
//! a split, a preview pane in a larger window, etc. This struct doesn't care:
//! it just draws and responds to events. The events come from the application
//! runtime so the runtime can determine when and how those are delivered
//! (i.e. with focus, without focus, and so on).
const Surface = @This();

const apprt = @import("apprt.zig");
pub const Mailbox = apprt.surface.Mailbox;
pub const Message = apprt.surface.Message;

const std = @import("std");
const builtin = @import("builtin");
const assert = @import("quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const global = @import("global.zig");
const oni = @import("oniguruma");
const simd = @import("simd/main.zig");
const crash = @import("crash/main.zig");
const unicode = @import("unicode/main.zig");
const rendererpkg = @import("renderer.zig");
const termio = @import("termio.zig");
const font = @import("font/main.zig");
... (6662 lines truncated)
</file>

<file path="src/termio.zig">
//! Termio is responsible for "terminal IO." Specifically, this is the
//! reading and writing of bytes for the underlying pty or pty-like device.
//!
//! Termio is constructed of a few components:
//!   - Termio - The main shared struct that has common logic across all
//!     backends and mailboxes (defined below).
//!   - Backend - Responsible for the actual physical IO. For example, one
//!     implementation creates a subprocess, allocates and assigns a pty,
//!     and sets up a read thread on the pty.
//!   - Mailbox - Responsible for storing/dispensing event messages to
//!     the backend. This exists separately from backends because termio
//!     is built to be both single and multi-threaded.
//!
//! Termio supports (and recommends) multi-threaded operation. Multi-threading
//! enables the read/writes to generally happen on separate threads and
//! almost always improves throughput and latency under heavy IO load. To
//! enable threading, use the Thread struct. This wraps a Termio, requires
//! specific backend/mailbox capabilities, and sets up the necessary threads.

const stream_handler = @import("termio/stream_handler.zig");

const message = @import("termio/message.zig");
pub const backend = @import("termio/backend.zig");
pub const mailbox = @import("termio/mailbox.zig");
pub const Exec = @import("termio/Exec.zig");
pub const Options = @import("termio/Options.zig");
pub const Termio = @import("termio/Termio.zig");
pub const Thread = @import("termio/Thread.zig");
pub const Backend = backend.Backend;
pub const DerivedConfig = Termio.DerivedConfig;
... (10 lines truncated)
</file>

<file path="src/tripwire.zig">
//! A library for injecting failures into Zig code for the express
//! purpose of testing error handling paths.
//!
//! Improper `errdefer` is one of the highest sources of bugs in Zig code.
//! Many `errdefer` points are hard to exercise in unit tests and rare
//! to encounter in production, so they often hide bugs. Worse, error
//! scenarios are most likely to put your code in an unexpected state
//! that can result in future assertion failures or memory safety issues.
//!
//! This module aims to solve this problem by providing a way to inject
//! errors at specific points in your code during unit tests, allowing you
//! to test every possible error path.
//!
//! # Usage
//!
//! To use this package, create a `tripwire.module` for each failable
//! function you want to test. The enum must be hand-curated to be the
//! set of fail points, and the error set comes directly from the function
//! itself.
//!
//! Pepper your function with `try tw.check` calls wherever you want to
//! have a testable failure point. You don't need every "try" to have
//! an associated tripwire check, only the ones you care about testing.
//! Usually, this is going to be the points where you want to test
//! errdefer logic above it.
//!
//! In unit tests, add `try tw.errorAlways` or related calls to
//! configure expected failures. Then, call your function. Finally, always
//! call `try tw.end(.reset)` to verify your expectations were met and
//! to reset the tripwire module for future tests.
... (259 lines truncated)
</file>

<file path=".mailmap">
Mitchell Hashimoto <m@mitchellh.com> <mitchell.hashimoto@gmail.com>
Gregory Anders <greg@gpanders.com> <8965202+gpanders@users.noreply.github.com>
Jeffrey C. Ollie <jeff@ocjtech.us> <jcollie@dmacc.edu>
Kevin Hovsäter <kevin@hovsater.com> <kevin@hovsater.com>
Nathan Fisher <nfisher.sr@gmail.com> <jeang3nie@hitchhiker-linux.org>
Paul Berg <naydex.mc@gmail.com> <9824244+Pangoraw@users.noreply.github.com>
RGBCube <git@rgbcu.be> <RGBCube@users.noreply.github.com>
RGBCube <git@rgbcu.be> <78925721+RGBCube@users.noreply.github.com>
</file>

<file path=".shellcheckrc">
# ShellCheck <https://www.shellcheck.net/>
# https://github.com/koalaman/shellcheck/wiki/Directive#shellcheckrc-file

# Allow opening any 'source'd file, even if not specified as input
external-sources=true

# Assume bash by default
shell=bash
</file>

<file path="AGENTS.md">
# Agent Development Guide

A file for [guiding coding agents](https://agents.md/).

## Commands

- **Build:** `zig build`
  - If you're on macOS and don't need to build the macOS app, use
    `-Demit-macos-app=false` to skip building the app bundle and speed up
    compilation.
- **Test (Zig):** `zig build test`
  - Prefer to run targeted tests with `-Dtest-filter` because the full
    test suite is slow to run.
- **Test filter (Zig)**: `zig build test -Dtest-filter=<test name>`
- **Formatting (Zig)**: `zig fmt .`
- **Formatting (Swift)**: `swiftlint lint --strict --fix`
- **Formatting (other)**: `prettier -w .`

## libghostty-vt

- Build: `zig build -Demit-lib-vt`
- Build WASM: `zig build -Demit-lib-vt -Dtarget=wasm32-freestanding -Doptimize=ReleaseSmall`
- Test: `zig build test-lib-vt -Dtest-filter=<filter>`
  - Prefer this when the change is in a libghostty-vt file
- All C enums in `include/ghostty/vt/` must have a `_MAX_VALUE = GHOSTTY_ENUM_MAX_VALUE`
  sentinel as the last entry to force int enum sizing (pre-C23 portability).

## Directory Structure

- Shared Zig core: `src/`
... (10 lines truncated)
</file>

<file path="AI_POLICY.md">
# AI Usage Policy

The Ghostty project has strict rules for AI usage:

- **All AI usage in any form must be disclosed.** You must state
  the tool you used (e.g. Claude Code, Cursor, Amp) along with
  the extent that the work was AI-assisted.

- **The human-in-the-loop must fully understand all code.** If you
  can't explain what your changes do and how they interact with the
  greater system without the aid of AI tools, do not contribute
  to this project.

- **Issues and discussions can use AI assistance but must have a full
  human-in-the-loop.** This means that any content generated with AI
  must have been reviewed _and edited_ by a human before submission.
  AI is very good at being overly verbose and including noise that
  distracts from the main point. Humans must do their research and
  trim this down.

- **No AI-generated media is allowed (art, images, videos, audio, etc.).**
  Text and code are the only acceptable AI-generated content, per the
  other rules in this policy.

- **Bad AI drivers will be denounced** People who produce bad contributions
  that are clearly AI (slop) will be added to our public denouncement list.
  This list will block all future contributions. Additionally, the list
  is public and may be used by other projects to be aware of bad actors.
  We love to help junior developers learn and grow, but
  if you're interested in that then don't use AI, and we'll help you.
... (36 lines truncated)
</file>

<file path="build.zig">
const std = @import("std");
const assert = std.debug.assert;
const builtin = @import("builtin");
const buildpkg = @import("src/build/main.zig");
const translate_c = @import("translate_c");

/// App version from build.zig.zon.
const app_zon_version = @import("build.zig.zon").version;

/// Libghostty version. We use a separate version from the app.
const lib_version = "0.1.0-dev";

/// Minimum required zig version.
const minimum_zig_version = @import("build.zig.zon").minimum_zig_version;

comptime {
    buildpkg.requireZig(minimum_zig_version);
}

pub fn build(b: *std.Build) !void {
    // This defines all the available build options (e.g. `-D`). If you
    // want to know what options are available, you can run `--help` or
    // you can read `src/build/Config.zig`.

    // If we have a VERSION file (present in source tarballs) then we
    // use that as the version source of truth. Otherwise we fall back
    // to what is in the build.zig.zon.
    const file_version: ?[]const u8 = if (b.build_root.handle.readFileAlloc(
        b.graph.io,
        "VERSION",
... (420 lines truncated)
</file>

<file path="build.zig.zon">
.{
    .name = .ghostty,
    .version = "1.3.2-dev",
    .paths = .{""},
    .fingerprint = 0x64407a2a0b4147e5,
    .minimum_zig_version = "0.16.0",
    .dependencies = .{
        // Our higher-level C translation helper (this also helps ensure we
        // only need to maintain one external dependency point)
        .translate_c = .{ .path = "./pkg/translate-c" },

        // Zig libs
        .libxev = .{
            // mitchellh/libxev
            .url = "https://deps.files.ghostty.org/libxev-9ce8e8e6ff89e583258a7f8e7adeeeaeae8611bf.tar.gz",
            .hash = "libxev-0.0.0-86vtcwIRFADbH4hk-EjROXxlrKIRPQdA41XiTSytYO-F",
            .lazy = true,
        },
        .vaxis = .{
            // rockorager/libvaxis
            .url = "https://deps.files.ghostty.org/vaxis-1dbbe575dff4586fe51e3217aa5c3fecdcbb6089.tar.gz",
            .hash = "vaxis-0.6.0-BWNV_CrbCQCscGpzsAlR402rYQ_tV3aAl081c2iRRkka",
            .lazy = true,
        },
        .z2d = .{
            // vancluever/z2d
            .url = "https://deps.files.ghostty.org/z2d-7dbae85c81784dba9988320bf9543ed9a81350c8.tar.gz",
            .hash = "z2d-0.12.1-j5P_Hsw8EQAKyZTQICCQnAH2xYkLDW8k9uefbsYdfPZ-",
            .lazy = true,
        },
... (98 lines truncated)
</file>

<file path="build.zig.zon.json">
{
  "aro-0.0.0-JSD1Qk6lNgDdcDV4Vh7Sfy-34m2TluIVOdPzMmj_0BjX": {
    "name": "aro",
    "url": "https://github.com/vancluever/arocc/archive/f97cdfc3779aec4b242299e2fc9a1c828c3547c6.tar.gz",
    "hash": "sha256-G/NNgk7KhJSLdy17ip1igIzpYhAUlzO7ef8r3/iCv/s="
  },
  "N-V-__8AANT61wB--nJ95Gj_ctmzAtcjloZ__hRqNw5lC1Kr": {
    "name": "bindings",
    "url": "https://deps.files.ghostty.org/DearBindings_v0.17_ImGui_v1.92.5-docking.tar.gz",
    "hash": "sha256-i/7FAOAJJvZ5hT7iPWfMOS08MYFzPKRwRzhlHT9wuqM="
  },
  "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-__8AAOgqbADacob-q2_DMQlmgaG4xKHRuW-6PJ4oJzMZ": {
    "name": "fontconfig",
    "url": "https://gitlab.freedesktop.org/api/v4/projects/890/packages/generic/fontconfig/2.18.3/fontconfig-2.18.3.tar.xz",
    "hash": "sha256-T3tVSjjN94wDP2ZsiHHzdJ4UoJT2Wgf2MMke0LQ9NeM="
  },
  "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="
... (168 lines truncated)
</file>

<file path="build.zig.zon.txt">
git+https://github.com/jacobsandlund/uucode#2826a37a4562284fdacd8fa029d49509cc9bffcd
git+https://github.com/rockorager/libvaxis.git#c1e1f23be38951c425cdf31af455ba23ef178940
git+https://github.com/zigimg/zigimg#d695acd97c02e57bb151e8f659d1280f5cd6ca70
https://codeberg.org/vancluever/translate-c/archive/4e879eb8aba615de112eabd1231ea6e01920cead.tar.gz
https://deps.files.ghostty.org/DearBindings_v0.17_ImGui_v1.92.5-docking.tar.gz
https://deps.files.ghostty.org/JetBrainsMono-2.304.tar.gz
https://deps.files.ghostty.org/N-V-__8AAEbOfQBnvcFcCX2W5z7tDaN8vaNZGamEQtNOe0UI.tar.gz
https://deps.files.ghostty.org/N-V-__8AAFdWDwA0ktbNUi9pFBHCRN4weXIgIfCrVjfGxqgA.tar.gz
https://deps.files.ghostty.org/NerdFontsSymbolsOnly-3.4.0.tar.gz
https://deps.files.ghostty.org/breakpad-b99f444ba5f6b98cac261cbb391d8766b34a5918.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/ghostty-themes-release-20260928-151043-99d9701.tgz
https://deps.files.ghostty.org/glslang-12201278a1a05c0ce0b6eb6026c65cd3e9247aa041b1c260324bf29cee559dd23ba1.tar.gz
https://deps.files.ghostty.org/gobject-2026-07-28-36-1.tar.zst
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/libpng-1220aa013f0c83da3fb64ea6d327f9173fa008d10e28bc9349eac3463457723b1c66.tar.gz
https://deps.files.ghostty.org/libxev-9ce8e8e6ff89e583258a7f8e7adeeeaeae8611bf.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/vaxis-1dbbe575dff4586fe51e3217aa5c3fecdcbb6089.tar.gz
https://deps.files.ghostty.org/wayland-0.6.0-lQa1kqz8AQADQmdNJsNhLoNHcnEGEUjrOaPV-dtEnEmX.tar.gz
https://deps.files.ghostty.org/wayland-9cb3d7aa9dc995ffafdbdef7ab86a949d0fb0e7d.tar.gz
https://deps.files.ghostty.org/wayland-protocols-258d8f88f2c8c25a830c6316f87d23ce1a0f12d9.tar.gz
... (10 lines truncated)
</file>

<file path="CODEOWNERS">
# This file documents the subsystem maintainers of the Ghostty project
# along with the responsibilities of a maintainer and how one can become
# a maintainer.
#
# Ghostty follows a subsystem maintainer model where distinguished
# contributors (with mutual agreement) are designated as maintainers of a
# specific subset of the project. A subsystem maintainer has more privileges
# and authority over a specific part of the project than a regular
# contributor and deference is given to them when making decisions about
# their subsystem.
#
# Ultimately Ghostty has a BDFL (Benevolent Dictator For Life) model
# currently with @mitchellh as the BDFL. The BDFL has the final say in all
# decisions and may override a maintainer's decision if necessary. I like to
# say its a BDFLFN (Benevolent Dictator For Life "For Now") model because
# long term I'd like to see the project be more community driven. But for
# now, early in its life, we're going with this model.
#
# ## Privileges
#
#   - Authority to approve or reject pull requests in their subsystem.
#   - Authority to moderate issues and discussions in their subsystem.
#   - Authority to make roadmap and design decisions about their subsystem
#     with input only from other subsystem maintainers.
#
# In all scenarios, the BDFL doesn't need to be consulted for decisions
# but may revert or override decisions if necessary. The expectation is
# that maintainers will be trusted to make the right decisions for their
# subsystem and this will be rare.
#
... (175 lines truncated)
</file>

<file path="CONTRIBUTING.md">
# Contributing to Ghostty

This document describes the process of contributing to Ghostty. It is intended
for anyone considering opening an **issue**, **discussion** or **pull request**.
For people who are interested in developing Ghostty and technical details behind
it, please check out our ["Developing Ghostty"](HACKING.md) document as well.

> [!NOTE]
>
> I'm sorry for the wall of text. I'm not trying to be difficult and I do
> appreciate your contributions. Ghostty is a personal project for me that
> I maintain in my free time. If you're expecting me to dedicate my personal
> time to fixing bugs, maintaining features, and reviewing code, I do kindly
> ask you spend a few minutes reading this document. Thank you. ❤️

## The Critical Rule

**The most important rule: you must understand your code.** If you can't
explain what your changes do and how they interact with the greater system
without the aid of AI tools, do not contribute to this project.

Using AI to write code is fine. You can gain understanding by interrogating an
agent with access to the codebase until you grasp all edge cases and effects
of your changes. What's not fine is submitting agent-generated slop without
that understanding. Be sure to read the [AI Usage Policy](AI_POLICY.md).

## AI Usage

The Ghostty project has strict rules for AI usage. Please see
the [AI Usage Policy](AI_POLICY.md). **This is very important.**
... (166 lines truncated)
</file>

<file path="Doxyfile">
# Doxyfile 1.13.2

DOXYFILE_ENCODING      = UTF-8
PROJECT_NAME           = "libghostty"
PROJECT_LOGO           = images/gnome/64.png
INPUT                  = include/ghostty
INPUT_ENCODING         = UTF-8
RECURSIVE              = YES
FILE_PATTERNS          = *.h
EXAMPLE_PATH           = example
EXAMPLE_RECURSIVE      = YES
EXAMPLE_PATTERNS       = *
FULL_PATH_NAMES        = NO
STRIP_FROM_INC_PATH    = include
SOURCE_BROWSER         = YES
INLINE_SOURCES         = NO
REFERENCES_RELATION    = YES
REFERENCED_BY_RELATION = YES

#---------------------------------------------------------------------------
# Preprocessor
#---------------------------------------------------------------------------

# Enable preprocessing to handle #ifdef guards
ENABLE_PREPROCESSING   = YES
MACRO_EXPANSION        = YES
EXPAND_ONLY_PREDEF     = YES
PREDEFINED             = __wasm__

#---------------------------------------------------------------------------
... (64 lines truncated)
</file>

<file path="DoxygenLayout.xml">
<?xml version="1.0" encoding="UTF-8"?>
<doxygenlayout version="2.0">
  <navindex>
    <tab type="mainpage" visible="yes" title=""/>
    <tab type="pages" visible="yes" title="" intro=""/>
    <tab type="topics" visible="yes" title="" intro=""/>
    <tab type="modules" visible="yes" title="API Groups" intro="">
      <tab type="modulelist" visible="yes" title="" intro=""/>
      <tab type="modulemembers" visible="yes" title="" intro=""/>
    </tab>
    <tab type="structs" visible="yes" title="Data Types" intro="">
      <tab type="structlist" visible="yes" title="" intro=""/>
      <tab type="structindex" visible="$ALPHABETICAL_INDEX" title=""/>
    </tab>
    <tab type="files" visible="yes" title="C Headers" intro="">
      <tab type="filelist" visible="yes" title="" intro=""/>
      <tab type="globals" visible="yes" title="" intro=""/>
    </tab>
    <tab type="examples" visible="yes" title="" intro=""/>
  </navindex>
  <!-- Layout definition for a class page -->
  <class>
    <briefdescription visible="yes"/>
    <includes visible="$SHOW_HEADERFILE"/>
    <inheritancegraph visible="yes"/>
    <collaborationgraph visible="yes"/>
    <memberdecl>
      <nestedclasses visible="yes" title=""/>
      <publictypes visible="yes" title=""/>
      <services visible="yes" title=""/>
... (125 lines truncated)
</file>
  <!-- Layout definition for a group page -->
  <group>
    <briefdescription visible="yes"/>
    <detaileddescription visible="yes" title=""/>
    <memberdecl>
      <nestedgroups visible="yes" title=""/>
      <typedefs visible="yes" title=""/>
      <enums visible="yes" title=""/>
      <enumvalues visible="no" title=""/>
      <functions visible="yes" title=""/>
      <variables visible="yes" title=""/>
      <defines visible="yes" title=""/>
      <modules visible="yes" title=""/>
      <dirs visible="yes" title=""/>
      <files visible="yes" title=""/>
      <namespaces visible="yes" title=""/>
      <concepts visible="yes" title=""/>
      <classes visible="yes" title=""/>
      <sequences visible="yes" title=""/>
      <dictionaries visible="yes" title=""/>
      <signals visible="yes" title=""/>
      <publicslots visible="yes" title=""/>
      <protectedslots visible="yes" title=""/>
      <privateslots visible="yes" title=""/>
      <events visible="yes" title=""/>
      <properties visible="yes" title=""/>
      <friends visible="yes" title=""/>
      <membergroups visible="yes"/>
    </memberdecl>
    <memberdef>
      <pagedocs/>
      <inlineclasses visible="yes" title=""/>
      <typedefs visible="yes" title=""/>
      <enums visible="yes" title=""/>
      <enumvalues visible="yes" title=""/>
      <functions visible="yes" title=""/>
      <variables visible="yes" title=""/>
      <defines visible="yes" title=""/>
      <sequences visible="yes" title=""/>
      <dictionaries visible="yes" title=""/>
      <signals visible="yes" title=""/>
      <publicslots visible="yes" title=""/>
      <protectedslots visible="yes" title=""/>
      <privateslots visible="yes" title=""/>
      <events visible="yes" title=""/>
      <properties visible="yes" title=""/>
      <friends visible="yes" title=""/>
    </memberdef>
    <groupgraph visible="yes"/>
    <authorsection visible="yes"/>
  </group>
  <module>
    <briefdescription visible="yes"/>
    <exportedmodules visible="yes"/>
    <memberdecl>
      <concepts visible="yes" title=""/>
      <classes visible="yes" title=""/>
      <enums visible="yes" title=""/>
      <typedefs visible="yes" title=""/>
      <functions visible="yes" title=""/>
      <variables visible="yes" title=""/>
      <membergroups visible="yes" title=""/>
    </memberdecl>
    <detaileddescription visible="yes" title=""/>
    <memberdecl>
      <files visible="yes"/>
    </memberdecl>
  </module>
  <directory>
    <briefdescription visible="yes"/>
    <directorygraph visible="yes"/>
    <memberdecl>
      <dirs visible="yes"/>
      <files visible="yes"/>
    </memberdecl>
    <detaileddescription visible="yes" title=""/>
  </directory>
</doxygenlayout>
</file>

<file path="HACKING.md">
# Developing Ghostty

This document describes the technical details behind Ghostty's development.
If you'd like to open any pull requests or would like to implement new features
into Ghostty, please make sure to read our ["Contributing to Ghostty"](CONTRIBUTING.md)
document first.

To start development on Ghostty, you need to build Ghostty from a Git checkout,
which is very similar in process to [building Ghostty from a source tarball](http://ghostty.org/docs/install/build). One key difference is that obviously
you need to clone the Git repository instead of unpacking the source tarball:

```shell
git clone https://github.com/ghostty-org/ghostty
cd ghostty
```

> [!NOTE]
>
> Ghostty may require [extra dependencies](#extra-dependencies)
> when building from a Git checkout compared to a source tarball.
> Tip versions may also require a different version of Zig or other toolchains
> (e.g. the Xcode SDK on macOS) compared to stable versions — make sure to
> follow the steps closely!

When you're developing Ghostty, it's very likely that you will want to build a
_debug_ build to diagnose issues more easily. This is already the default for
Zig builds, so simply run `zig build` **without any `-Doptimize` flags**.

There are many more build steps than just `zig build`, some of which are listed
here:
... (458 lines truncated)
</file>

<file path="LICENSE">
MIT License

Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors

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.
</file>

<file path="Makefile">
init:
	@echo You probably want to run "zig build" instead.
.PHONY: init

# glad updates the GLAD loader. To use this, place the generated glad.zip
# in this directory next to the Makefile, remove vendor/glad and run this target.
#
# Generator: https://gen.glad.sh/
glad: vendor/glad
.PHONY: glad

vendor/glad: vendor/glad/include/glad/gl.h vendor/glad/include/glad/glad.h

vendor/glad/include/glad/gl.h: glad.zip
	rm -rf vendor/glad
	mkdir -p vendor/glad
	unzip glad.zip -dvendor/glad
	find vendor/glad -type f -exec touch '{}' +

vendor/glad/include/glad/glad.h: vendor/glad/include/glad/gl.h
	@echo "#include <glad/gl.h>" > $@

clean:
	rm -rf \
		zig-out .zig-cache \
		macos/build \
		macos/GhosttyKit.xcframework
.PHONY: clean
</file>

<file path="PACKAGING.md">
# Packaging Ghostty for Distribution

Ghostty relies on downstream package maintainers to distribute Ghostty to
end-users. This document provides guidance to package maintainers on how to
package Ghostty for distribution.

> [!IMPORTANT]
>
> This document is only accurate for the Ghostty source alongside it.
> **Do not use this document for older or newer versions of Ghostty!** If
> you are reading this document in a different version of Ghostty, please
> find the `PACKAGING.md` file alongside that version.

## Source Tarballs

Source tarballs with stable checksums are available for tagged releases
at `release.files.ghostty.org` in the following URL format where
`VERSION` is the version number with no prefix such as `1.0.0`:

```
https://release.files.ghostty.org/VERSION/ghostty-VERSION.tar.gz
https://release.files.ghostty.org/VERSION/ghostty-VERSION.tar.gz.minisig
```

Signature files are signed with
[minisign](https://jedisct1.github.io/minisign/)
using the following public key:

```
RWQlAjJC23149WL2sEpT/l0QKy7hMIFhYdQOFy0Z7z7PbneUgvlsnYcV
... (148 lines truncated)
</file>

<file path="passthrough.glsl">
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    fragColor = vec4(texture(iChannel0, uv).rgb, 1.0);
}
</file>

<file path="README.md">
<!-- LOGO -->
<h1>
<p align="center">
  <img src="https://github.com/user-attachments/assets/fe853809-ba8b-400b-83ab-a9a0da25be8a" alt="Logo" width="128">
  <br>Ghostty
</h1>
  <p align="center">
    Fast, native, feature-rich terminal emulator pushing modern features.
    <br />
    A native GUI or embeddable library via <code>libghostty</code>.
    <br />
    <a href="#about">About</a>
    ·
    <a href="https://ghostty.org/download">Download</a>
    ·
    <a href="https://ghostty.org/docs">Documentation</a>
    ·
    <a href="CONTRIBUTING.md">Contributing</a>
    ·
    <a href="HACKING.md">Developing</a>
  </p>
</p>

## About

Ghostty is a terminal emulator that differentiates itself by being
fast, feature-rich, and native. While there are many excellent terminal
emulators available, they all force you to choose between speed,
features, or native UIs. Ghostty provides all three.

... (197 lines truncated)
</file>

<file path="valgrind.supp">
# This Valgrind suppression file contains the suppressions necessary
# to run Ghostty with GTK under Valgrind. There may be some false suppressions
# here so we should scrutinize this file periodically.
#
# To run Ghostty under Valgrind:
#
#   valgrind \
#     --leak-check=full \
#     --num-callers=50 \
#     --suppressions=valgrind.supp \
#     ./zig-out/bin/ghostty
#
# You must gracefully exit Ghostty (do not SIGINT) by closing all windows
# and quitting. Otherwise, we leave a number of GTK resources around.

# Zig's DEFLATE encoder intentionally increments an undefined base[0] entry
# for unused Huffman symbols. The corresponding output code is also unused;
# see the comment in std.compress.flate.Compress.huffman.buildValues.
{
   Zig std DEFLATE unused Huffman code
   Memcheck:Cond
   fun:compress.flate.Compress.huffman.buildValues
}


# Reproduction: 
# 1. Launch Ghostty (no config)
# 2. Right Click on the terminal
# 3. Hover over "Split" to get a submenu
# 4. Close menu by clicking away
... (2421 lines truncated)
</file>

</files>
