Compare commits

..

96 Commits

Author SHA1 Message Date
Peter Tripp
3efbd3afa6 Maybe GITHUB_BASE_REF? 2024-09-30 22:57:03 -04:00
Peter Tripp
2e36aaf14b Renamed config option. 2024-09-30 22:06:48 -04:00
Peter Tripp
7b0a239db7 Disable linting. 2024-09-30 21:54:28 -04:00
Peter Tripp
375537b520 Merge branch 'main' into buf_action 2024-09-30 21:50:48 -04:00
Peter Tripp
fd47471ba6 Reformat proto. 2024-09-30 21:50:09 -04:00
Peter Tripp
1d2172aba8 docs: Correct glibc requirements (#18554) 2024-09-30 21:07:10 -04:00
Patrick MARIE
a752bbcee8 Fix linux double click (#18504)
Closes #17573

Release Notes:

- Check that double clicks on Linux are triggered by same button.
2024-09-30 16:51:05 -07:00
Jason Lee
938a0679c0 gpui: Fix img element to auto size when only have width or height (#17994)
Release Notes:

- N/A

---

We may only want to set the height of an image to limit the size and
make the width adaptive.

In HTML, we will only set width or height, and the other side will adapt
and maintain the original image ratio.

I changed this because I had a logo image that only to be limited in
height, and then I found that setting the height of the `img` alone
would not display correctly.

I also tried to set `ObjectFit` in this Demo, but it seems that none of
them can achieve the same effect as "After".

## Before
<img width="809" alt="before 2024-09-18 164029"
src="https://github.com/user-attachments/assets/7ba559ed-e53b-43e6-a072-93c8ba5b14ee">

## After
<img width="749" alt="after 2024-09-18 172003"
src="https://github.com/user-attachments/assets/51ee2eba-76b3-400a-abbf-de0e9c4021e2">
2024-09-30 16:39:19 -07:00
Junkui Zhang
77506afd83 windows: Implement copy/paste images (#17852)
**Clipboard Behavior on Windows Under This PR:**

| User Action | Zed’s Behavior |
| ------------------- |
-------------------------------------------------- |
| Paste PNG | Worked |
| Paste JPEG | Worked |
| Paste WebP | Worked, but not in the way you expect (see Issue section
below) |
| Paste GIF | Partially worked (see Issue section below) |
| Paste SVG | Partially worked (see Issue section below) |
| Paste BMP | Worked, but not in the way you expect (see Issue section
below) |
| Paste TIFF | Worked, but not in the way you expect (see Issue section
below) |
| Paste Files         | Worked, same behavior as macOS              |
| Copy image in Zed | Not tested, as I couldn’t find a way to copy
images |

---

**Differences Between the Windows and macOS Clipboard**

The clipboard functionality on Windows differs significantly from macOS.
On macOS, there can be multiple items in the clipboard, whereas, on
Windows, the clipboard holds only a single item. You can retrieve
different formats from the clipboard, but they are all just different
representations of the same item.

For example, when you copy a JPG image from Microsoft Word, the
clipboard will contain data in several formats:

- Microsoft Office proprietary data
- JPG format data
- PNG format data
- SVG format data

Please note that these formats all represent the same image, just in
different formats. This is due to compatibility concerns on Windows, as
various applications support different formats. Ideally, multiple
formats should be placed on the clipboard to support more software.
However, in general, supporting PNG will cover 99% of software, like
Chrome, which only supports PNG and BMP formats.

Additionally, since the clipboard on Windows only contains a single
item, special handling is required when copying multiple objects, such
as text and images. For instance, if you copy both text and an image
simultaneously in Microsoft Word, Microsoft places the following data on
the clipboard:

- Microsoft Office proprietary data containing a lot of content such as
text fonts, sizes, italics, positioning, image size, content, etc.
- RTF data representing the above content in RTF format
- HTML data representing the content in HTML format
- Plain text data

Therefore, for the current `ClipboardItem` implementation, if there are
multiple `ClipboardEntry` objects to be placed on the clipboard, RTF or
HTML formats are required. This PR does not support this scenario, and
only supports copying or pasting a single item from the clipboard.

---

**Known Issues**

- **WebP, BMP, TIFF**: These formats are not explicitly supported in
this PR. However, as mentioned earlier, in most cases, there are
corresponding PNG format data on the clipboard. This PR retrieves data
via PNG format, so users copying images in these formats from other
sources will still see the images displayed correctly.
  
- **GIF**: In this PR, GIFs are displayed, but for GIF images with
multiple frames, the image will not animate and will freeze on a single
frame. Since I observed the same behavior on macOS, I believe this is
not an issue with this PR.

- **SVG**: In this PR, only the top-left corner of the SVG image is
displayed. Again, I observed the same behavior on macOS, so I believe
this issue is not specific to this PR.

--- 

I hope this provides a clearer understanding. Any feedback or
suggestions on how to improve this are welcome.

Release Notes:

- N/A
2024-09-30 16:29:23 -07:00
Junkui Zhang
ecb7144b95 windows: Fix can not set folder for FileSaveDialog (#17708)
Closes #17622
Closes #17682

The story here is that `SHCreateItemFromParsingName` dose not accept UNC
path.

Video:



https://github.com/user-attachments/assets/f4f7f671-5ab5-4965-9158-e7a79ac02654



Release Notes:

- N/A
2024-09-30 16:26:20 -07:00
maan2003
837756198f linux/wayland: Add support for pasting images (#17671)
Release Notes:

- You can now paste images into the Assistant Panel to include them as
context on Linux wayland
2024-09-30 16:25:32 -07:00
Andrey Arutiunian
eb9fd62a90 Fix rendering of markdown tables (#18315)
- Closes: https://github.com/zed-industries/zed/issues/11024

## Release Notes:

- Improved Markdown Preview rendering of tables

## Before:


![image](https://github.com/user-attachments/assets/25f05604-38a9-4bde-901c-6d53a5d9d94d)

<img width="2035" alt="Screenshot 2024-09-25 at 05 47 19"
src="https://github.com/user-attachments/assets/a30c56f5-4793-44c2-8527-294189f9e724">

## Now:


![image](https://github.com/user-attachments/assets/ce06f045-d0db-4b8c-a1fc-2811d35f2683)


<img width="2040" alt="Screenshot 2024-09-25 at 05 47 48"
src="https://github.com/user-attachments/assets/76e5d217-9110-4c5d-9fad-dc63ae0b75f4">

## Note:

I'm not a Rust programmer and this is my first PR in Zed (because i just
want to fix this, so i can view my notes in Markdown in Zed, not slow
Visual Studio Code) - so there may be errors. I'm open for critic a
2024-09-30 15:50:30 -07:00
Peter Tripp
3010dfe038 Support More Linux (#18480)
- Add `script/build-docker`
- Add `script/install-cmake`
- Add `script/install-mold`
- Improve `script/linux` 
  - Add missing dependencies: `jq`, `git`, `tar`, `gzip` as required.
  - Add check for mold
  - Fix Redhat 8.x derivatives (RHEL, Centos, Almalinux, Rocky, Oracle, Amazon)
  - Fix perl libs to be Fedora only
  - Install the best `libstdc++` available on apt distros
  - ArchLinux: run `pacman -Syu` to update repos before installing. 
  - Should work on Raspbian (untested) 

This make it possible to test builds on other distros using docker:
```
./script/build-docker amazonlinux:2023
```
2024-09-30 17:46:21 -04:00
Peter Tripp
432de00e89 ci: Use BuildJet Ubuntu 20.04 runners for better glibc compatibility (#18442)
Use BuildJet Ubuntu 20.04 runners.
- Linux arm64 unchanged (glibc >= 2.35)
- Linux x64 glibc requirement becomes to >= 2.31 (from glibc >= 2.35).

Note: Ubuntu 20.04 repo cmake (3.16.3) is normally too old to build Zed, but `ubuntu-2004` [includes cmake
3.30.3](https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2004-Readme.md#tools).
2024-09-30 17:02:19 -04:00
Peter Tripp
09424edc35 ci: Add script/determine-release-channel (#18476)
- Refactor duplicated inline script from ci.yml to
`script/determine-release-channel`
- Remove references to non-existent '-nightly' release tags

Release Notes:

- N/A
2024-09-30 16:17:21 -04:00
Peter Tripp
74cba2407f ci: Move collab to Dockerfile-collab (#18515)
This makes it possible to have multiple Dockerfiles, each with their own
`.dockerignore`. Previously any docker builds would always include
anything inside `.dockerignore`. I believe this feature may require
`export DOCKER_BUILDKIT=1` but we use that in CI already.
2024-09-30 16:14:26 -04:00
Danilo Leal
053e31994f Fine-tune hunk controls block (#18543)
This PR changes the undo icon and adds a background color so that indent
lines don't bleed through the control block.

<img width="900" alt="Screenshot 2024-09-30 at 5 38 44 PM"
src="https://github.com/user-attachments/assets/4955f0f6-50ce-432f-85b9-1da0172d5e51">

Release Notes:

- N/A
2024-09-30 13:33:20 -03:00
Thorsten Ball
69e698c3be terminal: Fix blinking settings & blinking with custom shape (#18538)
This is a follow-up to #18530 thanks to this comment here:
https://github.com/zed-industries/zed/pull/18530#issuecomment-2382870564

In short: it fixes the `blinking` setting and the `cursor_shape` setting
as it relates to blinking.

Turns out our `blinking` setting was always the wrong value when using
`terminal_controlled` and the terminal _would_ control the blinking.

Example script to test with:

```bash
echo -e "0 normal \x1b[\x30 q"; sleep 2
echo -e "1 blink block \x1b[\x31 q"; sleep 2
echo -e "2 solid block \x1b[\x32 q"; sleep 2
echo -e "3 blink under \x1b[\x33 q"; sleep 2
echo -e "4 solid under \x1b[\x34 q"; sleep 2
echo -e "5 blink vert \x1b[\x35 q"; sleep 2
echo -e "6 solid vert \x1b[\x36 q"; sleep 2
echo -e "0 normal \x1b[\x30 q"; sleep 2

echo -e "color \x1b]12;#00ff00\x1b\\"; sleep 2
echo -e "reset \x1b]112\x1b\\ \x1b[\x30 q"
```

Before the changes in here, this script would set the cursor shape and
the blinking, but the blinking boolean would always be wrong.

This change here makes sure that it works consistently:

- `terminal.cursor_shape` only controls the *default* shape of the
terminal, not the blinking.
- `terminal.blinking = on` means that it's *always* blinking, regardless
of what terminal programs want
- `terminal.blinking = off` means that it's *never* blinking, regardless
of what terminal programs want
- `terminal.blinking = terminal_controlled (default)` means that it's
blinking depending on what terminal programs want. when a terminal
program resets the cursor to default, it sets it back to
`terminal.cursor_shape` if that is set.

Release Notes:

- Fixed the behavior of `{"terminal": {"blinking":
"[on|off|terminal_controlled]"}` to work correctly and to work correctly
when custom `cursor_shape` is set.
- `terminal.cursor_shape` only controls the *default* shape of the
terminal, not the blinking.
- `terminal.blinking = on` means that it's *always* blinking, regardless
of what terminal programs want
- `terminal.blinking = off` means that it's *never* blinking, regardless
of what terminal programs want
- `terminal.blinking = terminal_controlled (default)` means that it's
blinking depending on what terminal programs want. when a terminal
program resets the cursor to default, it sets it back to
`terminal.cursor_shape` if that is set.

Demo:


https://github.com/user-attachments/assets/b3fbeafd-ad58-41c8-9c07-1f03bc31771f

Co-authored-by: Bennet <bennet@zed.dev>
2024-09-30 15:36:35 +02:00
Stanislav Alekseev
215bce1974 Make direct direnv loading default (#18536)
I've been running with direct direnv loading for a while now and haven't
experienced any significant issues other than #18473. Making it default
would make direnv integration more reliable and consistent. I've also
updated the docs a bit to ensure that they represent current status of
direnv integration

Release Notes:

- Made direnv integration use direct (`direnv export json`) mode by
default instead of relying on a shell hook, improving consistency and
reliability of direnv detection
2024-09-30 15:35:36 +02:00
Kirill Bulatov
e64a86ce9f Fix a typo in the multi buffers documentation (#18535)
Closes https://github.com/zed-industries/zed/issues/18533

Release Notes:

- N/A
2024-09-30 15:28:46 +03:00
wannacu
8ae74bc6df gpui: Fix pre-edit position after applying scale factor (#18214)
before:

![image](https://github.com/user-attachments/assets/20590089-3333-4ca8-a371-b07acfbe43f9)

after:

![image](https://github.com/user-attachments/assets/2d25623e-0602-4d24-b563-64e1d2ec3492)

Release Notes:

- N/A
2024-09-30 12:57:59 +02:00
Thorsten Ball
65f6a7e5bc linux/x11: Give title bar inactive bg on mouse down (#18529)
This fixes something that I felt was off for a while. Previously, when
you'd click on the titlebar to move the window, the titlebar would only
change its background once the moving starts, but not on mouse-down.

That felt really off, since the moving is down with mouse-down and move,
so I think giving the user feedback about the mouse-down event makes
more sense.

I know there's a subjectivity to this change, so I'm ready to hear other
opinions, but for now I want to go with this.

Release Notes:

- N/A
2024-09-30 12:39:11 +02:00
Thorsten Ball
533416c5a9 terminal: Make CursorShape configurable (#18530)
This builds on top of @Yevgen's #15840 and combines it with the settings
names introduced in #17572.

Closes #4731.

Release Notes:

- Added a setting for the terminal's default cursor shape. The setting
is `{"terminal": {"cursor_shape": "block"}}``. Possible values: `block`,
`bar`, `hollow`, `underline`.

Demo:


https://github.com/user-attachments/assets/96ed28c2-c222-436b-80cb-7cd63eeb47dd
2024-09-30 12:38:57 +02:00
0hDEADBEAF
57ad5778fa Add a way to explicitly specify RC toolkit path (#18402)
Closes #18393 

Release Notes:

- Added a `ZED_RC_TOOLKIT_PATH` env variable so `winresource` crate can fetch the RC executable path correctly on some configurations
2024-09-30 11:34:44 +03:00
Patrick MARIE
707ccb04d2 Restore paste on middle-click on linux (#18503)
This is a partial revert of e6c1c51b37, which removed the middle-click
pasting on linux (both x11 & wayland). It also restores the
`middle_click_paste` option behavior which became unexistent.

Release Notes:

- Restore Linux middle-click pasting.
2024-09-30 10:27:47 +02:00
VacheDesNeiges
1f72069b42 Improve C++ Tree-sitter queries (#18016)
I made a few tree-sitter queries for improving the highlighting of C++. 

There is one query that I'm not totally certain about and would
appreciate some feedback on it, the one that concerns attributes.

Many editor only highlight the identifier as a keyword (This is the
behavior implemented in this commit), while others, for example the
tree-sitter plugin for neovim, tags the entire attribute for
highlighting (double brackets included). I don't know which one is
preferable. Here are screenshots of the two versions:


![image](https://github.com/user-attachments/assets/4e1b92c8-adc7-4900-a5b1-dc43c98f4c67)


![image](https://github.com/user-attachments/assets/290a13e3-5cb3-45cb-b6d9-3dc3e6a8af2d)


Release Notes:


- Fixed C++ attributes identifiers being wrongly highlighed through the
tag "variable"
- C++ attribute identifiers (nodiscard,deprecated, noreturn, etc.. ) are
now highlighted through the tag "keyword"
- Changed C++ primitives types (void, bool, int, size_t, etc.. ) to no
longer be highlighted with the tag "keyword", they can now be
highlighted by the tag "type.primitive".
- Added a tag "concept" for highlighting C++ concept identifiers. (This
tag name has been chosen to be the same than the one returned by
clangd's semantic tokens)
2024-09-30 10:27:30 +02:00
Kirill Bulatov
ed5eb725f9 Improve language server log view split ergonomics (#18527)
Allows to split log view, and opens it split on the right, same as the
syntax tree view.

Release Notes:

- Improved language server log panel split ergonomics
2024-09-30 11:25:11 +03:00
jansol
3fafdeb1a8 gpui: Fix blur region on Plasma/Wayland (#18465)
Once again aping after what winit does - since we always want to have
the whole window blurred there is apparently no need to specify a blur
region at all. Rounded corners would be the exception, but that is not
possible with the current protocol (it is planned for the vendor-neutral
version though!)

This eliminates the problem where only a fixed region of the window
would get blurred if the window was resized to be larger than at launch.
Also a drive-by comment grammar fix 😉

Release Notes:

- Fixed blur region handling on Plasma/Wayland
2024-09-30 10:09:13 +03:00
Sylvain Brunerie
898d48a574 php: Add syntax highlighting inside heredoc strings (#18368)
PHP heredoc strings make it easy to define string literals over multiple
lines:

```php
    $someString = <<<EOT
        multiline
        text
        EOT;
```

That `EOT` identifier can be anything else, and it is actually being
used in Sublime Text and VS Code to inject syntax highlighting for
another language in said string, depending on the identifier. For
instance, if the identifier is SQL, SQL syntax highlighting will be
applied to the contents of the string. Likewise if the identifier is CSS
or JS.

```php
    $someString = <<<SQL
        SELECT *
        FROM my_table
        SQL;
```

This PR changes the PHP extension so that it supports that feature too.

Release Notes:

- php: Added syntax highlighting inside heredoc strings
2024-09-30 10:02:12 +03:00
Stanislav Alekseev
5b40debb5f Don't stop loading the env if direnv call fails (#18473)
Before this we we would stop loading the environment if the call to
direnv failed, which is not necessary in any way
cc @mrnugget

Release Notes:

- Fixed the environment not loading if `direnv` mode is set to `direct`
and `.envrc` is not allowed
2024-09-30 09:54:22 +03:00
Maksim Bondarenkov
e39695bf1c docs: Update msys2 section in development/windows (#18385)
merge after
https://packages.msys2.org/packages/mingw-w64-clang-x86_64-zed is
available. alternatively you can check the
[queue](https://packages.msys2.org/queue) for build status

Zed now compiles and runs under msys2/CLANG64 environment, so change the
docs to give the users a choice of their environment

Release Notes:

- N/A
2024-09-30 09:38:49 +03:00
Tom Wieczorek
77df7e56f7 settings: Make external formatter arguments optional (#18340)
If specifying a formatter in the settings like this:

    "languages": {
      "foo": {
        "formatter": {
          "external": {
            "command": "/path/to/foo-formatter"
          }
        }
      }
    }

Zed will show an error like this:

    Invalid user settings file
    data did not match any variant of untagged enum SingleOrVec

This is because the arguments are not optional. The error is hard to
understand, so let's make the arguments actually optional, which makes
the above settings snippet valid.

Release Notes:

- Make external formatter arguments optional
2024-09-30 09:34:41 +03:00
Piotr Osiewicz
250f2e76eb tasks: Display runnables at the start of folds (#18526)
Release Notes:

- Fixed task indicators not showing up at the starts of folds.
2024-09-30 08:05:51 +02:00
Thorben Kröger
5f35fa5d92 Associate uv.lock files with TOML (#18426)
The `uv` python package manager uses the TOML for it's `uv.lock` file,
see https://docs.astral.sh/uv/guides/projects/#uvlock.

Ref #7808

Release Notes:

- associate `uv.lock` files with the TOML language
2024-09-29 13:54:09 -04:00
Antonio Scandurra
84ce81caf1 Pass Summary::Context to Item::summarize (#18510)
We are going to use this in the multi-buffer to produce a summary for an
`Excerpt` that contains a `Range<Anchor>`.

Release Notes:

- N/A

Co-authored-by: Nathan <nathan@zed.dev>
2024-09-29 10:30:48 -06:00
Joseph T. Lyons
8aeab4800c Continue to redirect to GitHub commits for nightly and dev release notes (#18487)
We are now using the `view release notes locally` action when clicking
on the update toast - the endpoint for this action does not currently
return anything for valid for these channels, as we don't have support
yet for diffing between these builds, so for now, [continue to do what
the `view release notes` action did and just send the user to the commit
view on
GitHub](caffb2733f/crates/auto_update/src/auto_update.rs (L255-L260)).
It is a bit counterintuitive to send the user to the browser when using
the "local" action, but this is just a patch in the interim.

If we make adjustments to our channels to keep the nightly tag stable
and add some sort of unique suffix, like a timestamp, we can then adjust
things to return these in the request body and show them in the editor.

Release Notes:

- N/A
2024-09-28 15:20:32 -04:00
Joseph T. Lyons
1021f0e288 Show release notes locally when showing update notification (#18486)
Closes https://github.com/zed-industries/zed/issues/17527

I think we are ok to switch to using the local action now. There are a
few things we don't support, like media, but we don't include media
directly too often, and I think this might help push the community to
maybe add support for it. That being said, I updated the markdown coming
back from the endpoint to include links to the web version of the
release notes, so they can always hop over to that version, if they
would like.


https://github.com/user-attachments/assets/b4d207a7-1640-48f1-91d0-94537f74116c

All forming of the Markdown happens in the endpoint, so if someone with
a better eye wants to update this, you can do that here:


0e5923e3e7/src/pages/api/release_notes/v2/%5Bchannel_type%5D/%5Bversion%5D.ts (L50-L62)

Release Notes:

- Changed the `view the release notes` button in the update toast to
trigger the local release notes action.
2024-09-28 14:21:13 -04:00
Danilo Leal
675673ed54 Fine-tune hunk control spacing (#18463)
<img width="900" alt="Screenshot 2024-09-28 at 1 09 35 AM"
src="https://github.com/user-attachments/assets/0b9d744f-3b92-488a-bc74-987f5a9d8c6c">

---

Release Notes:

- N/A
2024-09-28 01:45:40 +02:00
Danilo Leal
3737d4eb4f Add tooltip for code actions icon button (#18461)
I have just recently discovered this keybinding myself out of talking to
folks, ha. The tooltip here might ease the discovery for other folks in
the future.

<img width="700" alt="Screenshot 2024-09-27 at 11 04 28 PM"
src="https://github.com/user-attachments/assets/844d3b55-15af-47f7-a8db-5c8832ceba29">

---

Release Notes:

- N/A
2024-09-27 18:25:02 -03:00
Max Brunsfeld
0daa070448 More git hunk highlighting fixes (#18459)
Follow-up to https://github.com/zed-industries/zed/pull/18454

Release Notes:

- N/A
2024-09-27 13:48:37 -07:00
Max Brunsfeld
689da9d0b1 Move git hunk controls to the left side (#18460)
![Screenshot 2024-09-27 at 1 05
14 PM](https://github.com/user-attachments/assets/260a7d05-daa8-4a22-92bc-3b956035227f)

Release Notes:

- N/A
2024-09-27 13:13:55 -07:00
Danilo Leal
1c5be9de4e Capitalize tooltip labels on buffer search (#18458)
For consistency, as this seems to be the pattern we're using overall for
labels and buttons.

---

Release Notes:

- N/A
2024-09-27 17:02:32 -03:00
Kirill Bulatov
d5f67406b0 Install cargo-edito without extra features (#18457)
https://github.com/killercup/cargo-edit/pull/907 removed the feature
from the crate

Release Notes:

- N/A
2024-09-27 22:42:04 +03:00
Max Brunsfeld
c3075dfe9a Fix bugs in diff hunk highlighting (#18454)
Fixes https://github.com/zed-industries/zed/issues/18405

In https://github.com/zed-industries/zed/pull/18313, we introduced a
problem where git addition highlights might spuriously return when
undoing certain changes. It turned out, there were already some cases
where git hunk highlighting was incorrect when editing at the boundaries
of expanded diff hunks.

In this PR, I've introduced a test helper method for more rigorously
(and readably) testing the editor's git state. You can assert about the
entire state of an editor's diff decorations using a formatted diff:

```rust
    cx.assert_diff_hunks(
        r#"
        - use some::mod1;
          use some::mod2;
          const A: u32 = 42;
        - const B: u32 = 42;
          const C: u32 = 42;
          fn main() {
        -     println!("hello");
        +     //println!("hello");
              println!("world");
        +     //
        +     //
          }
          fn another() {
              println!("another");
        +     println!("another");
          }
        - fn another2() {
              println!("another2");
          }
        "#
        .unindent(),
    );
```

This will assert about the editor's actual row highlights, not just the
editor's internal hunk-tracking state.

I rewrote all of our editor diff tests to use these more high-level
assertions, and it caught the new bug, as well as some pre-existing bugs
in the highlighting of added content.

The problem was how we *remove* highlighted rows. Previously, it relied
on supplying exactly the same range as one that we had previously
highlighted. I've added a `remove_highlighted_rows(ranges)` APIs which
is much simpler - it clears out any row ranges that intersect the given
ranges (which is all that we need for the Git diff use case).

Release Notes:

- N/A
2024-09-27 11:14:28 -07:00
Richard Feldman
caaa9a00a9 Remove Qwen2 model (#18444)
Removed deprecated Qwen2 7B Instruct model from zed.dev provider (staff
only).

Release Notes:

- N/A
2024-09-27 13:30:25 -04:00
Conrad Irwin
ffd1083cc1 vim: Command selection fixes (#18424)
Release Notes:

- vim: Fixed cursor position after `:{range}yank`.
- vim: Added `:fo[ld]`, `:foldo[pen]` and `:foldc[lose]`
2024-09-27 10:06:19 -06:00
Joseph T. Lyons
6d4ecac610 Add a get-release-notes-since script (#18445)
Release Notes:

- N/A
2024-09-27 10:59:19 -04:00
Ömer Sinan Ağacan
dc5ffe6994 Fix GoToDefinition changing the viewport unnecessarily (#18441)
Closes #10738.

Release Notes:

- Fixed `GoToDefinition` changing the viewport (scrolling up/down) even when the definition is already within the viewport. ([#10738](https://github.com/zed-industries/zed/issues/10738))
2024-09-27 17:55:03 +03:00
Peter Tripp
03c7f08581 docs: Ollama api_url improvements (#18440) 2024-09-27 10:29:49 -04:00
Bennet Bo Fenner
73ff8c0f1f Fix missing tooltips for selected buttons (#18435)
Reverts #13857. Hiding tooltips for selected buttons prevents tooltips
like "Close x dock" from showing up, see #14938 for an example.
The intention of the original PR was to hide the "Show application menu"
tooltip, while the context menu is open.
In order to fix this without breaking other UI elements, we track the
state of the context menu using `PopoverMenuHandle` now, which allows us
to prevent the tooltip from showing up while the context menu is open.

Closes #14938

Release Notes:

- Fixed an issue where some tooltips would not show up
2024-09-27 14:16:14 +02:00
Bennet Bo Fenner
1c5d9c221a Add missing shortcuts in tooltips (#18282)
Fixes some missing shortcuts from Tooltips like the project search,
buffer search, quick action bar, ....


https://github.com/user-attachments/assets/d3a0160a-8d6e-4ddc-bf82-1fabeca42d59

This should hopefully help new users learn and discover some nice
keyboard shortcuts

Release Notes:

- Display keyboard shortcuts inside tooltips in the project search,
buffer search etc.
2024-09-27 11:06:48 +02:00
Bennet Bo Fenner
a1d2e1106e assistant: Fix copy/cut not working when selection is empty (#18403)
Release Notes:

- Fixed copy/cut/paste not working in the assistant panel when selection
was empty
2024-09-27 10:51:49 +02:00
Kirill Bulatov
568a21a700 Fix the numeration in line wrap docs (#18428)
Follow-up of https://github.com/zed-industries/zed/pull/18412

Release Notes:

- N/A

Co-authored-by: Thorsten Ball <thorsten@zed.dev>
2024-09-27 10:48:34 +03:00
Thorsten Ball
5199135b54 ssh remoting: Show error if opening connection timed out (#18401)
This shows an error if opening a connection to a remote host didn't work
in the timeout of 10s (maybe we'll need to make that configurable in the
future? for now it seems fine.)

![screenshot-2024-09-26-18 01
07@2x](https://github.com/user-attachments/assets/cbfa0e9f-9c29-4b6c-bade-07fdd7393c9d)


Release Notes:

- N/A

---------

Co-authored-by: Bennet <bennet@zed.dev>
Co-authored-by: Conrad <conrad@zed.dev>
2024-09-27 09:31:45 +02:00
CharlesChen0823
8559731e0d project: Fix worktree store event missing in remote projects (#18376)
Release Notes:

- N/A
2024-09-27 08:55:35 +02:00
Conrad Irwin
02d0561586 Fix read timeout for ollama (#18417)
Supercedes: #18310

Release Notes:

- Fixed `low_speed_timeout_in_seconds` for Ollama
2024-09-27 00:36:17 -06:00
Conrad Irwin
1be3c44550 vim: Support za (#18421)
Closes #6822
Updates #5142 

Release Notes:

- Added new fold actions to toggle folds (`cmd-k cmd-l`), fold every
fold (`cmd-k cmd-0`) unfold every fold (`cmd-k cmd-j`) to fold
recursively (`cmd-k cmd-[`) and unfold recursively (`cmd-k cmd-]`).
- vim: Added `za` to toggle fold under cursor.
- vim: Added `zO`/`zC`/`zA` to open, close and toggle folds recursively
(and fixed `zc` to not recurse into selections).
- vim: Added `zR`/`zM` to open/close all folds in the buffer.
2024-09-26 23:52:07 -06:00
Conrad Irwin
32605e9ea4 Fix register selection in visual mode (#18418)
Related to #12895

Release Notes:

- vim: Fix register selection in visual yank
2024-09-26 20:27:49 -06:00
Kirill Bulatov
c83d007138 Remove non-wrapping settings from the language configuration (#18412)
Closes https://github.com/zed-industries/zed/issues/17736

Those are limited with 1024 symbols before wrapping still, and were
introduced for git diff deleted hunks display.
Instead of confusing people with actually wrapping, restores behavior
that was before https://github.com/zed-industries/zed/pull/11080

Release Notes:

- Removed confusing soft wrap option behavior
([#17736]https://github.com/zed-industries/zed/issues/17736)
2024-09-26 23:43:58 +03:00
Peter Tripp
48c6eb9ac7 Add script to generate license dependencies as csv (#18411)
Co-authored-by: Joseph T. Lyons <JosephTLyons@gmail.com>
2024-09-26 16:21:20 -04:00
Conrad Irwin
e28496d4e2 Stop leaking isahc assumption (#18408)
Users of our http_client crate knew they were interacting with isahc as
they set its extensions on the request. This change adds our own
equivalents for their APIs in preparation for changing the default http
client.

Release Notes:

- N/A
2024-09-26 14:01:05 -06:00
Max Brunsfeld
c1a039a5d7 Remove old project search code path, bump min-supported zed version for collaboration (#18404)
Release Notes:

- N/A
2024-09-26 12:10:39 -07:00
Mikayla Maki
71da81c743 SSH Remoting: Fix bugs in worktree syncing (#18406)
Release Notes:

- N/A

---------

Co-authored-by: conrad <conrad@zed.dev>
2024-09-26 12:03:57 -07:00
thataboy
11058765be Add ability to separately set background color for highlighted brackets (#17566)
Closes https://github.com/zed-industries/zed/issues/16380

Currently brackets are highlighted with
`editor.document_highlight.read_background`. This commit adds a separate
`editor.document_highlight.bracket_background` theme setting so bracket
highlights can be made more prominent without doing the same to other
highlights, making the display too busy.

(My own theme)


https://github.com/user-attachments/assets/29a8c05e-2f1a-4c16-9be8-a4b4cb143548

I set defaults for light and dark theme that I hope are sensible and not
too obnoxious, but noticeable so people can change it if they don't like
it.

Release Notes:

- Added `editor.document_highlight.bracket_background` field to the
theme to set background color of highlighted brackets.
- This will fall back to `editor.document_highlight.read_background`, if
not set.

<img width="355" alt="Screenshot 2024-09-08 at 8 46 57 AM"
src="https://github.com/user-attachments/assets/3270bb4d-19f5-4b34-8003-982377b2ceb6">
<img width="444" alt="Screenshot 2024-09-08 at 9 03 27 AM"
src="https://github.com/user-attachments/assets/3b12d84d-913c-4bde-9132-9b10f4a8d49b">

---------

Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-09-26 12:48:23 -04:00
renovate[bot]
c7a79cfc02 Update Rust crate libc to v0.2.159 (#18370)
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [libc](https://redirect.github.com/rust-lang/libc) |
workspace.dependencies | patch | `0.2.158` -> `0.2.159` |

---

### Release Notes

<details>
<summary>rust-lang/libc (libc)</summary>

###
[`v0.2.159`](https://redirect.github.com/rust-lang/libc/releases/tag/0.2.159)

[Compare
Source](https://redirect.github.com/rust-lang/libc/compare/0.2.158...0.2.159)

##### Added

- Android: add more `AT_*` constants in
[#&#8203;3779](https://redirect.github.com/rust-lang/libc/pull/3779)
- Apple: add missing `NOTE_*` constants in
[#&#8203;3883](https://redirect.github.com/rust-lang/libc/pull/3883)
- Hermit: add missing error numbers in
[#&#8203;3858](https://redirect.github.com/rust-lang/libc/pull/3858)
- Hurd: add `__timeval` for 64-bit support in
[#&#8203;3786](https://redirect.github.com/rust-lang/libc/pull/3786)
- Linux: add `epoll_pwait2` in
[#&#8203;3868](https://redirect.github.com/rust-lang/libc/pull/3868)
- Linux: add `mq_notify` in
[#&#8203;3849](https://redirect.github.com/rust-lang/libc/pull/3849)
- Linux: add missing `NFT_CT_*` constants in
[#&#8203;3844](https://redirect.github.com/rust-lang/libc/pull/3844)
- Linux: add the `fchmodat2` syscall in
[#&#8203;3588](https://redirect.github.com/rust-lang/libc/pull/3588)
- Linux: add the `mseal` syscall in
[#&#8203;3798](https://redirect.github.com/rust-lang/libc/pull/3798)
- OpenBSD: add `sendmmsg` and `recvmmsg` in
[#&#8203;3831](https://redirect.github.com/rust-lang/libc/pull/3831)
- Unix: add `IN6ADDR_ANY_INIT` and `IN6ADDR_LOOPBACK_INIT` in
[#&#8203;3693](https://redirect.github.com/rust-lang/libc/pull/3693)
- VxWorks: add `S_ISVTX` in
[#&#8203;3768](https://redirect.github.com/rust-lang/libc/pull/3768)
- VxWorks: add `vxCpuLib` and `taskLib` functions
[#&#8203;3861](https://redirect.github.com/rust-lang/libc/pull/3861)
- WASIp2: add definitions for `std::net` support in
[#&#8203;3892](https://redirect.github.com/rust-lang/libc/pull/3892)

##### Fixed

- Correctly handle version checks when `clippy-driver` is used
[#&#8203;3893](https://redirect.github.com/rust-lang/libc/pull/3893)

##### Changed

- EspIdf: change signal constants to c_int in
[#&#8203;3895](https://redirect.github.com/rust-lang/libc/pull/3895)
- HorizonOS: update network definitions in
[#&#8203;3863](https://redirect.github.com/rust-lang/libc/pull/3863)
- Linux: combine `ioctl` APIs in
[#&#8203;3722](https://redirect.github.com/rust-lang/libc/pull/3722)
- WASI: enable CI testing in
[#&#8203;3869](https://redirect.github.com/rust-lang/libc/pull/3869)
- WASIp2: enable CI testing in
[#&#8203;3870](https://redirect.github.com/rust-lang/libc/pull/3870)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "after 3pm on Wednesday" in timezone
America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC44MC4wIiwidXBkYXRlZEluVmVyIjoiMzguODAuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-09-26 12:16:49 -04:00
renovate[bot]
84a6ded657 Update Rust crate clap to v4.5.18 (#18369)
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [clap](https://redirect.github.com/clap-rs/clap) |
workspace.dependencies | patch | `4.5.17` -> `4.5.18` |

---

### Release Notes

<details>
<summary>clap-rs/clap (clap)</summary>

###
[`v4.5.18`](https://redirect.github.com/clap-rs/clap/blob/HEAD/CHANGELOG.md#4518---2024-09-20)

[Compare
Source](https://redirect.github.com/clap-rs/clap/compare/v4.5.17...v4.5.18)

##### Features

- *(builder)* Expose `Arg::get_display_order` and
`Command::get_display_order`

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "after 3pm on Wednesday" in timezone
America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC44MC4wIiwidXBkYXRlZEluVmVyIjoiMzguODAuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-09-26 11:52:12 -04:00
renovate[bot]
e5bbd378a6 Update Rust crate cargo_toml to v0.20.5 (#18365)
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [cargo_toml](https://lib.rs/cargo_toml)
([source](https://gitlab.com/lib.rs/cargo_toml)) |
workspace.dependencies | patch | `0.20.4` -> `0.20.5` |

---

### Release Notes

<details>
<summary>lib.rs/cargo_toml (cargo_toml)</summary>

###
[`v0.20.5`](https://gitlab.com/lib.rs/cargo_toml/compare/v0.20.4...v0.20.5)

[Compare
Source](https://gitlab.com/lib.rs/cargo_toml/compare/v0.20.4...v0.20.5)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "after 3pm on Wednesday" in timezone
America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC44MC4wIiwidXBkYXRlZEluVmVyIjoiMzguODAuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-09-26 11:44:38 -04:00
renovate[bot]
82eb753b31 Update actions/setup-node digest to 0a44ba7 (#18357)
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [actions/setup-node](https://redirect.github.com/actions/setup-node) |
action | digest | `1e60f62` -> `0a44ba7` |

---

### Configuration

📅 **Schedule**: Branch creation - "after 3pm on Wednesday" in timezone
America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC44MC4wIiwidXBkYXRlZEluVmVyIjoiMzguODAuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-09-26 11:24:01 -04:00
renovate[bot]
de1889d6a8 Update Rust crate async-trait to v0.1.83 (#18364)
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [async-trait](https://redirect.github.com/dtolnay/async-trait) |
workspace.dependencies | patch | `0.1.82` -> `0.1.83` |

---

### Release Notes

<details>
<summary>dtolnay/async-trait (async-trait)</summary>

###
[`v0.1.83`](https://redirect.github.com/dtolnay/async-trait/releases/tag/0.1.83)

[Compare
Source](https://redirect.github.com/dtolnay/async-trait/compare/0.1.82...0.1.83)

- Prevent needless_arbitrary_self_type lint being produced in generated
code
([#&#8203;278](https://redirect.github.com/dtolnay/async-trait/issues/278))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "after 3pm on Wednesday" in timezone
America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC44MC4wIiwidXBkYXRlZEluVmVyIjoiMzguODAuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-09-26 08:49:50 -06:00
Piotr Osiewicz
f143396825 ssh: Do not require user to be signed in to use ssh remoting (#18396)
Fixes #18392

Closes #18392

Release Notes:

- N/A
2024-09-26 16:24:11 +02:00
Thorsten Ball
7eea1a6f51 git blame gutter: Use smallest possible space (#18145)
Before:
![screenshot-2024-09-26-15 00
20@2x](https://github.com/user-attachments/assets/f6706325-5bef-404e-a0b4-63a5121969fa)

After:

![screenshot-2024-09-26-15 02
24@2x](https://github.com/user-attachments/assets/739d0831-0b4a-457f-917e-10f3a662e74d)


Release Notes:

- Improved the git blame gutter to take up only the space required to
display the longest git author name in the current file.

---------

Co-authored-by: Bennet Bo Fenner <bennet@zed.dev>
2024-09-26 15:47:14 +02:00
Galen Elias
1a4f9b2891 Fix minimum gutter line number spacing (#18021)
I was inspecting how Zed did the layout in the editor, specifically for
the gutter, and noticed that `em_width * X` is being used as the 'width
of X consecutive characters'. Howevever, that math didn't work for me,
because em_width doesn't account for the space between characters, so
you can't just multiply it by a character count.

One place this is actually noticeable is in the logic for
`min_width_for_number_on_gutter`, where we try to reserve 4 characters
of line number space. However, once you actually hit 4 characters, the
actual width is bigger, causing things to resize. This seems clearly
counter to the intent of the code.

It seems the more correct logic is to use `em_advance` which accounts
for the space between the characters. I am leaving the rest of the uses
of `em_width` for generic padding. It is also possible that
`column_pixels()` would be the more correct fix here, but it wasn't
straightforward to use that due to it residing EditorElement source
file.

On my MacBook this increases the width of the gutter by 6 pixels when
there are <999 lines in the file, otherwise it's identical.

It might be worth doing some more general audit of some of the other
uses of em_width as a concept. (e.g. `git_blame_entries_width`)


https://github.com/user-attachments/assets/f2a28cd5-9bb6-4109-bf41-1838e56a75f9

Release Notes:

- Fix a slight gutter flicker when going over 999 lines
2024-09-26 16:30:06 +03:00
Taras Martyniuk
1deed247eb terraform: Bump to v0.1.1 (#18382)
This PR bumps the Terraform extension to v0.1.1

- https://github.com/zed-industries/zed/pull/17200

Release Notes:

- N/A
2024-09-26 08:36:58 -04:00
Piotr Osiewicz
db92a31067 lsp: Do not notify all language servers on file save (#17756)
This is not an ideal solution to
https://github.com/fasterthanlime/zed-diags-readme, but current status
quo is not great either; we were just going through all of the language
servers and notifying them, whereas we should ideally do it based on a
glob.
/cc @fasterthanlime

Release Notes:

- N/A
2024-09-26 13:18:50 +02:00
Bennet Bo Fenner
31902a1b73 Remove leftover println statements (#18389)
Remove some leftover println statements from #17644

Release Notes:

- N/A
2024-09-26 12:52:56 +02:00
Thorsten Ball
3f415f3587 Fix use_on_type_format setting being unused per language (#18387)
Before this change, `use_on_type_format` would only have an effect when
defined on a global level in our settings.

But our default.json settings would also document that it's used in
language settings, i.e.:

```json
{
  "languages": {
    "C": {
      "use_on_type_format": false
    },
    "C++": {
      "use_on_type_format": false
    }
  }
}
```

But this did **not** work.

With the change, it now works globally and per-language.

Release Notes:

- Fixed `use_on_type_format` setting not working when defined inside
`"languages"` in the settings. This change will now change the default
behavior for C, C++, and Markdown, by turning language server's
`OnTypeFormatting` completions off by default.

Co-authored-by: Bennet <bennet@zed.dev>
2024-09-26 12:27:08 +02:00
Thorsten Ball
140d70289e Avoid panic by only restoring workspace if UI has launched (#18386)
This should fix the `unregistered setting type
workspace::workspace_settings::WorkspaceSettings` panic that came from
inside `restorable_workspace_locations`.

We tracked it down to a possible scenario (we can't recreate it though)
in which `app.on_reopen` is called before the app has finished
launching.

In any case, this check makes sense, because we only want to restore a
workspace in case the whole app has launched with a UI.

Release Notes:

- N/A

Co-authored-by: Bennet <bennet@zed.dev>
2024-09-26 12:26:58 +02:00
Hyunmin Woo (Hanul)
b9b689d322 Fix Typo in rust language guide (#18383)
Release Notes:

- N/A
2024-09-26 12:24:29 +02:00
Thorsten Ball
2d2e20f9d4 editor: Fix cursor shape not restoring when setting removed (#18379)
Closes #18119

Release Notes:

- Fixed the cursor shape in the editor not changing back to default when
`{"cursor_shape": "..."}` setting is removed. (Does not apply to Vim
mode.)
2024-09-26 11:07:07 +02:00
Conrad Irwin
b701eab44f Avoid unwrap in file finder (#18374)
Release Notes:

- Fixed a (rare) panic in file finder

---------

Co-authored-by: Kirill Bulatov <kirill@zed.dev>
2024-09-26 10:31:17 +03:00
Max Brunsfeld
6167688a63 Proposed changes editor features (#18373)
This PR adds some more functionality to the Proposed Changes Editor
view, which we'll be using in
https://github.com/zed-industries/zed/pull/18240 for allowing the
assistant to propose changes to a set of buffers.

* Add an `Apply All` button, and fully implement applying of changes to
the base buffer
* Make the proposed changes editor searchable
* Fix a bug in branch buffers' diff state management

Release Notes:

- N/A
2024-09-25 16:33:00 -07:00
Mikayla Maki
3161aedcb0 Fix broken collaboration UI from #18308 (#18372)
Fixes a bug introduced by #18308, that caused the call controls to
render incorrectly.

Release Notes:

- N/A
2024-09-25 16:03:08 -07:00
Conrad Irwin
64532e94e4 Move adapters to remote (#18359)
Release Notes:

- ssh remoting: run LSP Adapters on host

---------

Co-authored-by: Mikayla <mikayla@zed.dev>
2024-09-25 15:29:04 -07:00
Peter Tripp
40408e731e Fix sending alt-enter in terminal (#18363) 2024-09-25 18:01:33 -04:00
Peter Tripp
7398f795e3 Ollama llama3.2 default context size (#18366)
Release Notes:

- Ollama: Added llama3.2 support
2024-09-25 18:01:12 -04:00
Piotr Osiewicz
4b4565fb7a assistant: Enable assistant panel/inline assists in ssh remote projects (#18367)
Release Notes:

- ssh remoting: Enable assistant panel and inline assists (running on
client)
2024-09-25 22:55:36 +02:00
Max Brunsfeld
21a023980d Expand git diffs when clicking the gutter strip, display their controls in a block above (#18313)
Todo:

* [x] Tooltips for hunk buttons
* [x] Buttons to go to next and previous hunk
* [x] Ellipsis button that opens a context menu with `Revert all`

/cc @iamnbutler @danilo-leal for design 👀 

Release Notes:

- Changed the behavior of the git gutter so that diff hunk are expanded
immediately when clicking the gutter, and hunk controls are displayed
above the hunk.

---------

Co-authored-by: Marshall <marshall@zed.dev>
Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-09-25 12:50:38 -07:00
Mikayla Maki
ae6a3d15af Make python run local worktree LSPs (#18353)
Release Notes:

- Python: made it possible to use locally installed `pyright` if
available

---------

Co-authored-by: conrad <conrad@zed.dev>
2024-09-25 12:45:41 -07:00
renovate[bot]
dc7c49bd0b Pin actions/stale action to 28ca103 (#18356)
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [actions/stale](https://redirect.github.com/actions/stale) | action |
pinDigest | -> `28ca103` |

---

### Configuration

📅 **Schedule**: Branch creation - "after 3pm on Wednesday" in timezone
America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

Release Notes:

- N/A

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzOC44MC4wIiwidXBkYXRlZEluVmVyIjoiMzguODAuMCIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-09-25 15:25:57 -04:00
Richard Feldman
1eddd2f38d Fix file descriptors leak in evals (#18351)
Fixes an issue where evals were hitting "too many open files" errors
because we were adding (and detaching) new directory watches for each
project. Now we add those watches globally/at the worktree level, and we
store the tasks so they stop watching on drop.

Release Notes:

- N/A

---------

Co-authored-by: Max <max@zed.dev>
Co-authored-by: Piotr <piotr@zed.dev>
Co-authored-by: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com>
2024-09-25 15:21:00 -04:00
Peter Tripp
4aad214eae Rewind a bit on the buf version. 2024-09-18 17:26:44 -04:00
Peter Tripp
2d62e50023 Apply buf format 2024-09-18 17:21:40 -04:00
Peter Tripp
c772f87b99 No v maybe? 2024-09-18 17:07:02 -04:00
Peter Tripp
4783fe176d Bump buf-action to newest (v1.41.0) as buf-action requires buf >= v1.35.0 2024-09-18 16:51:41 -04:00
Peter Tripp
39c92bc9ee Update .github/workflows/ci.yml
Co-authored-by: Marshall Bowers <elliott.codes@gmail.com>
2024-09-18 16:37:05 -04:00
Peter Tripp
3bedf2b30c ci: Switch Proto-buf checks to non-deprecated bufbuild/buf-action.
- bufbuild/buf-setup-action [has been deprecated](3de295e042) since 2024-08-01.
2024-09-18 16:34:44 -04:00
208 changed files with 5956 additions and 5619 deletions

View File

@@ -10,7 +10,7 @@ runs:
cargo install cargo-nextest
- name: Install Node
uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # v4
uses: actions/setup-node@0a44ba7841725637a19e28fa30b79a866c81b0a6 # v4
with:
node-version: "18"

View File

@@ -41,7 +41,7 @@ jobs:
exit 1
;;
esac
which cargo-set-version > /dev/null || cargo install cargo-edit --features vendored-openssl
which cargo-set-version > /dev/null || cargo install cargo-edit
output=$(cargo set-version -p zed --bump patch 2>&1 | sed 's/.* //')
git commit -am "Bump to $output for @$GITHUB_ACTOR" --author "Zed Bot <hi@zed.dev>"
git tag v${output}${tag_suffix}

View File

@@ -65,13 +65,13 @@ jobs:
echo "BUF_BASE_BRANCH=$GITHUB_BASE_REF" >> $GITHUB_ENV
fi
- uses: bufbuild/buf-setup-action@v1
with:
version: v1.29.0
- uses: bufbuild/buf-breaking-action@v1
- name: Protobuf checks
uses: bufbuild/buf-action@v1
with:
version: 1.35.0
input: "crates/proto/proto/"
against: "https://github.com/${GITHUB_REPOSITORY}.git#branch=${BUF_BASE_BRANCH},subdir=crates/proto/proto/"
breaking_against: "https://github.com/${GITHUB_REPOSITORY}.git#branch=${GITHUB_BASE_REF},subdir=crates/proto/proto/"
lint: false
macos_tests:
timeout-minutes: 60
@@ -172,7 +172,7 @@ jobs:
DIGITALOCEAN_SPACES_SECRET_KEY: ${{ secrets.DIGITALOCEAN_SPACES_SECRET_KEY }}
steps:
- name: Install Node
uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # v4
uses: actions/setup-node@0a44ba7841725637a19e28fa30b79a866c81b0a6 # v4
with:
node-version: "18"
@@ -192,29 +192,12 @@ jobs:
- name: Determine version and release channel
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
run: |
set -eu
# This exports RELEASE_CHANNEL into env (GITHUB_ENV)
script/determine-release-channel
version=$(script/get-crate-version zed)
channel=$(cat crates/zed/RELEASE_CHANNEL)
echo "Publishing version: ${version} on release channel ${channel}"
echo "RELEASE_CHANNEL=${channel}" >> $GITHUB_ENV
expected_tag_name=""
case ${channel} in
stable)
expected_tag_name="v${version}";;
preview)
expected_tag_name="v${version}-pre";;
nightly)
expected_tag_name="v${version}-nightly";;
*)
echo "can't publish a release on channel ${channel}"
exit 1;;
esac
if [[ $GITHUB_REF_NAME != $expected_tag_name ]]; then
echo "invalid release tag ${GITHUB_REF_NAME}. expected ${expected_tag_name}"
exit 1
fi
- name: Draft release notes
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
run: |
mkdir -p target/
# Ignore any errors that occur while drafting release notes to not fail the build.
script/draft-release-notes "$version" "$channel" > target/release-notes.md || true
@@ -271,7 +254,7 @@ jobs:
timeout-minutes: 60
name: Create a Linux bundle
runs-on:
- buildjet-16vcpu-ubuntu-2204
- buildjet-16vcpu-ubuntu-2004
if: ${{ startsWith(github.ref, 'refs/tags/v') || contains(github.event.pull_request.labels.*.name, 'run-bundling') }}
needs: [linux_tests]
env:
@@ -284,34 +267,13 @@ jobs:
clean: false
- name: Install Linux dependencies
run: ./script/linux
run: ./script/linux && ./script/install-mold 2.34.0
- name: Determine version and release channel
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
run: |
set -eu
version=$(script/get-crate-version zed)
channel=$(cat crates/zed/RELEASE_CHANNEL)
echo "Publishing version: ${version} on release channel ${channel}"
echo "RELEASE_CHANNEL=${channel}" >> $GITHUB_ENV
expected_tag_name=""
case ${channel} in
stable)
expected_tag_name="v${version}";;
preview)
expected_tag_name="v${version}-pre";;
nightly)
expected_tag_name="v${version}-nightly";;
*)
echo "can't publish a release on channel ${channel}"
exit 1;;
esac
if [[ $GITHUB_REF_NAME != $expected_tag_name ]]; then
echo "invalid release tag ${GITHUB_REF_NAME}. expected ${expected_tag_name}"
exit 1
fi
# This exports RELEASE_CHANNEL into env (GITHUB_ENV)
script/determine-release-channel
- name: Create Linux .tar.gz bundle
run: script/bundle-linux
@@ -357,29 +319,8 @@ jobs:
- name: Determine version and release channel
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
run: |
set -eu
version=$(script/get-crate-version zed)
channel=$(cat crates/zed/RELEASE_CHANNEL)
echo "Publishing version: ${version} on release channel ${channel}"
echo "RELEASE_CHANNEL=${channel}" >> $GITHUB_ENV
expected_tag_name=""
case ${channel} in
stable)
expected_tag_name="v${version}";;
preview)
expected_tag_name="v${version}-pre";;
nightly)
expected_tag_name="v${version}-nightly";;
*)
echo "can't publish a release on channel ${channel}"
exit 1;;
esac
if [[ $GITHUB_REF_NAME != $expected_tag_name ]]; then
echo "invalid release tag ${GITHUB_REF_NAME}. expected ${expected_tag_name}"
exit 1
fi
# This exports RELEASE_CHANNEL into env (GITHUB_ENV)
script/determine-release-channel
- name: Create and upload Linux .tar.gz bundle
run: script/bundle-linux

View File

@@ -8,7 +8,7 @@ jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
- uses: actions/stale@28ca1036281a5e5922ead5184a1bbf96e5fc984e # v9
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: >

View File

@@ -21,7 +21,7 @@ jobs:
version: 9
- name: Setup Node
uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # v4
uses: actions/setup-node@0a44ba7841725637a19e28fa30b79a866c81b0a6 # v4
with:
node-version: "20"
cache: "pnpm"

View File

@@ -76,7 +76,11 @@ jobs:
clean: false
- name: Build docker image
run: docker build . --build-arg GITHUB_SHA=$GITHUB_SHA --tag registry.digitalocean.com/zed/collab:$GITHUB_SHA
run: |
docker build -f Dockerfile-collab \
--build-arg GITHUB_SHA=$GITHUB_SHA \
--tag registry.digitalocean.com/zed/collab:$GITHUB_SHA \
.
- name: Publish docker image
run: docker push registry.digitalocean.com/zed/collab:${GITHUB_SHA}

View File

@@ -22,7 +22,7 @@ jobs:
- buildjet-16vcpu-ubuntu-2204
steps:
- name: Install Node
uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # v4
uses: actions/setup-node@0a44ba7841725637a19e28fa30b79a866c81b0a6 # v4
with:
node-version: "18"

View File

@@ -70,7 +70,7 @@ jobs:
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
steps:
- name: Install Node
uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # v4
uses: actions/setup-node@0a44ba7841725637a19e28fa30b79a866c81b0a6 # v4
with:
node-version: "18"
@@ -100,7 +100,7 @@ jobs:
name: Create a Linux *.tar.gz bundle for x86
if: github.repository_owner == 'zed-industries'
runs-on:
- buildjet-16vcpu-ubuntu-2204
- buildjet-16vcpu-ubuntu-2004
needs: tests
env:
DIGITALOCEAN_SPACES_ACCESS_KEY: ${{ secrets.DIGITALOCEAN_SPACES_ACCESS_KEY }}
@@ -117,7 +117,7 @@ jobs:
run: echo "$HOME/.cargo/bin" >> $GITHUB_PATH
- name: Install Linux dependencies
run: ./script/linux
run: ./script/linux && ./script/install-mold 2.34.0
- name: Limit target directory size
run: script/clear-target-dir-if-larger-than 100

2
.gitignore vendored
View File

@@ -10,7 +10,7 @@
/crates/collab/seed.json
/crates/zed/resources/flatpak/flatpak-cargo-sources.json
/dev.zed.Zed*.json
/assets/*licenses.md
/assets/*licenses.*
**/venv
.build
*.wasm

View File

@@ -36,8 +36,15 @@
"RUST_DEFAULT_PACKAGE_RUN": "zed"
}
}
},
"proto": {
"tab_size": 2
}
},
"file_types": {
"Dockerfile": ["Dockerfile*[!dockerignore]"],
"Git Ignore": ["dockerignore"]
},
"hard_tabs": false,
"formatter": "auto",
"remove_trailing_whitespace_on_save": true,

41
Cargo.lock generated
View File

@@ -245,7 +245,6 @@ dependencies = [
"chrono",
"futures 0.3.30",
"http_client",
"isahc",
"schemars",
"serde",
"serde_json",
@@ -895,9 +894,9 @@ dependencies = [
[[package]]
name = "async-trait"
version = "0.1.82"
version = "0.1.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a27b8a3a6e1a44fa4c8baf1f653e4172e81486d4941f2237e20dc2d0cf4ddff1"
checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd"
dependencies = [
"proc-macro2",
"quote",
@@ -2087,9 +2086,9 @@ dependencies = [
[[package]]
name = "cargo_toml"
version = "0.20.4"
version = "0.20.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad639525b1c67b6a298f378417b060fbc04618bea559482a8484381cce27d965"
checksum = "88da5a13c620b4ca0078845707ea9c3faf11edbc3ffd8497d11d686211cd1ac0"
dependencies = [
"serde",
"toml 0.8.19",
@@ -2283,9 +2282,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.5.17"
version = "4.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e5a21b8495e732f1b3c364c9949b201ca7bae518c502c80256c96ad79eaf6ac"
checksum = "b0956a43b323ac1afaffc053ed5c4b7c1f1800bacd1683c353aabbb752515dd3"
dependencies = [
"clap_builder",
"clap_derive",
@@ -2293,9 +2292,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.5.17"
version = "4.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cf2dd12af7a047ad9d6da2b6b249759a22a7abc0f474c1dae1777afa4b21a73"
checksum = "4d72166dd41634086d5803a47eb71ae740e61d84709c36f3c34110173db3961b"
dependencies = [
"anstream",
"anstyle",
@@ -2315,9 +2314,9 @@ dependencies = [
[[package]]
name = "clap_derive"
version = "4.5.13"
version = "4.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "501d359d5f3dcaf6ecdeee48833ae73ec6e42723a1e52419c79abf9507eec0a0"
checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -2850,7 +2849,6 @@ dependencies = [
"gpui",
"http_client",
"indoc",
"isahc",
"language",
"lsp",
"menu",
@@ -3731,6 +3729,7 @@ dependencies = [
"multi_buffer",
"ordered-float 2.10.1",
"parking_lot",
"pretty_assertions",
"project",
"rand 0.8.5",
"release_channel",
@@ -4128,7 +4127,6 @@ dependencies = [
"gpui",
"http_client",
"indexed_docs",
"isahc",
"isahc_http_client",
"language",
"log",
@@ -4289,7 +4287,6 @@ dependencies = [
"gpui",
"http_client",
"human_bytes",
"isahc",
"language",
"log",
"menu",
@@ -5016,7 +5013,6 @@ dependencies = [
"anyhow",
"futures 0.3.30",
"http_client",
"isahc",
"schemars",
"serde",
"serde_json",
@@ -6288,7 +6284,6 @@ dependencies = [
"http_client",
"image",
"inline_completion_button",
"isahc",
"language",
"log",
"menu",
@@ -6434,9 +6429,9 @@ checksum = "03087c2bad5e1034e8cace5926dec053fb3790248370865f5117a7d0213354c8"
[[package]]
name = "libc"
version = "0.2.158"
version = "0.2.159"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439"
checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5"
[[package]]
name = "libdbus-sys"
@@ -6478,7 +6473,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4"
dependencies = [
"cfg-if",
"windows-targets 0.48.5",
"windows-targets 0.52.6",
]
[[package]]
@@ -7591,7 +7586,6 @@ dependencies = [
"anyhow",
"futures 0.3.30",
"http_client",
"isahc",
"schemars",
"serde",
"serde_json",
@@ -9122,6 +9116,7 @@ dependencies = [
"gpui",
"http_client",
"language",
"languages",
"log",
"lsp",
"node_runtime",
@@ -10498,6 +10493,7 @@ dependencies = [
"futures 0.3.30",
"gpui",
"parking_lot",
"paths",
"serde",
"serde_json",
"snippet",
@@ -13534,7 +13530,7 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
dependencies = [
"windows-sys 0.48.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -14433,7 +14429,6 @@ dependencies = [
"image_viewer",
"inline_completion_button",
"install_cli",
"isahc",
"isahc_http_client",
"journal",
"language",
@@ -14685,7 +14680,7 @@ dependencies = [
[[package]]
name = "zed_terraform"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"zed_extension_api 0.1.0",
]

26
Dockerfile-distros Normal file
View File

@@ -0,0 +1,26 @@
# syntax=docker/dockerfile:1
ARG BASE_IMAGE
FROM ${BASE_IMAGE}
WORKDIR /app
ARG TZ=Etc/UTC \
LANG=C.UTF-8 \
LC_ALL=C.UTF-8 \
DEBIAN_FRONTEND=noninteractive
ENV CARGO_TERM_COLOR=always
COPY script/linux script/
RUN ./script/linux
COPY script/install-mold script/install-cmake script/
RUN ./script/install-mold "2.34.0"
RUN ./script/install-cmake "3.30.4"
COPY . .
# When debugging, make these into individual RUN statements.
# Cleanup to avoid saving big layers we aren't going to use.
RUN . "$HOME/.cargo/env" \
&& cargo fetch \
&& cargo build \
&& cargo run -- --help \
&& cargo clean --quiet

View File

@@ -0,0 +1,2 @@
**/target
**/node_modules

View File

@@ -196,7 +196,7 @@
}
},
{
"context": "BufferSearchBar && in_replace",
"context": "BufferSearchBar && in_replace > Editor",
"bindings": {
"enter": "search::ReplaceNext",
"ctrl-enter": "search::ReplaceAll"
@@ -310,6 +310,11 @@
"ctrl-shift-\\": "editor::MoveToEnclosingBracket",
"ctrl-shift-[": "editor::Fold",
"ctrl-shift-]": "editor::UnfoldLines",
"ctrl-k ctrl-l": "editor::ToggleFold",
"ctrl-k ctrl-[": "editor::FoldRecursive",
"ctrl-k ctrl-]": "editor::UnfoldRecursive",
"ctrl-k ctrl-0": "editor::FoldAll",
"ctrl-k ctrl-j": "editor::UnfoldAll",
"ctrl-space": "editor::ShowCompletions",
"ctrl-.": "editor::ToggleCodeActions",
"alt-ctrl-r": "editor::RevealInFileManager",

View File

@@ -232,7 +232,7 @@
}
},
{
"context": "BufferSearchBar && in_replace",
"context": "BufferSearchBar && in_replace > Editor",
"bindings": {
"enter": "search::ReplaceNext",
"cmd-enter": "search::ReplaceAll"
@@ -347,6 +347,11 @@
"cmd-shift-\\": "editor::MoveToEnclosingBracket",
"alt-cmd-[": "editor::Fold",
"alt-cmd-]": "editor::UnfoldLines",
"cmd-k cmd-l": "editor::ToggleFold",
"cmd-k cmd-[": "editor::FoldRecursive",
"cmd-k cmd-]": "editor::UnfoldRecursive",
"cmd-k cmd-0": "editor::FoldAll",
"cmd-k cmd-j": "editor::UnfoldAll",
"ctrl-space": "editor::ShowCompletions",
"cmd-.": "editor::ToggleCodeActions",
"alt-cmd-r": "editor::RevealInFileManager",

View File

@@ -132,9 +132,15 @@
"z z": "editor::ScrollCursorCenter",
"z .": ["workspace::SendKeystrokes", "z z ^"],
"z b": "editor::ScrollCursorBottom",
"z a": "editor::ToggleFold",
"z A": "editor::ToggleFoldRecursive",
"z c": "editor::Fold",
"z C": "editor::FoldRecursive",
"z o": "editor::UnfoldLines",
"z O": "editor::UnfoldRecursive",
"z f": "editor::FoldSelectedRanges",
"z M": "editor::FoldAll",
"z R": "editor::UnfoldAll",
"shift-z shift-q": ["pane::CloseActiveItem", { "saveIntent": "skip" }],
"shift-z shift-z": ["pane::CloseActiveItem", { "saveIntent": "saveAll" }],
// Count support

View File

@@ -535,17 +535,16 @@
// How to soft-wrap long lines of text.
// Possible values:
//
// 1. Do not soft wrap.
// 1. Prefer a single line generally, unless an overly long line is encountered.
// "soft_wrap": "none",
// 2. Prefer a single line generally, unless an overly long line is encountered.
// "soft_wrap": "prefer_line",
// 3. Soft wrap lines that overflow the editor.
// "soft_wrap": "prefer_line", // (deprecated, same as "none")
// 2. Soft wrap lines that overflow the editor.
// "soft_wrap": "editor_width",
// 4. Soft wrap lines at the preferred line length.
// 3. Soft wrap lines at the preferred line length.
// "soft_wrap": "preferred_line_length",
// 5. Soft wrap lines at the preferred line length or the editor width (whichever is smaller).
// 4. Soft wrap lines at the preferred line length or the editor width (whichever is smaller).
// "soft_wrap": "bounded",
"soft_wrap": "prefer_line",
"soft_wrap": "none",
// The column at which to soft-wrap lines, for buffers where soft-wrap
// is enabled.
"preferred_line_length": 80,
@@ -600,13 +599,11 @@
}
},
// Configuration for how direnv configuration should be loaded. May take 2 values:
// 1. Load direnv configuration through the shell hook, works for POSIX shells and fish.
// "load_direnv": "shell_hook"
// 2. Load direnv configuration using `direnv export json` directly.
// This can help with some shells that otherwise would not detect
// the direnv environment, such as nushell or elvish.
// 1. Load direnv configuration using `direnv export json` directly.
// "load_direnv": "direct"
"load_direnv": "shell_hook",
// 2. Load direnv configuration through the shell hook, works for POSIX shells and fish.
// "load_direnv": "shell_hook"
"load_direnv": "direct",
"inline_completions": {
// A list of globs representing files that inline completions should be disabled for.
"disabled_globs": [".env"]
@@ -672,6 +669,18 @@
// 3. Always blink the cursor, ignoring the terminal mode
// "blinking": "on",
"blinking": "terminal_controlled",
// Default cursor shape for the terminal.
// 1. A block that surrounds the following character
// "block"
// 2. A vertical bar
// "bar"
// 3. An underline that runs along the following character
// "underscore"
// 4. A box drawn around the following character
// "hollow"
//
// Default: not set, defaults to "block"
"cursor_shape": null,
// Set whether Alternate Scroll mode (code: ?1007) is active by default.
// Alternate Scroll mode converts mouse scroll events into up / down key
// presses when in the alternate screen (e.g. when running applications
@@ -770,7 +779,8 @@
"**/Zed/**/*.json",
"tsconfig.json",
"pyrightconfig.json"
]
],
"TOML": ["uv.lock"]
},
/// By default use a recent system version of node, or install our own.
/// You can override this to use a version of node that is not in $PATH with:

View File

@@ -20,7 +20,6 @@ anyhow.workspace = true
chrono.workspace = true
futures.workspace = true
http_client.workspace = true
isahc.workspace = true
schemars = { workspace = true, optional = true }
serde.workspace = true
serde_json.workspace = true

View File

@@ -6,9 +6,8 @@ use std::{pin::Pin, str::FromStr};
use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Utc};
use futures::{io::BufReader, stream::BoxStream, AsyncBufReadExt, AsyncReadExt, Stream, StreamExt};
use http_client::{AsyncBody, HttpClient, Method, Request as HttpRequest};
use isahc::config::Configurable;
use isahc::http::{HeaderMap, HeaderValue};
use http_client::http::{HeaderMap, HeaderValue};
use http_client::{AsyncBody, HttpClient, HttpRequestExt, Method, Request as HttpRequest};
use serde::{Deserialize, Serialize};
use strum::{EnumIter, EnumString};
use thiserror::Error;
@@ -289,7 +288,7 @@ pub async fn stream_completion_with_rate_limit_info(
.header("X-Api-Key", api_key)
.header("Content-Type", "application/json");
if let Some(low_speed_timeout) = low_speed_timeout {
request_builder = request_builder.low_speed_timeout(100, low_speed_timeout);
request_builder = request_builder.read_timeout(low_speed_timeout);
}
let serialized_request =
serde_json::to_string(&request).context("failed to serialize request")?;

View File

@@ -72,6 +72,7 @@ use std::{
time::Duration,
};
use terminal_view::{terminal_panel::TerminalPanel, TerminalView};
use text::SelectionGoal;
use ui::TintColor;
use ui::{
prelude::*,
@@ -960,7 +961,8 @@ impl AssistantPanel {
}
fn new_context(&mut self, cx: &mut ViewContext<Self>) -> Option<View<ContextEditor>> {
if self.project.read(cx).is_via_collab() {
let project = self.project.read(cx);
if project.is_via_collab() && project.dev_server_project_id().is_none() {
let task = self
.context_store
.update(cx, |store, cx| store.create_remote_context(cx));
@@ -3437,7 +3439,7 @@ impl ContextEditor {
fn copy(&mut self, _: &editor::actions::Copy, cx: &mut ViewContext<Self>) {
if self.editor.read(cx).selections.count() == 1 {
let (copied_text, metadata) = self.get_clipboard_contents(cx);
let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
copied_text,
metadata,
@@ -3451,11 +3453,9 @@ impl ContextEditor {
fn cut(&mut self, _: &editor::actions::Cut, cx: &mut ViewContext<Self>) {
if self.editor.read(cx).selections.count() == 1 {
let (copied_text, metadata) = self.get_clipboard_contents(cx);
let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
self.editor.update(cx, |editor, cx| {
let selections = editor.selections.all::<Point>(cx);
editor.transact(cx, |this, cx| {
this.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.select(selections);
@@ -3475,52 +3475,71 @@ impl ContextEditor {
cx.propagate();
}
fn get_clipboard_contents(&mut self, cx: &mut ViewContext<Self>) -> (String, CopyMetadata) {
let creases = self.editor.update(cx, |editor, cx| {
let selection = editor.selections.newest::<Point>(cx);
let selection_start = editor.selections.newest::<usize>(cx).start;
fn get_clipboard_contents(
&mut self,
cx: &mut ViewContext<Self>,
) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
let (snapshot, selection, creases) = self.editor.update(cx, |editor, cx| {
let mut selection = editor.selections.newest::<Point>(cx);
let snapshot = editor.buffer().read(cx).snapshot(cx);
editor.display_map.update(cx, |display_map, cx| {
display_map
.snapshot(cx)
.crease_snapshot
.creases_in_range(
MultiBufferRow(selection.start.row)..MultiBufferRow(selection.end.row + 1),
&snapshot,
)
.filter_map(|crease| {
if let Some(metadata) = &crease.metadata {
let start = crease
.range
.start
.to_offset(&snapshot)
.saturating_sub(selection_start);
let end = crease
.range
.end
.to_offset(&snapshot)
.saturating_sub(selection_start);
let range_relative_to_selection = start..end;
let is_entire_line = selection.is_empty() || editor.selections.line_mode;
if is_entire_line {
selection.start = Point::new(selection.start.row, 0);
selection.end =
cmp::min(snapshot.max_point(), Point::new(selection.start.row + 1, 0));
selection.goal = SelectionGoal::None;
}
if range_relative_to_selection.is_empty() {
None
let selection_start = snapshot.point_to_offset(selection.start);
(
snapshot.clone(),
selection.clone(),
editor.display_map.update(cx, |display_map, cx| {
display_map
.snapshot(cx)
.crease_snapshot
.creases_in_range(
MultiBufferRow(selection.start.row)
..MultiBufferRow(selection.end.row + 1),
&snapshot,
)
.filter_map(|crease| {
if let Some(metadata) = &crease.metadata {
let start = crease
.range
.start
.to_offset(&snapshot)
.saturating_sub(selection_start);
let end = crease
.range
.end
.to_offset(&snapshot)
.saturating_sub(selection_start);
let range_relative_to_selection = start..end;
if range_relative_to_selection.is_empty() {
None
} else {
Some(SelectedCreaseMetadata {
range_relative_to_selection,
crease: metadata.clone(),
})
}
} else {
Some(SelectedCreaseMetadata {
range_relative_to_selection,
crease: metadata.clone(),
})
None
}
} else {
None
}
})
.collect::<Vec<_>>()
})
})
.collect::<Vec<_>>()
}),
)
});
let selection = selection.map(|point| snapshot.point_to_offset(point));
let context = self.context.read(cx);
let selection = self.editor.read(cx).selections.newest::<usize>(cx);
let mut text = String::new();
for message in context.messages(cx) {
if message.offset_range.start >= selection.range().end {
@@ -3539,7 +3558,7 @@ impl ContextEditor {
}
}
(text, CopyMetadata { creases })
(text, CopyMetadata { creases }, vec![selection])
}
fn paste(&mut self, action: &editor::actions::Paste, cx: &mut ViewContext<Self>) {

View File

@@ -1142,7 +1142,7 @@ impl InlineAssistant {
for row_range in inserted_row_ranges {
editor.highlight_rows::<InlineAssist>(
row_range,
Some(cx.theme().status().info_background),
cx.theme().status().info_background,
false,
cx,
);
@@ -1208,8 +1208,8 @@ impl InlineAssistant {
editor.set_read_only(true);
editor.set_show_inline_completions(Some(false), cx);
editor.highlight_rows::<DeletedLines>(
Anchor::min()..=Anchor::max(),
Some(cx.theme().status().deleted_background),
Anchor::min()..Anchor::max(),
cx.theme().status().deleted_background,
false,
cx,
);
@@ -2557,7 +2557,7 @@ enum CodegenStatus {
#[derive(Default)]
struct Diff {
deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)>,
inserted_row_ranges: Vec<RangeInclusive<Anchor>>,
inserted_row_ranges: Vec<Range<Anchor>>,
}
impl Diff {
@@ -3103,7 +3103,7 @@ impl CodegenAlternative {
new_end_row,
new_snapshot.line_len(MultiBufferRow(new_end_row)),
));
self.diff.inserted_row_ranges.push(start..=end);
self.diff.inserted_row_ranges.push(start..end);
new_row += lines;
}
}
@@ -3181,7 +3181,7 @@ impl CodegenAlternative {
new_end_row,
new_snapshot.line_len(MultiBufferRow(new_end_row)),
));
inserted_row_ranges.push(start..=end);
inserted_row_ranges.push(start..end);
new_row += line_count;
}
}

View File

@@ -264,6 +264,18 @@ pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<(
fn view_release_notes_locally(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
let release_channel = ReleaseChannel::global(cx);
let url = match release_channel {
ReleaseChannel::Nightly => Some("https://github.com/zed-industries/zed/commits/nightly/"),
ReleaseChannel::Dev => Some("https://github.com/zed-industries/zed/commits/main/"),
_ => None,
};
if let Some(url) = url {
cx.open_url(url);
return;
}
let version = AppVersion::global(cx).to_string();
let client = client::Client::global(cx).http_client();
@@ -345,15 +357,17 @@ pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
let should_show_notification = should_show_notification.await?;
if should_show_notification {
workspace.update(&mut cx, |workspace, cx| {
let workspace_handle = workspace.weak_handle();
workspace.show_notification(
NotificationId::unique::<UpdateNotification>(),
cx,
|cx| cx.new_view(|_| UpdateNotification::new(version)),
|cx| cx.new_view(|_| UpdateNotification::new(version, workspace_handle)),
);
updater
.read(cx)
.set_should_show_update_notification(false, cx)
.detach_and_log_err(cx);
updater.update(cx, |updater, cx| {
updater
.set_should_show_update_notification(false, cx)
.detach_and_log_err(cx);
});
})?;
}
anyhow::Ok(())

View File

@@ -1,13 +1,18 @@
use gpui::{
div, DismissEvent, EventEmitter, InteractiveElement, IntoElement, ParentElement, Render,
SemanticVersion, StatefulInteractiveElement, Styled, ViewContext,
SemanticVersion, StatefulInteractiveElement, Styled, ViewContext, WeakView,
};
use menu::Cancel;
use release_channel::ReleaseChannel;
use workspace::ui::{h_flex, v_flex, Icon, IconName, Label, StyledExt};
use util::ResultExt;
use workspace::{
ui::{h_flex, v_flex, Icon, IconName, Label, StyledExt},
Workspace,
};
pub struct UpdateNotification {
version: SemanticVersion,
workspace: WeakView<Workspace>,
}
impl EventEmitter<DismissEvent> for UpdateNotification {}
@@ -41,7 +46,11 @@ impl Render for UpdateNotification {
.child(Label::new("View the release notes"))
.cursor_pointer()
.on_click(cx.listener(|this, _, cx| {
crate::view_release_notes(&Default::default(), cx);
this.workspace
.update(cx, |workspace, cx| {
crate::view_release_notes_locally(workspace, cx);
})
.log_err();
this.dismiss(&menu::Cancel, cx)
})),
)
@@ -49,8 +58,8 @@ impl Render for UpdateNotification {
}
impl UpdateNotification {
pub fn new(version: SemanticVersion) -> Self {
Self { version }
pub fn new(version: SemanticVersion, workspace: WeakView<Workspace>) -> Self {
Self { version, workspace }
}
pub fn dismiss(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {

View File

@@ -1,7 +1,7 @@
use editor::Editor;
use gpui::{
Element, EventEmitter, IntoElement, ParentElement, Render, StyledText, Subscription,
ViewContext,
Element, EventEmitter, FocusableView, IntoElement, ParentElement, Render, StyledText,
Subscription, ViewContext,
};
use itertools::Itertools;
use std::cmp;
@@ -90,17 +90,30 @@ impl Render for Breadcrumbs {
ButtonLike::new("toggle outline view")
.child(breadcrumbs_stack)
.style(ButtonStyle::Transparent)
.on_click(move |_, cx| {
if let Some(editor) = editor.upgrade() {
outline::toggle(editor, &editor::actions::ToggleOutline, cx)
.on_click({
let editor = editor.clone();
move |_, cx| {
if let Some(editor) = editor.upgrade() {
outline::toggle(editor, &editor::actions::ToggleOutline, cx)
}
}
})
.tooltip(|cx| {
Tooltip::for_action(
"Show symbol outline",
&editor::actions::ToggleOutline,
cx,
)
.tooltip(move |cx| {
if let Some(editor) = editor.upgrade() {
let focus_handle = editor.read(cx).focus_handle(cx);
Tooltip::for_action_in(
"Show symbol outline",
&editor::actions::ToggleOutline,
&focus_handle,
cx,
)
} else {
Tooltip::for_action(
"Show symbol outline",
&editor::actions::ToggleOutline,
cx,
)
}
}),
),
None => element

View File

@@ -808,7 +808,7 @@ pub fn mentions_to_proto(mentions: &[(Range<usize>, UserId)]) -> Vec<proto::Chat
impl sum_tree::Item for ChannelMessage {
type Summary = ChannelMessageSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &()) -> Self::Summary {
ChannelMessageSummary {
max_id: self.id,
count: 1,

View File

@@ -149,18 +149,6 @@ spec:
secretKeyRef:
name: google-ai
key: api_key
- name: RUNPOD_API_KEY
valueFrom:
secretKeyRef:
name: runpod
key: api_key
optional: true
- name: RUNPOD_API_SUMMARY_URL
valueFrom:
secretKeyRef:
name: runpod
key: summary
optional: true
- name: BLOB_STORE_ACCESS_KEY
valueFrom:
secretKeyRef:

View File

@@ -32,6 +32,7 @@ macro_rules! id_type {
#[allow(unused)]
#[allow(missing_docs)]
pub fn from_proto(value: u64) -> Self {
debug_assert!(value != 0);
Self(value as i32)
}

View File

@@ -285,7 +285,7 @@ impl Database {
)
.one(&*tx)
.await?
.ok_or_else(|| anyhow!("no such project"))?;
.ok_or_else(|| anyhow!("no such project: {project_id}"))?;
// Update metadata.
worktree::Entity::update(worktree::ActiveModel {

View File

@@ -170,8 +170,6 @@ pub struct Config {
pub anthropic_api_key: Option<Arc<str>>,
pub anthropic_staff_api_key: Option<Arc<str>>,
pub llm_closed_beta_model_name: Option<Arc<str>>,
pub runpod_api_key: Option<Arc<str>>,
pub runpod_api_summary_url: Option<Arc<str>>,
pub zed_client_checksum_seed: Option<String>,
pub slack_panics_webhook: Option<String>,
pub auto_join_channel_id: Option<ChannelId>,
@@ -235,8 +233,6 @@ impl Config {
stripe_api_key: None,
stripe_price_id: None,
supermaven_admin_api_key: None,
runpod_api_key: None,
runpod_api_summary_url: None,
user_backfiller_github_access_token: None,
}
}

View File

@@ -400,42 +400,6 @@ async fn perform_completion(
})
.boxed()
}
LanguageModelProvider::Zed => {
let api_key = state
.config
.runpod_api_key
.as_ref()
.context("no Qwen2-7B API key configured on the server")?;
let api_url = state
.config
.runpod_api_summary_url
.as_ref()
.context("no Qwen2-7B URL configured on the server")?;
let chunks = open_ai::stream_completion(
&state.http_client,
api_url,
api_key,
serde_json::from_str(params.provider_request.get())?,
None,
)
.await?;
chunks
.map(|event| {
event.map(|chunk| {
let input_tokens =
chunk.usage.as_ref().map_or(0, |u| u.prompt_tokens) as usize;
let output_tokens =
chunk.usage.as_ref().map_or(0, |u| u.completion_tokens) as usize;
(
serde_json::to_vec(&chunk).unwrap(),
input_tokens,
output_tokens,
)
})
})
.boxed()
}
};
Ok(Response::new(Body::wrap_stream(TokenCountingStream {

View File

@@ -77,7 +77,6 @@ fn authorize_access_for_country(
LanguageModelProvider::Anthropic => anthropic::is_supported_country(country_code),
LanguageModelProvider::OpenAi => open_ai::is_supported_country(country_code),
LanguageModelProvider::Google => google_ai::is_supported_country(country_code),
LanguageModelProvider::Zed => true,
};
if !is_country_supported_by_provider {
Err(Error::http(
@@ -213,7 +212,6 @@ mod tests {
(LanguageModelProvider::Anthropic, "T1"), // Tor
(LanguageModelProvider::OpenAi, "T1"), // Tor
(LanguageModelProvider::Google, "T1"), // Tor
(LanguageModelProvider::Zed, "T1"), // Tor
];
for (provider, country_code) in cases {

View File

@@ -40,15 +40,6 @@ pub async fn seed_database(_config: &Config, db: &mut LlmDatabase, _force: bool)
price_per_million_input_tokens: 25, // $0.25/MTok
price_per_million_output_tokens: 125, // $1.25/MTok
},
ModelParams {
provider: LanguageModelProvider::Zed,
name: "Qwen/Qwen2-7B-Instruct".into(),
max_requests_per_minute: 5,
max_tokens_per_minute: 25_000, // These are arbitrary limits we've set to cap costs; we control this number
max_tokens_per_day: 300_000,
price_per_million_input_tokens: 25,
price_per_million_output_tokens: 125,
},
])
.await
}

View File

@@ -26,7 +26,6 @@ async fn test_initialize_providers(db: &mut LlmDatabase) {
LanguageModelProvider::Anthropic,
LanguageModelProvider::Google,
LanguageModelProvider::OpenAi,
LanguageModelProvider::Zed
]
)
}

View File

@@ -474,9 +474,6 @@ impl Server {
.add_request_handler(user_handler(
forward_read_only_project_request::<proto::GetReferences>,
))
.add_request_handler(user_handler(
forward_read_only_project_request::<proto::SearchProject>,
))
.add_request_handler(user_handler(forward_find_search_candidates_request))
.add_request_handler(user_handler(
forward_read_only_project_request::<proto::GetDocumentHighlights>,
@@ -2298,7 +2295,7 @@ async fn list_remote_directory(
let dev_server_connection_id = session
.connection_pool()
.await
.dev_server_connection_id_supporting(dev_server_id, ZedVersion::with_list_directory())?;
.online_dev_server_connection_id(dev_server_id)?;
session
.db()
@@ -2337,10 +2334,7 @@ async fn update_dev_server_project(
let dev_server_connection_id = session
.connection_pool()
.await
.dev_server_connection_id_supporting(
dev_server_project.dev_server_id,
ZedVersion::with_list_directory(),
)?;
.online_dev_server_connection_id(dev_server_project.dev_server_id)?;
session.peer.send(
dev_server_connection_id,
@@ -2950,40 +2944,6 @@ async fn forward_find_search_candidates_request(
.await
.host_for_read_only_project_request(project_id, session.connection_id, session.user_id())
.await?;
let host_version = session
.connection_pool()
.await
.connection(host_connection_id)
.map(|c| c.zed_version);
if host_version.is_some_and(|host_version| host_version < ZedVersion::with_search_candidates())
{
let query = request.query.ok_or_else(|| anyhow!("missing query"))?;
let search = proto::SearchProject {
project_id: project_id.to_proto(),
query: query.query,
regex: query.regex,
whole_word: query.whole_word,
case_sensitive: query.case_sensitive,
files_to_include: query.files_to_include,
files_to_exclude: query.files_to_exclude,
include_ignored: query.include_ignored,
};
let payload = session
.peer
.forward_request(session.connection_id, host_connection_id, search)
.await?;
return response.send(proto::FindSearchCandidatesResponse {
buffer_ids: payload
.locations
.into_iter()
.map(|loc| loc.buffer_id)
.collect(),
});
}
let payload = session
.peer
.forward_request(session.connection_id, host_connection_id, request)

View File

@@ -32,15 +32,7 @@ impl fmt::Display for ZedVersion {
impl ZedVersion {
pub fn can_collaborate(&self) -> bool {
self.0 >= SemanticVersion::new(0, 134, 0)
}
pub fn with_list_directory() -> ZedVersion {
ZedVersion(SemanticVersion::new(0, 145, 0))
}
pub fn with_search_candidates() -> ZedVersion {
ZedVersion(SemanticVersion::new(0, 151, 0))
self.0 >= SemanticVersion::new(0, 151, 0)
}
}
@@ -169,6 +161,16 @@ impl ConnectionPool {
self.connected_dev_servers.get(&dev_server_id).copied()
}
pub fn online_dev_server_connection_id(
&self,
dev_server_id: DevServerId,
) -> Result<ConnectionId> {
match self.connected_dev_servers.get(&dev_server_id) {
Some(cid) => Ok(*cid),
None => Err(anyhow!(proto::ErrorCode::DevServerOffline)),
}
}
pub fn dev_server_connection_id_supporting(
&self,
dev_server_id: DevServerId,

View File

@@ -246,7 +246,7 @@ async fn test_channel_notes_participant_indices(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
// Clients A and B open the same file.

View File

@@ -7,18 +7,12 @@ use collections::HashMap;
use editor::{
actions::{
ConfirmCodeAction, ConfirmCompletion, ConfirmRename, ContextMenuFirst, Redo, Rename,
RevertSelectedHunks, ToggleCodeActions, Undo,
},
display_map::DisplayRow,
test::{
editor_hunks,
editor_test_context::{AssertionContextManager, EditorTestContext},
expanded_hunks, expanded_hunks_background_highlights,
ToggleCodeActions, Undo,
},
test::editor_test_context::{AssertionContextManager, EditorTestContext},
Editor,
};
use futures::StreamExt;
use git::diff::DiffHunkStatus;
use gpui::{TestAppContext, UpdateGlobal, VisualContext, VisualTestContext};
use indoc::indoc;
use language::{
@@ -82,7 +76,7 @@ async fn test_host_disconnect(
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
cx_a.background_executor.run_until_parked();
assert!(worktree_a.read_with(cx_a, |tree, _| tree.has_update_observer()));
@@ -198,7 +192,7 @@ async fn test_newline_above_or_below_does_not_move_guest_cursor(
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open a buffer as client A
let buffer_a = project_a
@@ -314,7 +308,7 @@ async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mu
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open a file in an editor as the guest.
let buffer_b = project_b
@@ -571,7 +565,7 @@ async fn test_collaborating_with_code_actions(
.unwrap();
// Join the project as client B.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
let editor_b = workspace_b
.update(cx_b, |workspace, cx| {
@@ -786,7 +780,7 @@ async fn test_collaborating_with_renames(cx_a: &mut TestAppContext, cx_b: &mut T
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
let editor_b = workspace_b
@@ -1036,7 +1030,7 @@ async fn test_language_server_statuses(cx_a: &mut TestAppContext, cx_b: &mut Tes
.await
.unwrap();
executor.run_until_parked();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
project_b.read_with(cx_b, |project, cx| {
let status = project.language_server_statuses(cx).next().unwrap().1;
@@ -1132,9 +1126,7 @@ async fn test_share_project(
.await
.unwrap();
let client_b_peer_id = client_b.peer_id().unwrap();
let project_b = client_b
.build_dev_server_project(initial_project.id, cx_b)
.await;
let project_b = client_b.join_remote_project(initial_project.id, cx_b).await;
let replica_id_b = project_b.read_with(cx_b, |project, _| project.replica_id());
@@ -1236,9 +1228,7 @@ async fn test_share_project(
.update(cx_c, |call, cx| call.accept_incoming(cx))
.await
.unwrap();
let _project_c = client_c
.build_dev_server_project(initial_project.id, cx_c)
.await;
let _project_c = client_c.join_remote_project(initial_project.id, cx_c).await;
// Client B closes the editor, and client A sees client B's selections removed.
cx_b.update(move |_| drop(editor_b));
@@ -1297,7 +1287,7 @@ async fn test_on_input_format_from_host_to_guest(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open a file in an editor as the host.
let buffer_a = project_a
@@ -1417,7 +1407,7 @@ async fn test_on_input_format_from_guest_to_host(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open a file in an editor as the guest.
let buffer_b = project_b
@@ -1580,7 +1570,7 @@ async fn test_mutual_editor_inlay_hint_cache_update(
.unwrap();
// Client B joins the project
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
@@ -1842,7 +1832,7 @@ async fn test_inlay_hint_refresh_is_forwarded(
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
@@ -1970,285 +1960,6 @@ async fn test_inlay_hint_refresh_is_forwarded(
});
}
#[gpui::test]
async fn test_multiple_hunk_types_revert(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
let mut server = TestServer::start(cx_a.executor()).await;
let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await;
server
.create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
.await;
let active_call_a = cx_a.read(ActiveCall::global);
let active_call_b = cx_b.read(ActiveCall::global);
cx_a.update(editor::init);
cx_b.update(editor::init);
client_a.language_registry().add(rust_lang());
client_b.language_registry().add(rust_lang());
let base_text = indoc! {r#"struct Row;
struct Row1;
struct Row2;
struct Row4;
struct Row5;
struct Row6;
struct Row8;
struct Row9;
struct Row10;"#};
client_a
.fs()
.insert_tree(
"/a",
json!({
"main.rs": base_text,
}),
)
.await;
let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
active_call_a
.update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
.await
.unwrap();
let project_id = active_call_a
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
.unwrap();
let (workspace_a, cx_a) = client_a.build_workspace(&project_a, cx_a);
let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
let editor_a = workspace_a
.update(cx_a, |workspace, cx| {
workspace.open_path((worktree_id, "main.rs"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
let editor_b = workspace_b
.update(cx_b, |workspace, cx| {
workspace.open_path((worktree_id, "main.rs"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
let mut editor_cx_a = EditorTestContext {
cx: cx_a.clone(),
window: cx_a.handle(),
editor: editor_a,
assertion_cx: AssertionContextManager::new(),
};
let mut editor_cx_b = EditorTestContext {
cx: cx_b.clone(),
window: cx_b.handle(),
editor: editor_b,
assertion_cx: AssertionContextManager::new(),
};
// host edits the file, that differs from the base text, producing diff hunks
editor_cx_a.set_state(indoc! {r#"struct Row;
struct Row0.1;
struct Row0.2;
struct Row1;
struct Row4;
struct Row5444;
struct Row6;
struct Row9;
struct Row1220;ˇ"#});
editor_cx_a.update_editor(|editor, cx| {
editor
.buffer()
.read(cx)
.as_singleton()
.unwrap()
.update(cx, |buffer, cx| {
buffer.set_diff_base(Some(base_text.into()), cx);
});
});
editor_cx_b.update_editor(|editor, cx| {
editor
.buffer()
.read(cx)
.as_singleton()
.unwrap()
.update(cx, |buffer, cx| {
buffer.set_diff_base(Some(base_text.into()), cx);
});
});
cx_a.executor().run_until_parked();
cx_b.executor().run_until_parked();
// the client selects a range in the updated buffer, expands it to see the diff for each hunk in the selection
// the host does not see the diffs toggled
editor_cx_b.set_selections_state(indoc! {r#"«ˇstruct Row;
struct Row0.1;
struct Row0.2;
struct Row1;
struct Row4;
struct Row5444;
struct Row6;
struct R»ow9;
struct Row1220;"#});
editor_cx_b
.update_editor(|editor, cx| editor.toggle_hunk_diff(&editor::actions::ToggleHunkDiff, cx));
cx_a.executor().run_until_parked();
cx_b.executor().run_until_parked();
editor_cx_a.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(
all_hunks,
vec![
(
"".to_string(),
DiffHunkStatus::Added,
DisplayRow(1)..DisplayRow(3)
),
(
"struct Row2;\n".to_string(),
DiffHunkStatus::Removed,
DisplayRow(4)..DisplayRow(4)
),
(
"struct Row5;\n".to_string(),
DiffHunkStatus::Modified,
DisplayRow(6)..DisplayRow(7)
),
(
"struct Row8;\n".to_string(),
DiffHunkStatus::Removed,
DisplayRow(9)..DisplayRow(9)
),
(
"struct Row10;".to_string(),
DiffHunkStatus::Modified,
DisplayRow(10)..DisplayRow(10),
),
]
);
assert_eq!(all_expanded_hunks, Vec::new());
});
editor_cx_b.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(
expanded_hunks_background_highlights(editor, cx),
vec![DisplayRow(1)..=DisplayRow(2), DisplayRow(8)..=DisplayRow(8)],
);
assert_eq!(
all_hunks,
vec![
(
"".to_string(),
DiffHunkStatus::Added,
DisplayRow(1)..DisplayRow(3)
),
(
"struct Row2;\n".to_string(),
DiffHunkStatus::Removed,
DisplayRow(5)..DisplayRow(5)
),
(
"struct Row5;\n".to_string(),
DiffHunkStatus::Modified,
DisplayRow(8)..DisplayRow(9)
),
(
"struct Row8;\n".to_string(),
DiffHunkStatus::Removed,
DisplayRow(12)..DisplayRow(12)
),
(
"struct Row10;".to_string(),
DiffHunkStatus::Modified,
DisplayRow(13)..DisplayRow(13),
),
]
);
assert_eq!(all_expanded_hunks, &all_hunks[..all_hunks.len() - 1]);
});
// the client reverts the hunks, removing the expanded diffs too
// both host and the client observe the reverted state (with one hunk left, not covered by client's selection)
editor_cx_b.update_editor(|editor, cx| {
editor.revert_selected_hunks(&RevertSelectedHunks, cx);
});
cx_a.executor().run_until_parked();
cx_b.executor().run_until_parked();
editor_cx_a.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(
all_hunks,
vec![(
"struct Row10;".to_string(),
DiffHunkStatus::Modified,
DisplayRow(10)..DisplayRow(10),
)]
);
assert_eq!(all_expanded_hunks, Vec::new());
});
editor_cx_b.update_editor(|editor, cx| {
let snapshot = editor.snapshot(cx);
let all_hunks = editor_hunks(editor, &snapshot, cx);
let all_expanded_hunks = expanded_hunks(editor, &snapshot, cx);
assert_eq!(expanded_hunks_background_highlights(editor, cx), Vec::new());
assert_eq!(
all_hunks,
vec![(
"struct Row10;".to_string(),
DiffHunkStatus::Modified,
DisplayRow(10)..DisplayRow(10),
)]
);
assert_eq!(all_expanded_hunks, Vec::new());
});
editor_cx_a.assert_editor_state(indoc! {r#"struct Row;
struct Row1;
struct Row2;
struct Row4;
struct Row5;
struct Row6;
struct Row8;
struct Row9;
struct Row1220;ˇ"#});
editor_cx_b.assert_editor_state(indoc! {r#"«ˇstruct Row;
struct Row1;
struct Row2;
struct Row4;
struct Row5;
struct Row6;
struct Row8;
struct R»ow9;
struct Row1220;"#});
}
#[gpui::test(iterations = 10)]
async fn test_git_blame_is_forwarded(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
let mut server = TestServer::start(cx_a.executor()).await;
@@ -2335,7 +2046,7 @@ async fn test_git_blame_is_forwarded(cx_a: &mut TestAppContext, cx_b: &mut TestA
.unwrap();
// Join the project as client B.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
let editor_b = workspace_b
.update(cx_b, |workspace, cx| {

View File

@@ -74,7 +74,7 @@ async fn test_basic_following(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
@@ -162,7 +162,7 @@ async fn test_basic_following(
executor.run_until_parked();
let active_call_c = cx_c.read(ActiveCall::global);
let project_c = client_c.build_dev_server_project(project_id, cx_c).await;
let project_c = client_c.join_remote_project(project_id, cx_c).await;
let (workspace_c, cx_c) = client_c.build_workspace(&project_c, cx_c);
active_call_c
.update(cx_c, |call, cx| call.set_location(Some(&project_c), cx))
@@ -175,7 +175,7 @@ async fn test_basic_following(
cx_d.executor().run_until_parked();
let active_call_d = cx_d.read(ActiveCall::global);
let project_d = client_d.build_dev_server_project(project_id, cx_d).await;
let project_d = client_d.join_remote_project(project_id, cx_d).await;
let (workspace_d, cx_d) = client_d.build_workspace(&project_d, cx_d);
active_call_d
.update(cx_d, |call, cx| call.set_location(Some(&project_d), cx))
@@ -569,7 +569,7 @@ async fn test_following_tab_order(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
@@ -686,7 +686,7 @@ async fn test_peers_following_each_other(cx_a: &mut TestAppContext, cx_b: &mut T
.unwrap();
// Client B joins the project.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
@@ -1199,7 +1199,7 @@ async fn test_auto_unfollowing(cx_a: &mut TestAppContext, cx_b: &mut TestAppCont
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
@@ -1335,7 +1335,7 @@ async fn test_peers_simultaneously_following_each_other(
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let (workspace_b, cx_b) = client_b.build_workspace(&project_b, cx_b);
executor.run_until_parked();
@@ -1685,7 +1685,7 @@ async fn test_following_into_excluded_file(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await

View File

@@ -1372,7 +1372,7 @@ async fn test_unshare_project(
.unwrap();
let worktree_a = project_a.read_with(cx_a, |project, cx| project.worktrees(cx).next().unwrap());
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
executor.run_until_parked();
assert!(worktree_a.read_with(cx_a, |tree, _| tree.has_update_observer()));
@@ -1392,7 +1392,7 @@ async fn test_unshare_project(
assert!(project_b.read_with(cx_b, |project, _| project.is_disconnected()));
// Client C opens the project.
let project_c = client_c.build_dev_server_project(project_id, cx_c).await;
let project_c = client_c.join_remote_project(project_id, cx_c).await;
// When client A unshares the project, client C's project becomes read-only.
project_a
@@ -1409,7 +1409,7 @@ async fn test_unshare_project(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_c2 = client_c.build_dev_server_project(project_id, cx_c).await;
let project_c2 = client_c.join_remote_project(project_id, cx_c).await;
executor.run_until_parked();
assert!(worktree_a.read_with(cx_a, |tree, _| tree.has_update_observer()));
@@ -1514,9 +1514,9 @@ async fn test_project_reconnect(
.await
.unwrap();
let project_b1 = client_b.build_dev_server_project(project1_id, cx_b).await;
let project_b2 = client_b.build_dev_server_project(project2_id, cx_b).await;
let project_b3 = client_b.build_dev_server_project(project3_id, cx_b).await;
let project_b1 = client_b.join_remote_project(project1_id, cx_b).await;
let project_b2 = client_b.join_remote_project(project2_id, cx_b).await;
let project_b3 = client_b.join_remote_project(project3_id, cx_b).await;
executor.run_until_parked();
let worktree1_id = worktree_a1.read_with(cx_a, |worktree, _| {
@@ -2310,8 +2310,8 @@ async fn test_propagate_saves_and_fs_changes(
.unwrap();
// Join that worktree as clients B and C.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_c = client_c.build_dev_server_project(project_id, cx_c).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let project_c = client_c.join_remote_project(project_id, cx_c).await;
let worktree_b = project_b.read_with(cx_b, |p, cx| p.worktrees(cx).next().unwrap());
@@ -2535,7 +2535,7 @@ async fn test_git_diff_base_change(
.await
.unwrap();
let project_remote = client_b.build_dev_server_project(project_id, cx_b).await;
let project_remote = client_b.join_remote_project(project_id, cx_b).await;
let diff_base = "
one
@@ -2791,7 +2791,7 @@ async fn test_git_branch_name(
.await
.unwrap();
let project_remote = client_b.build_dev_server_project(project_id, cx_b).await;
let project_remote = client_b.join_remote_project(project_id, cx_b).await;
client_a
.fs()
.set_branch_name(Path::new("/dir/.git"), Some("branch-1"));
@@ -2836,7 +2836,7 @@ async fn test_git_branch_name(
assert_branch(Some("branch-2"), project, cx)
});
let project_remote_c = client_c.build_dev_server_project(project_id, cx_c).await;
let project_remote_c = client_c.join_remote_project(project_id, cx_c).await;
executor.run_until_parked();
project_remote_c.read_with(cx_c, |project, cx| {
@@ -2891,7 +2891,7 @@ async fn test_git_status_sync(
.await
.unwrap();
let project_remote = client_b.build_dev_server_project(project_id, cx_b).await;
let project_remote = client_b.join_remote_project(project_id, cx_b).await;
// Wait for it to catch up to the new status
executor.run_until_parked();
@@ -2967,7 +2967,7 @@ async fn test_git_status_sync(
});
// And synchronization while joining
let project_remote_c = client_c.build_dev_server_project(project_id, cx_c).await;
let project_remote_c = client_c.join_remote_project(project_id, cx_c).await;
executor.run_until_parked();
project_remote_c.read_with(cx_c, |project, cx| {
@@ -3015,7 +3015,7 @@ async fn test_fs_operations(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let worktree_a = project_a.read_with(cx_a, |project, cx| project.worktrees(cx).next().unwrap());
let worktree_b = project_b.read_with(cx_b, |project, cx| project.worktrees(cx).next().unwrap());
@@ -3316,7 +3316,7 @@ async fn test_local_settings(
executor.run_until_parked();
// As client B, join that project and observe the local settings.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let worktree_b = project_b.read_with(cx_b, |project, cx| project.worktrees(cx).next().unwrap());
executor.run_until_parked();
@@ -3439,7 +3439,7 @@ async fn test_buffer_conflict_after_save(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open a buffer as client B
let buffer_b = project_b
@@ -3503,7 +3503,7 @@ async fn test_buffer_reloading(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open a buffer as client B
let buffer_b = project_b
@@ -3557,7 +3557,7 @@ async fn test_editing_while_guest_opens_buffer(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open a buffer as client A
let buffer_a = project_a
@@ -3605,7 +3605,7 @@ async fn test_leaving_worktree_while_opening_buffer(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// See that a guest has joined as client A.
executor.run_until_parked();
@@ -3652,7 +3652,7 @@ async fn test_canceling_buffer_opening(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let buffer_a = project_a
.update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
@@ -3709,8 +3709,8 @@ async fn test_leaving_project(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b1 = client_b.build_dev_server_project(project_id, cx_b).await;
let project_c = client_c.build_dev_server_project(project_id, cx_c).await;
let project_b1 = client_b.join_remote_project(project_id, cx_b).await;
let project_c = client_c.join_remote_project(project_id, cx_c).await;
// Client A sees that a guest has joined.
executor.run_until_parked();
@@ -3751,7 +3751,7 @@ async fn test_leaving_project(
});
// Client B re-joins the project and can open buffers as before.
let project_b2 = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b2 = client_b.join_remote_project(project_id, cx_b).await;
executor.run_until_parked();
project_a.read_with(cx_a, |project, _| {
@@ -3927,7 +3927,7 @@ async fn test_collaborating_with_diagnostics(
);
// Join the worktree as client B.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Wait for server to see the diagnostics update.
executor.run_until_parked();
@@ -3952,7 +3952,7 @@ async fn test_collaborating_with_diagnostics(
});
// Join project as client C and observe the diagnostics.
let project_c = client_c.build_dev_server_project(project_id, cx_c).await;
let project_c = client_c.join_remote_project(project_id, cx_c).await;
executor.run_until_parked();
let project_c_diagnostic_summaries =
Rc::new(RefCell::new(project_c.read_with(cx_c, |project, cx| {
@@ -4160,7 +4160,7 @@ async fn test_collaborating_with_lsp_progress_updates_and_diagnostics_ordering(
.unwrap();
// Join the project as client B and open all three files.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let guest_buffers = futures::future::try_join_all(file_names.iter().map(|file_name| {
project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, file_name), cx))
}))
@@ -4266,7 +4266,7 @@ async fn test_reloading_buffer_manually(
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
@@ -4364,7 +4364,7 @@ async fn test_formatting_buffer(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
@@ -4409,7 +4409,7 @@ async fn test_formatting_buffer(
file.defaults.formatter = Some(SelectedFormatter::List(FormatterList(
vec![Formatter::External {
command: "awk".into(),
arguments: vec!["{sub(/two/,\"{buffer_path}\")}1".to_string()].into(),
arguments: Some(vec!["{sub(/two/,\"{buffer_path}\")}1".to_string()].into()),
}]
.into(),
)));
@@ -4486,7 +4486,7 @@ async fn test_prettier_formatting_buffer(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.ts"), cx));
let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
@@ -4599,7 +4599,7 @@ async fn test_definition(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open the file on client B.
let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
@@ -4744,7 +4744,7 @@ async fn test_references(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open the file on client B.
let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx));
@@ -4901,7 +4901,7 @@ async fn test_project_search(
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Perform a search as the guest.
let mut results = HashMap::default();
@@ -4991,7 +4991,7 @@ async fn test_document_highlights(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open the file on client B.
let open_b = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx));
@@ -5109,7 +5109,7 @@ async fn test_lsp_hover(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Open the file as the guest
let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx));
@@ -5286,7 +5286,7 @@ async fn test_project_symbols(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Cause the language server to start.
let open_buffer_task =
@@ -5381,7 +5381,7 @@ async fn test_open_buffer_while_getting_definition_pointing_to_it(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let open_buffer_task = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
let buffer_b1 = cx_b.executor().spawn(open_buffer_task).await.unwrap();
@@ -6470,7 +6470,7 @@ async fn test_context_collaboration_with_reconnect(
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
// Client A sees that a guest has joined.
executor.run_until_parked();

View File

@@ -9,7 +9,7 @@ use remote_server::HeadlessProject;
use serde_json::json;
use std::{path::Path, sync::Arc};
#[gpui::test]
#[gpui::test(iterations = 10)]
async fn test_sharing_an_ssh_remote_project(
cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext,
@@ -54,9 +54,8 @@ async fn test_sharing_an_ssh_remote_project(
let (project_a, worktree_id) = client_a
.build_ssh_project("/code/project1", client_ssh, cx_a)
.await;
executor.run_until_parked();
// User A shares the remote project.
// While the SSH worktree is being scanned, user A shares the remote project.
let active_call_a = cx_a.read(ActiveCall::global);
let project_id = active_call_a
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
@@ -64,12 +63,30 @@ async fn test_sharing_an_ssh_remote_project(
.unwrap();
// User B joins the project.
let project_b = client_b.build_dev_server_project(project_id, cx_b).await;
let project_b = client_b.join_remote_project(project_id, cx_b).await;
let worktree_b = project_b
.update(cx_b, |project, cx| project.worktree_for_id(worktree_id, cx))
.unwrap();
let worktree_a = project_a
.update(cx_a, |project, cx| project.worktree_for_id(worktree_id, cx))
.unwrap();
executor.run_until_parked();
worktree_a.update(cx_a, |worktree, _cx| {
assert_eq!(
worktree.paths().map(Arc::as_ref).collect::<Vec<_>>(),
vec![
Path::new(".zed"),
Path::new(".zed/settings.json"),
Path::new("README.md"),
Path::new("src"),
Path::new("src/lib.rs"),
]
);
});
worktree_b.update(cx_b, |worktree, _cx| {
assert_eq!(
worktree.paths().map(Arc::as_ref).collect::<Vec<_>>(),

View File

@@ -679,8 +679,6 @@ impl TestServer {
stripe_api_key: None,
stripe_price_id: None,
supermaven_admin_api_key: None,
runpod_api_key: None,
runpod_api_summary_url: None,
user_backfiller_github_access_token: None,
},
})
@@ -921,7 +919,7 @@ impl TestClient {
})
}
pub async fn build_dev_server_project(
pub async fn join_remote_project(
&self,
host_project_id: u64,
guest_cx: &mut TestAppContext,

View File

@@ -37,7 +37,6 @@ fs.workspace = true
futures.workspace = true
gpui.workspace = true
http_client.workspace = true
isahc.workspace = true
language.workspace = true
lsp.workspace = true
menu.workspace = true

View File

@@ -7,8 +7,7 @@ use chrono::DateTime;
use fs::Fs;
use futures::{io::BufReader, stream::BoxStream, AsyncBufReadExt, AsyncReadExt, StreamExt};
use gpui::{AppContext, AsyncAppContext, Global};
use http_client::{AsyncBody, HttpClient, Method, Request as HttpRequest};
use isahc::config::Configurable;
use http_client::{AsyncBody, HttpClient, HttpRequestExt, Method, Request as HttpRequest};
use paths::home_dir;
use serde::{Deserialize, Serialize};
use settings::watch_config_file;
@@ -275,7 +274,7 @@ async fn request_api_token(
.header("Accept", "application/json");
if let Some(low_speed_timeout) = low_speed_timeout {
request_builder = request_builder.low_speed_timeout(100, low_speed_timeout);
request_builder = request_builder.read_timeout(low_speed_timeout);
}
let request = request_builder.body(AsyncBody::empty())?;
@@ -332,7 +331,7 @@ async fn stream_completion(
.header("Copilot-Integration-Id", "vscode-chat");
if let Some(low_speed_timeout) = low_speed_timeout {
request_builder = request_builder.low_speed_timeout(100, low_speed_timeout);
request_builder = request_builder.read_timeout(low_speed_timeout);
}
let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
let mut response = client.send(request).await?;

View File

@@ -24,7 +24,8 @@ test-support = [
"workspace/test-support",
"tree-sitter-rust",
"tree-sitter-typescript",
"tree-sitter-html"
"tree-sitter-html",
"unindent",
]
[dependencies]
@@ -54,6 +55,7 @@ markdown.workspace = true
multi_buffer.workspace = true
ordered-float.workspace = true
parking_lot.workspace = true
pretty_assertions.workspace = true
project.workspace = true
rand.workspace = true
rpc.workspace = true
@@ -74,6 +76,7 @@ theme.workspace = true
tree-sitter-html = { workspace = true, optional = true }
tree-sitter-rust = { workspace = true, optional = true }
tree-sitter-typescript = { workspace = true, optional = true }
unindent = { workspace = true, optional = true }
ui.workspace = true
url.workspace = true
util.workspace = true

View File

@@ -230,7 +230,11 @@ gpui::actions!(
ExpandMacroRecursively,
FindAllReferences,
Fold,
FoldAll,
FoldRecursive,
FoldSelectedRanges,
ToggleFold,
ToggleFoldRecursive,
Format,
GoToDeclaration,
GoToDeclarationSplit,
@@ -340,7 +344,9 @@ gpui::actions!(
Transpose,
Undo,
UndoSelection,
UnfoldAll,
UnfoldLines,
UnfoldRecursive,
UniqueLinesCaseInsensitive,
UniqueLinesCaseSensitive,
]

View File

@@ -1360,7 +1360,7 @@ impl<'a> Iterator for BlockBufferRows<'a> {
impl sum_tree::Item for Transform {
type Summary = TransformSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &()) -> Self::Summary {
self.summary.clone()
}
}

View File

@@ -291,7 +291,7 @@ impl sum_tree::Summary for ItemSummary {
impl sum_tree::Item for CreaseItem {
type Summary = ItemSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &MultiBufferSnapshot) -> Self::Summary {
ItemSummary {
range: self.crease.range.clone(),
}

View File

@@ -944,7 +944,7 @@ struct TransformSummary {
impl sum_tree::Item for Transform {
type Summary = TransformSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &()) -> Self::Summary {
self.summary.clone()
}
}
@@ -1004,7 +1004,7 @@ impl Default for FoldRange {
impl sum_tree::Item for Fold {
type Summary = FoldSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &MultiBufferSnapshot) -> Self::Summary {
FoldSummary {
start: self.range.start,
end: self.range.end,

View File

@@ -74,7 +74,7 @@ impl Inlay {
impl sum_tree::Item for Transform {
type Summary = TransformSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &()) -> Self::Summary {
match self {
Transform::Isomorphic(summary) => TransformSummary {
input: summary.clone(),

View File

@@ -917,7 +917,7 @@ impl Transform {
impl sum_tree::Item for Transform {
type Summary = TransformSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &()) -> Self::Summary {
self.summary.clone()
}
}

View File

@@ -98,7 +98,9 @@ use language::{
};
use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
use linked_editing_ranges::refresh_linked_ranges;
use proposed_changes_editor::{ProposedChangesBuffer, ProposedChangesEditor};
pub use proposed_changes_editor::{
ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
};
use similar::{ChangeTag, TextDiff};
use task::{ResolvedTask, TaskTemplate, TaskVariables};
@@ -154,7 +156,7 @@ use theme::{
};
use ui::{
h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
ListItem, Popover, Tooltip,
ListItem, Popover, PopoverMenuHandle, Tooltip,
};
use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
use workspace::item::{ItemHandle, PreviewTabsSettings};
@@ -374,12 +376,20 @@ pub enum EditorMode {
Full,
}
#[derive(Clone, Debug)]
#[derive(Copy, Clone, Debug)]
pub enum SoftWrap {
/// Prefer not to wrap at all.
///
/// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
/// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
GitDiff,
/// Prefer a single line generally, unless an overly long line is encountered.
None,
PreferLine,
/// Soft wrap lines that exceed the editor width.
EditorWidth,
/// Soft wrap lines at the preferred line length.
Column(u32),
/// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
Bounded(u32),
}
@@ -562,6 +572,7 @@ pub struct Editor {
nav_history: Option<ItemNavHistory>,
context_menu: RwLock<Option<ContextMenu>>,
mouse_context_menu: Option<MouseContextMenu>,
hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
signature_help_state: SignatureHelpState,
auto_signature_help: Option<bool>,
@@ -660,7 +671,7 @@ pub struct EditorSnapshot {
show_git_diff_gutter: Option<bool>,
show_code_actions: Option<bool>,
show_runnables: Option<bool>,
render_git_blame_gutter: bool,
git_blame_gutter_max_author_length: Option<usize>,
pub display_snapshot: DisplaySnapshot,
pub placeholder_text: Option<Arc<str>>,
is_focused: bool,
@@ -670,7 +681,7 @@ pub struct EditorSnapshot {
gutter_hovered: bool,
}
const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
#[derive(Default, Debug, Clone, Copy)]
pub struct GutterDimensions {
@@ -810,8 +821,8 @@ impl SelectionHistory {
struct RowHighlight {
index: usize,
range: RangeInclusive<Anchor>,
color: Option<Hsla>,
range: Range<Anchor>,
color: Hsla,
should_autoscroll: bool,
}
@@ -1834,7 +1845,7 @@ impl Editor {
let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
.then(|| language_settings::SoftWrap::PreferLine);
.then(|| language_settings::SoftWrap::None);
let mut project_subscriptions = Vec::new();
if mode == EditorMode::Full {
@@ -1938,6 +1949,7 @@ impl Editor {
nav_history: None,
context_menu: RwLock::new(None),
mouse_context_menu: None,
hunk_controls_menu_handle: PopoverMenuHandle::default(),
completion_tasks: Default::default(),
signature_help_state: SignatureHelpState::default(),
auto_signature_help: None,
@@ -2207,6 +2219,19 @@ impl Editor {
}
pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
let git_blame_gutter_max_author_length = self
.render_git_blame_gutter(cx)
.then(|| {
if let Some(blame) = self.blame.as_ref() {
let max_author_length =
blame.update(cx, |blame, cx| blame.max_author_length(cx));
Some(max_author_length)
} else {
None
}
})
.flatten();
EditorSnapshot {
mode: self.mode,
show_gutter: self.show_gutter,
@@ -2214,7 +2239,7 @@ impl Editor {
show_git_diff_gutter: self.show_git_diff_gutter,
show_code_actions: self.show_code_actions,
show_runnables: self.show_runnables,
render_git_blame_gutter: self.render_git_blame_gutter(cx),
git_blame_gutter_max_author_length,
display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
scroll_anchor: self.scroll_manager.anchor(),
ongoing_scroll: self.scroll_manager.ongoing_scroll(),
@@ -3438,7 +3463,7 @@ impl Editor {
s.select(new_selections)
});
if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
if !bracket_inserted {
if let Some(on_type_format_task) =
this.trigger_on_type_formatting(text.to_string(), cx)
{
@@ -4187,6 +4212,15 @@ impl Editor {
.read(cx)
.text_anchor_for_position(position, cx)?;
let settings = language_settings::language_settings(
buffer.read(cx).language_at(buffer_position).as_ref(),
buffer.read(cx).file(),
cx,
);
if !settings.use_on_type_format {
return None;
}
// OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
// hence we do LSP request & edit on host side only — add formats to host's history.
let push_to_lsp_host_history = true;
@@ -5334,6 +5368,19 @@ impl Editor {
.icon_size(IconSize::XSmall)
.icon_color(Color::Muted)
.selected(is_active)
.tooltip({
let focus_handle = self.focus_handle.clone();
move |cx| {
Tooltip::for_action_in(
"Toggle Code Actions",
&ToggleCodeActions {
deployed_from_indicator: None,
},
&focus_handle,
cx,
)
}
})
.on_click(cx.listener(move |editor, _e, cx| {
editor.focus(cx);
editor.toggle_code_actions(
@@ -5383,23 +5430,6 @@ impl Editor {
}))
}
fn close_hunk_diff_button(
&self,
hunk: HoveredHunk,
row: DisplayRow,
cx: &mut ViewContext<Self>,
) -> IconButton {
IconButton::new(
("close_hunk_diff_indicator", row.0 as usize),
ui::IconName::Close,
)
.shape(ui::IconButtonShape::Square)
.icon_size(IconSize::XSmall)
.icon_color(Color::Muted)
.tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
.on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
}
pub fn context_menu_visible(&self) -> bool {
self.context_menu
.read()
@@ -9335,32 +9365,42 @@ impl Editor {
}
}
fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
let snapshot = self
.display_map
.update(cx, |display_map, cx| display_map.snapshot(cx));
let selection = self.selections.newest::<Point>(cx);
self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
}
if !self.seek_in_direction(
&snapshot,
selection.head(),
fn go_to_hunk_after_position(
&mut self,
snapshot: &DisplaySnapshot,
position: Point,
cx: &mut ViewContext<'_, Editor>,
) -> Option<MultiBufferDiffHunk> {
if let Some(hunk) = self.go_to_next_hunk_in_direction(
snapshot,
position,
false,
snapshot.buffer_snapshot.git_diff_hunks_in_range(
MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
),
snapshot
.buffer_snapshot
.git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
cx,
) {
let wrapped_point = Point::zero();
self.seek_in_direction(
&snapshot,
wrapped_point,
true,
snapshot.buffer_snapshot.git_diff_hunks_in_range(
MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
),
cx,
);
return Some(hunk);
}
let wrapped_point = Point::zero();
self.go_to_next_hunk_in_direction(
snapshot,
wrapped_point,
true,
snapshot.buffer_snapshot.git_diff_hunks_in_range(
MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
),
cx,
)
}
fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
@@ -9369,52 +9409,65 @@ impl Editor {
.update(cx, |display_map, cx| display_map.snapshot(cx));
let selection = self.selections.newest::<Point>(cx);
if !self.seek_in_direction(
&snapshot,
selection.head(),
false,
snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
MultiBufferRow(0)..MultiBufferRow(selection.head().row),
),
cx,
) {
let wrapped_point = snapshot.buffer_snapshot.max_point();
self.seek_in_direction(
&snapshot,
wrapped_point,
true,
snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
),
cx,
);
}
self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
}
fn seek_in_direction(
fn go_to_hunk_before_position(
&mut self,
snapshot: &DisplaySnapshot,
position: Point,
cx: &mut ViewContext<'_, Editor>,
) -> Option<MultiBufferDiffHunk> {
if let Some(hunk) = self.go_to_next_hunk_in_direction(
snapshot,
position,
false,
snapshot
.buffer_snapshot
.git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
cx,
) {
return Some(hunk);
}
let wrapped_point = snapshot.buffer_snapshot.max_point();
self.go_to_next_hunk_in_direction(
snapshot,
wrapped_point,
true,
snapshot
.buffer_snapshot
.git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
cx,
)
}
fn go_to_next_hunk_in_direction(
&mut self,
snapshot: &DisplaySnapshot,
initial_point: Point,
is_wrapped: bool,
hunks: impl Iterator<Item = MultiBufferDiffHunk>,
cx: &mut ViewContext<Editor>,
) -> bool {
) -> Option<MultiBufferDiffHunk> {
let display_point = initial_point.to_display_point(snapshot);
let mut hunks = hunks
.map(|hunk| diff_hunk_to_display(&hunk, snapshot))
.filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
.map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
.filter(|(display_hunk, _)| {
is_wrapped || !display_hunk.contains_display_row(display_point.row())
})
.dedup();
if let Some(hunk) = hunks.next() {
if let Some((display_hunk, hunk)) = hunks.next() {
self.change_selections(Some(Autoscroll::fit()), cx, |s| {
let row = hunk.start_display_row();
let row = display_hunk.start_display_row();
let point = DisplayPoint::new(row, 0);
s.select_display_ranges([point..point]);
});
true
Some(hunk)
} else {
false
None
}
}
@@ -9657,7 +9710,7 @@ impl Editor {
if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
let buffer = target.buffer.read(cx);
let range = check_multiline_range(buffer, range);
editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.select_ranges([range]);
});
} else {
@@ -10511,17 +10564,79 @@ impl Editor {
}
}
pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
let mut fold_ranges = Vec::new();
pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
let selection = self.selections.newest::<Point>(cx);
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
let range = if selection.is_empty() {
let point = selection.head().to_display_point(&display_map);
let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
.to_point(&display_map);
start..end
} else {
selection.range()
};
if display_map.folds_in_range(range).next().is_some() {
self.unfold_lines(&Default::default(), cx)
} else {
self.fold(&Default::default(), cx)
}
}
pub fn toggle_fold_recursive(
&mut self,
_: &actions::ToggleFoldRecursive,
cx: &mut ViewContext<Self>,
) {
let selection = self.selections.newest::<Point>(cx);
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
let range = if selection.is_empty() {
let point = selection.head().to_display_point(&display_map);
let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
.to_point(&display_map);
start..end
} else {
selection.range()
};
if display_map.folds_in_range(range).next().is_some() {
self.unfold_recursive(&Default::default(), cx)
} else {
self.fold_recursive(&Default::default(), cx)
}
}
pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
let mut fold_ranges = Vec::new();
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
let selections = self.selections.all_adjusted(cx);
for selection in selections {
let range = selection.range().sorted();
let buffer_start_row = range.start.row;
for row in (0..=range.end.row).rev() {
if range.start.row != range.end.row {
let mut found = false;
let mut row = range.start.row;
while row <= range.end.row {
if let Some((foldable_range, fold_text)) =
{ display_map.foldable_range(MultiBufferRow(row)) }
{
found = true;
row = foldable_range.end.row + 1;
fold_ranges.push((foldable_range, fold_text));
} else {
row += 1
}
}
if found {
continue;
}
}
for row in (0..=range.start.row).rev() {
if let Some((foldable_range, fold_text)) =
display_map.foldable_range(MultiBufferRow(row))
{
@@ -10538,6 +10653,61 @@ impl Editor {
self.fold_ranges(fold_ranges, true, cx);
}
pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
let mut fold_ranges = Vec::new();
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
for row in 0..display_map.max_buffer_row().0 {
if let Some((foldable_range, fold_text)) =
display_map.foldable_range(MultiBufferRow(row))
{
fold_ranges.push((foldable_range, fold_text));
}
}
self.fold_ranges(fold_ranges, true, cx);
}
pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
let mut fold_ranges = Vec::new();
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
let selections = self.selections.all_adjusted(cx);
for selection in selections {
let range = selection.range().sorted();
let buffer_start_row = range.start.row;
if range.start.row != range.end.row {
let mut found = false;
for row in range.start.row..=range.end.row {
if let Some((foldable_range, fold_text)) =
{ display_map.foldable_range(MultiBufferRow(row)) }
{
found = true;
fold_ranges.push((foldable_range, fold_text));
}
}
if found {
continue;
}
}
for row in (0..=range.start.row).rev() {
if let Some((foldable_range, fold_text)) =
display_map.foldable_range(MultiBufferRow(row))
{
if foldable_range.end.row >= buffer_start_row {
fold_ranges.push((foldable_range, fold_text));
} else {
break;
}
}
}
}
self.fold_ranges(fold_ranges, true, cx);
}
pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
let buffer_row = fold_at.buffer_row;
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
@@ -10572,6 +10742,24 @@ impl Editor {
self.unfold_ranges(ranges, true, true, cx);
}
pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
let selections = self.selections.all::<Point>(cx);
let ranges = selections
.iter()
.map(|s| {
let mut range = s.display_range(&display_map).sorted();
*range.start.column_mut() = 0;
*range.end.column_mut() = display_map.line_len(range.end.row());
let start = range.start.to_point(&display_map);
let end = range.end.to_point(&display_map);
start..end
})
.collect::<Vec<_>>();
self.unfold_ranges(ranges, true, true, cx);
}
pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
@@ -10590,6 +10778,16 @@ impl Editor {
self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
}
pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
self.unfold_ranges(
[Point::zero()..display_map.max_point().to_point(&display_map)],
true,
true,
cx,
);
}
pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
let selections = self.selections.all::<Point>(cx);
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
@@ -10866,8 +11064,9 @@ impl Editor {
let settings = self.buffer.read(cx).settings_at(0, cx);
let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
match mode {
language_settings::SoftWrap::None => SoftWrap::None,
language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
SoftWrap::None
}
language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
language_settings::SoftWrap::PreferredLineLength => {
SoftWrap::Column(settings.preferred_line_length)
@@ -10915,9 +11114,10 @@ impl Editor {
self.soft_wrap_mode_override.take();
} else {
let soft_wrap = match self.soft_wrap_mode(cx) {
SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
SoftWrap::GitDiff => return,
SoftWrap::None => language_settings::SoftWrap::EditorWidth,
SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
language_settings::SoftWrap::PreferLine
language_settings::SoftWrap::None
}
};
self.soft_wrap_mode_override = Some(soft_wrap);
@@ -11313,56 +11513,130 @@ impl Editor {
}
}
/// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
/// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
/// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
/// Adds a row highlight for the given range. If a row has multiple highlights, the
/// last highlight added will be used.
///
/// If the range ends at the beginning of a line, then that line will not be highlighted.
pub fn highlight_rows<T: 'static>(
&mut self,
rows: RangeInclusive<Anchor>,
color: Option<Hsla>,
range: Range<Anchor>,
color: Hsla,
should_autoscroll: bool,
cx: &mut ViewContext<Self>,
) {
let snapshot = self.buffer().read(cx).snapshot(cx);
let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
highlight
.range
.start()
.cmp(rows.start(), &snapshot)
.then(highlight.range.end().cmp(rows.end(), &snapshot))
let ix = row_highlights.binary_search_by(|highlight| {
Ordering::Equal
.then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
.then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
});
match (color, existing_highlight_index) {
(Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
ix,
RowHighlight {
index: post_inc(&mut self.highlight_order),
range: rows,
should_autoscroll,
color,
},
),
(None, Ok(i)) => {
row_highlights.remove(i);
if let Err(mut ix) = ix {
let index = post_inc(&mut self.highlight_order);
// If this range intersects with the preceding highlight, then merge it with
// the preceding highlight. Otherwise insert a new highlight.
let mut merged = false;
if ix > 0 {
let prev_highlight = &mut row_highlights[ix - 1];
if prev_highlight
.range
.end
.cmp(&range.start, &snapshot)
.is_ge()
{
ix -= 1;
if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
prev_highlight.range.end = range.end;
}
merged = true;
prev_highlight.index = index;
prev_highlight.color = color;
prev_highlight.should_autoscroll = should_autoscroll;
}
}
if !merged {
row_highlights.insert(
ix,
RowHighlight {
range: range.clone(),
index,
color,
should_autoscroll,
},
);
}
// If any of the following highlights intersect with this one, merge them.
while let Some(next_highlight) = row_highlights.get(ix + 1) {
let highlight = &row_highlights[ix];
if next_highlight
.range
.start
.cmp(&highlight.range.end, &snapshot)
.is_le()
{
if next_highlight
.range
.end
.cmp(&highlight.range.end, &snapshot)
.is_gt()
{
row_highlights[ix].range.end = next_highlight.range.end;
}
row_highlights.remove(ix + 1);
} else {
break;
}
}
}
}
/// Remove any highlighted row ranges of the given type that intersect the
/// given ranges.
pub fn remove_highlighted_rows<T: 'static>(
&mut self,
ranges_to_remove: Vec<Range<Anchor>>,
cx: &mut ViewContext<Self>,
) {
let snapshot = self.buffer().read(cx).snapshot(cx);
let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
let mut ranges_to_remove = ranges_to_remove.iter().peekable();
row_highlights.retain(|highlight| {
while let Some(range_to_remove) = ranges_to_remove.peek() {
match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
Ordering::Less | Ordering::Equal => {
ranges_to_remove.next();
}
Ordering::Greater => {
match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
Ordering::Less | Ordering::Equal => {
return false;
}
Ordering::Greater => break,
}
}
}
}
true
})
}
/// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
pub fn clear_row_highlights<T: 'static>(&mut self) {
self.highlighted_rows.remove(&TypeId::of::<T>());
}
/// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
pub fn highlighted_rows<T: 'static>(
&self,
) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
Some(
self.highlighted_rows
.get(&TypeId::of::<T>())?
.iter()
.map(|highlight| (&highlight.range, highlight.color.as_ref())),
)
pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
self.highlighted_rows
.get(&TypeId::of::<T>())
.map_or(&[] as &[_], |vec| vec.as_slice())
.iter()
.map(|highlight| (highlight.range.clone(), highlight.color))
}
/// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
@@ -11380,17 +11654,22 @@ impl Editor {
.fold(
BTreeMap::<DisplayRow, Hsla>::new(),
|mut unique_rows, highlight| {
let start_row = highlight.range.start().to_display_point(&snapshot).row();
let end_row = highlight.range.end().to_display_point(&snapshot).row();
for row in start_row.0..=end_row.0 {
let start = highlight.range.start.to_display_point(&snapshot);
let end = highlight.range.end.to_display_point(&snapshot);
let start_row = start.row().0;
let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
&& end.column() == 0
{
end.row().0.saturating_sub(1)
} else {
end.row().0
};
for row in start_row..=end_row {
let used_index =
used_highlight_orders.entry(row).or_insert(highlight.index);
if highlight.index >= *used_index {
*used_index = highlight.index;
match highlight.color {
Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
None => unique_rows.remove(&DisplayRow(row)),
};
unique_rows.insert(DisplayRow(row), highlight.color);
}
}
unique_rows
@@ -11406,10 +11685,11 @@ impl Editor {
.values()
.flat_map(|highlighted_rows| highlighted_rows.iter())
.filter_map(|highlight| {
if highlight.color.is_none() || !highlight.should_autoscroll {
return None;
if highlight.should_autoscroll {
Some(highlight.range.start.to_display_point(snapshot).row())
} else {
None
}
Some(highlight.range.start().to_display_point(snapshot).row())
})
.min()
}
@@ -11915,12 +12195,19 @@ impl Editor {
)),
cx,
);
let editor_settings = EditorSettings::get_global(cx);
if let Some(cursor_shape) = editor_settings.cursor_shape {
self.cursor_shape = cursor_shape;
let old_cursor_shape = self.cursor_shape;
{
let editor_settings = EditorSettings::get_global(cx);
self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
}
if old_cursor_shape != self.cursor_shape {
cx.emit(EditorEvent::CursorShapeChanged);
}
self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
let project_settings = ProjectSettings::get_global(cx);
self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
@@ -12930,6 +13217,7 @@ impl EditorSnapshot {
font_id: FontId,
font_size: Pixels,
em_width: Pixels,
em_advance: Pixels,
max_line_number_width: Pixels,
cx: &AppContext,
) -> GutterDimensions {
@@ -12950,7 +13238,7 @@ impl EditorSnapshot {
.unwrap_or(gutter_settings.line_numbers);
let line_gutter_width = if show_line_numbers {
// Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
let min_width_for_number_on_gutter = em_width * 4.0;
let min_width_for_number_on_gutter = em_advance * 4.0;
max_line_number_width.max(min_width_for_number_on_gutter)
} else {
0.0.into()
@@ -12962,9 +13250,19 @@ impl EditorSnapshot {
let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
let git_blame_entries_width = self
.render_git_blame_gutter
.then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
let git_blame_entries_width =
self.git_blame_gutter_max_author_length
.map(|max_author_length| {
// Length of the author name, but also space for the commit hash,
// the spacing and the timestamp.
let max_char_count = max_author_length
.min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
+ 7 // length of commit sha
+ 14 // length of max relative timestamp ("60 minutes ago")
+ 4; // gaps and margins
em_advance * max_char_count
});
let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
left_padding += if show_code_actions || show_runnables {
@@ -13117,6 +13415,7 @@ pub enum EditorEvent {
TransactionBegun {
transaction_id: clock::Lamport,
},
CursorShapeChanged,
}
impl EventEmitter<EditorEvent> for Editor {}

View File

@@ -13,7 +13,6 @@ pub struct EditorSettings {
pub show_completions_on_input: bool,
pub show_completion_documentation: bool,
pub completion_documentation_secondary_query_debounce: u64,
pub use_on_type_format: bool,
pub toolbar: Toolbar,
pub scrollbar: Scrollbar,
pub gutter: Gutter,
@@ -209,11 +208,6 @@ pub struct EditorSettingsContent {
///
/// Default: 300 ms
pub completion_documentation_secondary_query_debounce: Option<u64>,
/// Whether to use additional LSP queries to format (and amend) the code after
/// every "trigger" symbol input, defined by LSP server capabilities.
///
/// Default: true
pub use_on_type_format: Option<bool>,
/// Toolbar related settings
pub toolbar: Option<ToolbarContent>,
/// Scrollbar related settings

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,7 @@ use crate::{
hover_popover::{
self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
},
hunk_diff::{diff_hunk_to_display, DisplayDiffHunk, ExpandedHunk},
hunk_diff::{diff_hunk_to_display, DisplayDiffHunk},
hunk_status,
items::BufferSearchHighlights,
mouse_context_menu::{self, MenuPosition, MouseContextMenu},
@@ -20,8 +20,8 @@ use crate::{
DocumentHighlightRead, DocumentHighlightWrite, Editor, EditorMode, EditorSettings,
EditorSnapshot, EditorStyle, ExpandExcerpts, FocusedBlock, GutterDimensions, HalfPageDown,
HalfPageUp, HandleInput, HoveredCursor, HoveredHunk, LineDown, LineUp, OpenExcerpts, PageDown,
PageUp, Point, RangeToAnchorExt, RowExt, RowRangeExt, SelectPhase, Selection, SoftWrap,
ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
PageUp, Point, RowExt, RowRangeExt, SelectPhase, Selection, SoftWrap, ToPoint,
CURSORS_VISIBLE_FOR, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED, MAX_LINE_LEN,
};
use client::ParticipantIndex;
use collections::{BTreeMap, HashMap};
@@ -302,7 +302,7 @@ impl EditorElement {
}
register_action(view, cx, Editor::go_to_diagnostic);
register_action(view, cx, Editor::go_to_prev_diagnostic);
register_action(view, cx, Editor::go_to_hunk);
register_action(view, cx, Editor::go_to_next_hunk);
register_action(view, cx, Editor::go_to_prev_hunk);
register_action(view, cx, |editor, a, cx| {
editor.go_to_definition(a, cx).detach_and_log_err(cx);
@@ -335,8 +335,14 @@ impl EditorElement {
register_action(view, cx, Editor::open_url);
register_action(view, cx, Editor::open_file);
register_action(view, cx, Editor::fold);
register_action(view, cx, Editor::fold_all);
register_action(view, cx, Editor::fold_at);
register_action(view, cx, Editor::fold_recursive);
register_action(view, cx, Editor::toggle_fold);
register_action(view, cx, Editor::toggle_fold_recursive);
register_action(view, cx, Editor::unfold_lines);
register_action(view, cx, Editor::unfold_recursive);
register_action(view, cx, Editor::unfold_all);
register_action(view, cx, Editor::unfold_at);
register_action(view, cx, Editor::fold_selected_ranges);
register_action(view, cx, Editor::show_completions);
@@ -489,28 +495,7 @@ impl EditorElement {
let mut modifiers = event.modifiers;
if let Some(hovered_hunk) = hovered_hunk {
if modifiers.control || modifiers.platform {
editor.toggle_hovered_hunk(&hovered_hunk, cx);
} else {
let display_range = hovered_hunk
.multi_buffer_range
.clone()
.to_display_points(&position_map.snapshot);
let hunk_bounds = Self::diff_hunk_bounds(
&position_map.snapshot,
position_map.line_height,
gutter_hitbox.bounds,
&DisplayDiffHunk::Unfolded {
diff_base_byte_range: hovered_hunk.diff_base_byte_range.clone(),
display_row_range: display_range.start.row()..display_range.end.row(),
multi_buffer_range: hovered_hunk.multi_buffer_range.clone(),
status: hovered_hunk.status,
},
);
if hunk_bounds.contains(&event.position) {
editor.open_hunk_context_menu(hovered_hunk, event.position, cx);
}
}
editor.toggle_hovered_hunk(&hovered_hunk, cx);
cx.notify();
return;
} else if gutter_hitbox.is_hovered(cx) {
@@ -651,11 +636,30 @@ impl EditorElement {
cx.stop_propagation();
} else if end_selection && pending_nonempty_selections {
cx.stop_propagation();
} else if cfg!(target_os = "linux")
&& event.button == MouseButton::Middle
&& (!text_hitbox.is_hovered(cx) || editor.read_only(cx))
{
return;
} else if cfg!(target_os = "linux") && event.button == MouseButton::Middle {
if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
return;
}
#[cfg(target_os = "linux")]
if EditorSettings::get_global(cx).middle_click_paste {
if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
let point_for_position =
position_map.point_for_position(text_hitbox.bounds, event.position);
let position = point_for_position.previous_valid;
editor.select(
SelectPhase::Begin {
position,
add: false,
click_count: 1,
},
cx,
);
editor.insert(&text, cx);
}
cx.stop_propagation()
}
}
}
@@ -1303,13 +1307,13 @@ impl EditorElement {
let display_hunks = buffer_snapshot
.git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
.filter_map(|hunk| {
let mut display_hunk = diff_hunk_to_display(&hunk, snapshot);
let display_hunk = diff_hunk_to_display(&hunk, snapshot);
if let DisplayDiffHunk::Unfolded {
multi_buffer_range,
status,
..
} = &mut display_hunk
} = &display_hunk
{
let mut is_expanded = false;
while let Some(expanded_hunk) = expanded_hunks.peek() {
@@ -1332,11 +1336,7 @@ impl EditorElement {
}
match status {
DiffHunkStatus::Added => {}
DiffHunkStatus::Modified => {
if is_expanded {
*status = DiffHunkStatus::Added;
}
}
DiffHunkStatus::Modified => {}
DiffHunkStatus::Removed => {
if is_expanded {
return None;
@@ -1470,7 +1470,7 @@ impl EditorElement {
AvailableSpace::MaxContent
};
let scroll_top = scroll_position.y * line_height;
let start_x = em_width * 1;
let start_x = em_width;
let mut last_used_color: Option<(PlayerColor, Oid)> = None;
@@ -1665,7 +1665,16 @@ impl EditorElement {
return None;
}
if snapshot.is_line_folded(multibuffer_row) {
return None;
// Skip folded indicators, unless it's the starting line of a fold.
if multibuffer_row
.0
.checked_sub(1)
.map_or(false, |previous_row| {
snapshot.is_line_folded(MultiBufferRow(previous_row))
})
{
return None;
}
}
let button = editor.render_run_indicator(
&self.style,
@@ -3371,9 +3380,6 @@ impl EditorElement {
for test_indicator in layout.test_indicators.iter_mut() {
test_indicator.paint(cx);
}
for close_indicator in layout.close_indicators.iter_mut() {
close_indicator.paint(cx);
}
if let Some(indicator) = layout.code_actions_indicator.as_mut() {
indicator.paint(cx);
@@ -4159,46 +4165,6 @@ impl EditorElement {
+ 1;
self.column_pixels(digit_count, cx)
}
#[allow(clippy::too_many_arguments)]
fn layout_hunk_diff_close_indicators(
&self,
line_height: Pixels,
scroll_pixel_position: gpui::Point<Pixels>,
gutter_dimensions: &GutterDimensions,
gutter_hitbox: &Hitbox,
rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
expanded_hunks_by_rows: HashMap<DisplayRow, ExpandedHunk>,
cx: &mut WindowContext,
) -> Vec<AnyElement> {
self.editor.update(cx, |editor, cx| {
expanded_hunks_by_rows
.into_iter()
.map(|(display_row, hunk)| {
let button = editor.close_hunk_diff_button(
HoveredHunk {
multi_buffer_range: hunk.hunk_range,
status: hunk.status,
diff_base_byte_range: hunk.diff_base_byte_range,
},
display_row,
cx,
);
prepaint_gutter_button(
button,
display_row,
line_height,
gutter_dimensions,
scroll_pixel_position,
gutter_hitbox,
rows_with_hunk_bounds,
cx,
)
})
.collect()
})
}
}
#[allow(clippy::too_many_arguments)]
@@ -4296,7 +4262,7 @@ fn render_blame_entry(
let short_commit_id = blame_entry.sha.display_short();
let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
let name = util::truncate_and_trailoff(author_name, 20);
let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
let details = blame.read(cx).details_for_entry(&blame_entry);
@@ -4308,22 +4274,21 @@ fn render_blame_entry(
h_flex()
.w_full()
.justify_between()
.font_family(style.text.font().family)
.line_height(style.text.line_height)
.id(("blame", ix))
.children([
div()
.text_color(sha_color.cursor)
.child(short_commit_id)
.mr_2(),
div()
.w_full()
.h_flex()
.justify_between()
.text_color(cx.theme().status().hint)
.child(name)
.child(relative_timestamp),
])
.text_color(cx.theme().status().hint)
.pr_2()
.gap_2()
.child(
h_flex()
.items_center()
.gap_2()
.child(div().text_color(sha_color.cursor).child(short_commit_id))
.child(name),
)
.child(relative_timestamp)
.on_mouse_down(MouseButton::Right, {
let blame_entry = blame_entry.clone();
let details = details.clone();
@@ -5038,6 +5003,7 @@ impl Element for EditorElement {
font_id,
font_size,
em_width,
em_advance,
self.max_line_number_width(&snapshot, cx),
cx,
);
@@ -5062,10 +5028,8 @@ impl Element for EditorElement {
snapshot
} else {
let wrap_width = match editor.soft_wrap_mode(cx) {
SoftWrap::None => None,
SoftWrap::PreferLine => {
Some((MAX_LINE_LEN / 2) as f32 * em_advance)
}
SoftWrap::GitDiff => None,
SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
SoftWrap::EditorWidth => Some(editor_width),
SoftWrap::Column(column) => Some(column as f32 * em_advance),
SoftWrap::Bounded(column) => {
@@ -5549,15 +5513,6 @@ impl Element for EditorElement {
} else {
Vec::new()
};
let close_indicators = self.layout_hunk_diff_close_indicators(
line_height,
scroll_pixel_position,
&gutter_dimensions,
&gutter_hitbox,
&rows_with_hunk_bounds,
expanded_add_hunks_by_rows,
cx,
);
self.layout_signature_help(
&hitbox,
@@ -5670,7 +5625,6 @@ impl Element for EditorElement {
selections,
mouse_context_menu,
test_indicators,
close_indicators,
code_actions_indicator,
gutter_fold_toggles,
crease_trailers,
@@ -5812,7 +5766,6 @@ pub struct EditorLayout {
selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
code_actions_indicator: Option<AnyElement>,
test_indicators: Vec<AnyElement>,
close_indicators: Vec<AnyElement>,
gutter_fold_toggles: Vec<Option<AnyElement>>,
crease_trailers: Vec<Option<CreaseTrailerLayout>>,
mouse_context_menu: Option<AnyElement>,
@@ -6362,10 +6315,21 @@ fn compute_auto_height_layout(
.unwrap()
.size
.width;
let em_advance = cx
.text_system()
.advance(font_id, font_size, 'm')
.unwrap()
.width;
let mut snapshot = editor.snapshot(cx);
let gutter_dimensions =
snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
let gutter_dimensions = snapshot.gutter_dimensions(
font_id,
font_size,
em_width,
em_advance,
max_line_number_width,
cx,
);
editor.gutter_dimensions = gutter_dimensions;
let text_width = width - gutter_dimensions.width;

View File

@@ -29,7 +29,7 @@ pub struct GitBlameEntrySummary {
impl sum_tree::Item for GitBlameEntry {
type Summary = GitBlameEntrySummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &()) -> Self::Summary {
GitBlameEntrySummary { rows: self.rows }
}
}
@@ -207,6 +207,27 @@ impl GitBlame {
})
}
pub fn max_author_length(&mut self, cx: &mut ModelContext<Self>) -> usize {
self.sync(cx);
let mut max_author_length = 0;
for entry in self.entries.iter() {
let author_len = entry
.blame
.as_ref()
.and_then(|entry| entry.author.as_ref())
.map(|author| author.len());
if let Some(author_len) = author_len {
if author_len > max_author_length {
max_author_length = author_len;
}
}
}
max_author_length
}
pub fn blur(&mut self, _: &mut ModelContext<Self>) {
self.focused = false;
}

View File

@@ -32,7 +32,7 @@ pub fn refresh_matching_bracket_highlights(editor: &mut Editor, cx: &mut ViewCon
opening_range.to_anchors(&snapshot.buffer_snapshot),
closing_range.to_anchors(&snapshot.buffer_snapshot),
],
|theme| theme.editor_document_highlight_read_background,
|theme| theme.editor_document_highlight_bracket_background,
cx,
)
}

View File

@@ -1,28 +1,23 @@
use collections::{hash_map, HashMap, HashSet};
use git::diff::DiffHunkStatus;
use gpui::{Action, AppContext, CursorStyle, Hsla, Model, MouseButton, Subscription, Task, View};
use gpui::{Action, AnchorCorner, AppContext, CursorStyle, Hsla, Model, MouseButton, Task, View};
use language::{Buffer, BufferId, Point};
use multi_buffer::{
Anchor, AnchorRangeExt, ExcerptRange, MultiBuffer, MultiBufferDiffHunk, MultiBufferRow,
MultiBufferSnapshot, ToPoint,
};
use settings::SettingsStore;
use std::{
ops::{Range, RangeInclusive},
sync::Arc,
};
use std::{ops::Range, sync::Arc};
use ui::{
prelude::*, ActiveTheme, ContextMenu, InteractiveElement, IntoElement, ParentElement, Pixels,
Styled, ViewContext, VisualContext,
prelude::*, ActiveTheme, ContextMenu, IconButtonShape, InteractiveElement, IntoElement,
ParentElement, PopoverMenu, Styled, Tooltip, ViewContext, VisualContext,
};
use util::{debug_panic, RangeExt};
use util::RangeExt;
use crate::{
editor_settings::CurrentLineHighlight, hunk_status, hunks_for_selections,
mouse_context_menu::MouseContextMenu, BlockDisposition, BlockProperties, BlockStyle,
CustomBlockId, DiffRowHighlight, DisplayRow, DisplaySnapshot, Editor, EditorElement,
EditorSnapshot, ExpandAllHunkDiffs, RangeToAnchorExt, RevertFile, RevertSelectedHunks,
ToDisplayPoint, ToggleHunkDiff,
editor_settings::CurrentLineHighlight, hunk_status, hunks_for_selections, BlockDisposition,
BlockProperties, BlockStyle, CustomBlockId, DiffRowHighlight, DisplayRow, DisplaySnapshot,
Editor, EditorElement, ExpandAllHunkDiffs, GoToHunk, GoToPrevHunk, RevertFile,
RevertSelectedHunks, ToDisplayPoint, ToggleHunkDiff,
};
#[derive(Debug, Clone)]
@@ -41,7 +36,7 @@ pub(super) struct ExpandedHunks {
#[derive(Debug, Clone)]
pub(super) struct ExpandedHunk {
pub block: Option<CustomBlockId>,
pub blocks: Vec<CustomBlockId>,
pub hunk_range: Range<Anchor>,
pub diff_base_byte_range: Range<usize>,
pub status: DiffHunkStatus,
@@ -77,85 +72,6 @@ impl ExpandedHunks {
}
impl Editor {
pub(super) fn open_hunk_context_menu(
&mut self,
hovered_hunk: HoveredHunk,
clicked_point: gpui::Point<Pixels>,
cx: &mut ViewContext<Editor>,
) {
let focus_handle = self.focus_handle.clone();
let expanded = self
.expanded_hunks
.hunks(false)
.any(|expanded_hunk| expanded_hunk.hunk_range == hovered_hunk.multi_buffer_range);
let editor_handle = cx.view().clone();
let editor_snapshot = self.snapshot(cx);
let start_point = self
.to_pixel_point(hovered_hunk.multi_buffer_range.start, &editor_snapshot, cx)
.unwrap_or(clicked_point);
let end_point = self
.to_pixel_point(hovered_hunk.multi_buffer_range.start, &editor_snapshot, cx)
.unwrap_or(clicked_point);
let norm =
|a: gpui::Point<Pixels>, b: gpui::Point<Pixels>| (a.x - b.x).abs() + (a.y - b.y).abs();
let closest_source = if norm(start_point, clicked_point) < norm(end_point, clicked_point) {
hovered_hunk.multi_buffer_range.start
} else {
hovered_hunk.multi_buffer_range.end
};
self.mouse_context_menu = MouseContextMenu::pinned_to_editor(
self,
closest_source,
clicked_point,
ContextMenu::build(cx, move |menu, _| {
menu.on_blur_subscription(Subscription::new(|| {}))
.context(focus_handle)
.entry(
if expanded {
"Collapse Hunk"
} else {
"Expand Hunk"
},
Some(ToggleHunkDiff.boxed_clone()),
{
let editor = editor_handle.clone();
let hunk = hovered_hunk.clone();
move |cx| {
editor.update(cx, |editor, cx| {
editor.toggle_hovered_hunk(&hunk, cx);
});
}
},
)
.entry("Revert Hunk", Some(RevertSelectedHunks.boxed_clone()), {
let editor = editor_handle.clone();
let hunk = hovered_hunk.clone();
move |cx| {
let multi_buffer = editor.read(cx).buffer().clone();
let multi_buffer_snapshot = multi_buffer.read(cx).snapshot(cx);
let mut revert_changes = HashMap::default();
if let Some(hunk) =
crate::hunk_diff::to_diff_hunk(&hunk, &multi_buffer_snapshot)
{
Editor::prepare_revert_change(
&mut revert_changes,
&multi_buffer,
&hunk,
cx,
);
}
if !revert_changes.is_empty() {
editor.update(cx, |editor, cx| editor.revert(revert_changes, cx));
}
}
})
.action("Revert File", RevertFile.boxed_clone())
}),
cx,
)
}
pub(super) fn toggle_hovered_hunk(
&mut self,
hovered_hunk: &HoveredHunk,
@@ -264,7 +180,8 @@ impl Editor {
break;
} else if expanded_hunk_row_range == hunk_to_toggle_row_range {
highlights_to_remove.push(expanded_hunk.hunk_range.clone());
blocks_to_remove.extend(expanded_hunk.block);
blocks_to_remove
.extend(expanded_hunk.blocks.iter().copied());
hunks_to_toggle.next();
retain = false;
break;
@@ -299,14 +216,7 @@ impl Editor {
});
}
for removed_rows in highlights_to_remove {
editor.highlight_rows::<DiffRowHighlight>(
to_inclusive_row_range(removed_rows, &snapshot),
None,
false,
cx,
);
}
editor.remove_highlighted_rows::<DiffRowHighlight>(highlights_to_remove, cx);
editor.remove_blocks(blocks_to_remove, None, cx);
for hunk in hunks_to_expand {
editor.expand_diff_hunk(None, &hunk, cx);
@@ -371,33 +281,48 @@ impl Editor {
Err(ix) => ix,
};
let block = match hunk.status {
let blocks;
match hunk.status {
DiffHunkStatus::Removed => {
self.insert_deleted_text_block(diff_base_buffer, deleted_text_lines, hunk, cx)
blocks = self.insert_blocks(
[
self.hunk_header_block(&hunk, cx),
Self::deleted_text_block(hunk, diff_base_buffer, deleted_text_lines, cx),
],
None,
cx,
);
}
DiffHunkStatus::Added => {
self.highlight_rows::<DiffRowHighlight>(
to_inclusive_row_range(hunk_start..hunk_end, &snapshot),
Some(added_hunk_color(cx)),
hunk_start..hunk_end,
added_hunk_color(cx),
false,
cx,
);
None
blocks = self.insert_blocks([self.hunk_header_block(&hunk, cx)], None, cx);
}
DiffHunkStatus::Modified => {
self.highlight_rows::<DiffRowHighlight>(
to_inclusive_row_range(hunk_start..hunk_end, &snapshot),
Some(added_hunk_color(cx)),
hunk_start..hunk_end,
added_hunk_color(cx),
false,
cx,
);
self.insert_deleted_text_block(diff_base_buffer, deleted_text_lines, hunk, cx)
blocks = self.insert_blocks(
[
self.hunk_header_block(&hunk, cx),
Self::deleted_text_block(hunk, diff_base_buffer, deleted_text_lines, cx),
],
None,
cx,
);
}
};
self.expanded_hunks.hunks.insert(
block_insert_index,
ExpandedHunk {
block,
blocks,
hunk_range: hunk_start..hunk_end,
status: hunk.status,
folded: false,
@@ -408,109 +333,367 @@ impl Editor {
Some(())
}
fn insert_deleted_text_block(
&mut self,
fn hunk_header_block(
&self,
hunk: &HoveredHunk,
cx: &mut ViewContext<'_, Editor>,
) -> BlockProperties<Anchor> {
let border_color = cx.theme().colors().border_variant;
let gutter_color = match hunk.status {
DiffHunkStatus::Added => cx.theme().status().created,
DiffHunkStatus::Modified => cx.theme().status().modified,
DiffHunkStatus::Removed => cx.theme().status().deleted,
};
BlockProperties {
position: hunk.multi_buffer_range.start,
height: 1,
style: BlockStyle::Sticky,
disposition: BlockDisposition::Above,
priority: 0,
render: Box::new({
let editor = cx.view().clone();
let hunk = hunk.clone();
move |cx| {
let hunk_controls_menu_handle =
editor.read(cx).hunk_controls_menu_handle.clone();
h_flex()
.id(cx.block_id)
.h(cx.line_height())
.w_full()
.border_t_1()
.border_color(border_color)
.bg(cx.theme().colors().editor_background)
.child(
div()
.id("gutter-strip")
.w(EditorElement::diff_hunk_strip_width(cx.line_height()))
.h_full()
.bg(gutter_color)
.cursor(CursorStyle::PointingHand)
.on_click({
let editor = editor.clone();
let hunk = hunk.clone();
move |_event, cx| {
editor.update(cx, |editor, cx| {
editor.toggle_hovered_hunk(&hunk, cx);
});
}
}),
)
.child(
h_flex()
.pl_2()
.pr_6()
.size_full()
.justify_between()
.child(
h_flex()
.gap_1()
.child(
IconButton::new("next-hunk", IconName::ArrowDown)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.tooltip({
let focus_handle = editor.focus_handle(cx);
move |cx| {
Tooltip::for_action_in(
"Next Hunk",
&GoToHunk,
&focus_handle,
cx,
)
}
})
.on_click({
let editor = editor.clone();
let hunk = hunk.clone();
move |_event, cx| {
editor.update(cx, |editor, cx| {
let snapshot = editor.snapshot(cx);
let position = hunk
.multi_buffer_range
.end
.to_point(
&snapshot.buffer_snapshot,
);
if let Some(hunk) = editor
.go_to_hunk_after_position(
&snapshot, position, cx,
)
{
let multi_buffer_start = snapshot
.buffer_snapshot
.anchor_before(Point::new(
hunk.row_range.start.0,
0,
));
let multi_buffer_end = snapshot
.buffer_snapshot
.anchor_after(Point::new(
hunk.row_range.end.0,
0,
));
editor.expand_diff_hunk(
None,
&HoveredHunk {
multi_buffer_range:
multi_buffer_start
..multi_buffer_end,
status: hunk_status(&hunk),
diff_base_byte_range: hunk
.diff_base_byte_range,
},
cx,
);
}
});
}
}),
)
.child(
IconButton::new("prev-hunk", IconName::ArrowUp)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.tooltip({
let focus_handle = editor.focus_handle(cx);
move |cx| {
Tooltip::for_action_in(
"Previous Hunk",
&GoToPrevHunk,
&focus_handle,
cx,
)
}
})
.on_click({
let editor = editor.clone();
let hunk = hunk.clone();
move |_event, cx| {
editor.update(cx, |editor, cx| {
let snapshot = editor.snapshot(cx);
let position = hunk
.multi_buffer_range
.start
.to_point(
&snapshot.buffer_snapshot,
);
let hunk = editor
.go_to_hunk_before_position(
&snapshot, position, cx,
);
if let Some(hunk) = hunk {
let multi_buffer_start = snapshot
.buffer_snapshot
.anchor_before(Point::new(
hunk.row_range.start.0,
0,
));
let multi_buffer_end = snapshot
.buffer_snapshot
.anchor_after(Point::new(
hunk.row_range.end.0,
0,
));
editor.expand_diff_hunk(
None,
&HoveredHunk {
multi_buffer_range:
multi_buffer_start
..multi_buffer_end,
status: hunk_status(&hunk),
diff_base_byte_range: hunk
.diff_base_byte_range,
},
cx,
);
}
});
}
}),
)
.child(
IconButton::new("discard", IconName::Undo)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.tooltip({
let focus_handle = editor.focus_handle(cx);
move |cx| {
Tooltip::for_action_in(
"Discard Hunk",
&RevertSelectedHunks,
&focus_handle,
cx,
)
}
})
.on_click({
let editor = editor.clone();
let hunk = hunk.clone();
move |_event, cx| {
let multi_buffer =
editor.read(cx).buffer().clone();
let multi_buffer_snapshot =
multi_buffer.read(cx).snapshot(cx);
let mut revert_changes = HashMap::default();
if let Some(hunk) =
crate::hunk_diff::to_diff_hunk(
&hunk,
&multi_buffer_snapshot,
)
{
Editor::prepare_revert_change(
&mut revert_changes,
&multi_buffer,
&hunk,
cx,
);
}
if !revert_changes.is_empty() {
editor.update(cx, |editor, cx| {
editor.revert(revert_changes, cx)
});
}
}
}),
)
.child({
let focus = editor.focus_handle(cx);
PopoverMenu::new("hunk-controls-dropdown")
.trigger(
IconButton::new(
"toggle_editor_selections_icon",
IconName::EllipsisVertical,
)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.style(ButtonStyle::Subtle)
.selected(
hunk_controls_menu_handle.is_deployed(),
)
.when(
!hunk_controls_menu_handle.is_deployed(),
|this| {
this.tooltip(|cx| {
Tooltip::text("Hunk Controls", cx)
})
},
),
)
.anchor(AnchorCorner::TopRight)
.with_handle(hunk_controls_menu_handle)
.menu(move |cx| {
let focus = focus.clone();
let menu =
ContextMenu::build(cx, move |menu, _| {
menu.context(focus.clone()).action(
"Discard All",
RevertFile.boxed_clone(),
)
});
Some(menu)
})
}),
)
.child(
div().child(
IconButton::new("collapse", IconName::Close)
.shape(IconButtonShape::Square)
.icon_size(IconSize::Small)
.tooltip({
let focus_handle = editor.focus_handle(cx);
move |cx| {
Tooltip::for_action_in(
"Collapse Hunk",
&ToggleHunkDiff,
&focus_handle,
cx,
)
}
})
.on_click({
let editor = editor.clone();
let hunk = hunk.clone();
move |_event, cx| {
editor.update(cx, |editor, cx| {
editor.toggle_hovered_hunk(&hunk, cx);
});
}
}),
),
),
)
.into_any_element()
}
}),
}
}
fn deleted_text_block(
hunk: &HoveredHunk,
diff_base_buffer: Model<Buffer>,
deleted_text_height: u32,
hunk: &HoveredHunk,
cx: &mut ViewContext<'_, Self>,
) -> Option<CustomBlockId> {
cx: &mut ViewContext<'_, Editor>,
) -> BlockProperties<Anchor> {
let gutter_color = match hunk.status {
DiffHunkStatus::Added => unreachable!(),
DiffHunkStatus::Modified => cx.theme().status().modified,
DiffHunkStatus::Removed => cx.theme().status().deleted,
};
let deleted_hunk_color = deleted_hunk_color(cx);
let (editor_height, editor_with_deleted_text) =
editor_with_deleted_text(diff_base_buffer, deleted_hunk_color, hunk, cx);
let editor = cx.view().clone();
let hunk = hunk.clone();
let height = editor_height.max(deleted_text_height);
let mut new_block_ids = self.insert_blocks(
Some(BlockProperties {
position: hunk.multi_buffer_range.start,
height,
style: BlockStyle::Flex,
disposition: BlockDisposition::Above,
render: Box::new(move |cx| {
let width = EditorElement::diff_hunk_strip_width(cx.line_height());
let gutter_dimensions = editor.read(cx.context).gutter_dimensions;
BlockProperties {
position: hunk.multi_buffer_range.start,
height,
style: BlockStyle::Flex,
disposition: BlockDisposition::Above,
priority: 0,
render: Box::new(move |cx| {
let width = EditorElement::diff_hunk_strip_width(cx.line_height());
let gutter_dimensions = editor.read(cx.context).gutter_dimensions;
let close_button = editor.update(cx.context, |editor, cx| {
let editor_snapshot = editor.snapshot(cx);
let hunk_display_range = hunk
.multi_buffer_range
.clone()
.to_display_points(&editor_snapshot);
editor.close_hunk_diff_button(
hunk.clone(),
hunk_display_range.start.row(),
cx,
)
});
h_flex()
.id("gutter with editor")
.bg(deleted_hunk_color)
.h(height as f32 * cx.line_height())
.w_full()
.child(
h_flex()
.id("gutter")
.max_w(gutter_dimensions.full_width())
.min_w(gutter_dimensions.full_width())
.size_full()
.child(
h_flex()
.id("gutter hunk")
.bg(cx.theme().status().deleted)
.pl(gutter_dimensions.margin
+ gutter_dimensions
.git_blame_entries_width
.unwrap_or_default())
.max_w(width)
.min_w(width)
.size_full()
.cursor(CursorStyle::PointingHand)
.on_mouse_down(MouseButton::Left, {
let editor = editor.clone();
let hunk = hunk.clone();
move |event, cx| {
let modifiers = event.modifiers;
if modifiers.control || modifiers.platform {
editor.update(cx, |editor, cx| {
editor.toggle_hovered_hunk(&hunk, cx);
});
} else {
editor.update(cx, |editor, cx| {
editor.open_hunk_context_menu(
hunk.clone(),
event.position,
cx,
);
});
}
}
}),
)
.child(
v_flex()
.size_full()
.pt(rems(0.25))
.justify_start()
.child(close_button),
),
)
.child(editor_with_deleted_text.clone())
.into_any_element()
}),
priority: 0,
h_flex()
.id(cx.block_id)
.bg(deleted_hunk_color)
.h(height as f32 * cx.line_height())
.w_full()
.child(
h_flex()
.id("gutter")
.max_w(gutter_dimensions.full_width())
.min_w(gutter_dimensions.full_width())
.size_full()
.child(
h_flex()
.id("gutter hunk")
.bg(gutter_color)
.pl(gutter_dimensions.margin
+ gutter_dimensions
.git_blame_entries_width
.unwrap_or_default())
.max_w(width)
.min_w(width)
.size_full()
.cursor(CursorStyle::PointingHand)
.on_mouse_down(MouseButton::Left, {
let editor = editor.clone();
let hunk = hunk.clone();
move |_event, cx| {
editor.update(cx, |editor, cx| {
editor.toggle_hovered_hunk(&hunk, cx);
});
}
}),
),
)
.child(editor_with_deleted_text.clone())
.into_any_element()
}),
None,
cx,
);
if new_block_ids.len() == 1 {
new_block_ids.pop()
} else {
debug_panic!(
"Inserted one editor block but did not receive exactly one block id: {new_block_ids:?}"
);
None
}
}
@@ -521,7 +704,7 @@ impl Editor {
.expanded_hunks
.hunks
.drain(..)
.filter_map(|expanded_hunk| expanded_hunk.block)
.flat_map(|expanded_hunk| expanded_hunk.blocks.into_iter())
.collect::<HashSet<_>>();
if to_remove.is_empty() {
false
@@ -603,7 +786,7 @@ impl Editor {
expanded_hunk.folded = true;
highlights_to_remove
.push(expanded_hunk.hunk_range.clone());
if let Some(block) = expanded_hunk.block.take() {
for block in expanded_hunk.blocks.drain(..) {
blocks_to_remove.insert(block);
}
break;
@@ -650,20 +833,13 @@ impl Editor {
}
}
if !retain {
blocks_to_remove.extend(expanded_hunk.block);
blocks_to_remove.extend(expanded_hunk.blocks.drain(..));
highlights_to_remove.push(expanded_hunk.hunk_range.clone());
}
retain
});
for removed_rows in highlights_to_remove {
editor.highlight_rows::<DiffRowHighlight>(
to_inclusive_row_range(removed_rows, &snapshot),
None,
false,
cx,
);
}
editor.remove_highlighted_rows::<DiffRowHighlight>(highlights_to_remove, cx);
editor.remove_blocks(blocks_to_remove, None, cx);
if let Some(diff_base_buffer) = &diff_base_buffer {
@@ -749,7 +925,7 @@ fn added_hunk_color(cx: &AppContext) -> Hsla {
}
fn deleted_hunk_color(cx: &AppContext) -> Hsla {
let mut deleted_color = cx.theme().status().git().deleted;
let mut deleted_color = cx.theme().status().deleted;
deleted_color.fade_out(0.7);
deleted_color
}
@@ -783,37 +959,20 @@ fn editor_with_deleted_text(
editor.set_read_only(true);
editor.set_show_inline_completions(Some(false), cx);
editor.highlight_rows::<DiffRowHighlight>(
Anchor::min()..=Anchor::max(),
Some(deleted_color),
Anchor::min()..Anchor::max(),
deleted_color,
false,
cx,
);
let subscription_editor = parent_editor.clone();
editor._subscriptions.extend([
cx.on_blur(&editor.focus_handle, |editor, cx| {
editor.set_current_line_highlight(Some(CurrentLineHighlight::None));
editor.set_current_line_highlight(Some(CurrentLineHighlight::None));
editor
._subscriptions
.extend([cx.on_blur(&editor.focus_handle, |editor, cx| {
editor.change_selections(None, cx, |s| {
s.try_cancel();
});
cx.notify();
}),
cx.on_focus(&editor.focus_handle, move |editor, cx| {
let restored_highlight = if let Some(parent_editor) = subscription_editor.upgrade()
{
parent_editor.read(cx).current_line_highlight
} else {
None
};
editor.set_current_line_highlight(restored_highlight);
cx.notify();
}),
cx.observe_global::<SettingsStore>(|editor, cx| {
if !editor.is_focused(cx) {
editor.set_current_line_highlight(Some(CurrentLineHighlight::None));
}
}),
]);
})]);
let parent_editor_for_reverts = parent_editor.clone();
let original_multi_buffer_range = hunk.multi_buffer_range.clone();
let diff_base_range = hunk.diff_base_byte_range.clone();
@@ -879,21 +1038,6 @@ fn buffer_diff_hunk(
None
}
fn to_inclusive_row_range(
row_range: Range<Anchor>,
snapshot: &EditorSnapshot,
) -> RangeInclusive<Anchor> {
let mut display_row_range =
row_range.start.to_display_point(snapshot)..row_range.end.to_display_point(snapshot);
if display_row_range.end.row() > display_row_range.start.row() {
*display_row_range.end.row_mut() -= 1;
}
let point_range = display_row_range.start.to_point(&snapshot.display_snapshot)
..display_row_range.end.to_point(&snapshot.display_snapshot);
let new_range = point_range.to_anchors(&snapshot.buffer_snapshot);
new_range.start..=new_range.end
}
impl DisplayDiffHunk {
pub fn start_display_row(&self) -> DisplayRow {
match self {

View File

@@ -6,10 +6,13 @@ use language::{Buffer, BufferEvent, Capability};
use multi_buffer::{ExcerptRange, MultiBuffer};
use project::Project;
use smol::stream::StreamExt;
use std::{ops::Range, time::Duration};
use std::{any::TypeId, ops::Range, time::Duration};
use text::ToOffset;
use ui::prelude::*;
use workspace::Item;
use workspace::{
searchable::SearchableItemHandle, Item, ItemHandle as _, ToolbarItemEvent, ToolbarItemLocation,
ToolbarItemView,
};
pub struct ProposedChangesEditor {
editor: View<Editor>,
@@ -23,6 +26,10 @@ pub struct ProposedChangesBuffer<T> {
pub ranges: Vec<Range<T>>,
}
pub struct ProposedChangesEditorToolbar {
current_editor: Option<View<ProposedChangesEditor>>,
}
impl ProposedChangesEditor {
pub fn new<T: ToOffset>(
buffers: Vec<ProposedChangesBuffer<T>>,
@@ -96,6 +103,17 @@ impl ProposedChangesEditor {
self.recalculate_diffs_tx.unbounded_send(buffer).ok();
}
}
fn apply_all_changes(&self, cx: &mut ViewContext<Self>) {
let buffers = self.editor.read(cx).buffer.read(cx).all_buffers();
for branch_buffer in buffers {
if let Some(base_buffer) = branch_buffer.read(cx).diff_base_buffer() {
base_buffer.update(cx, |base_buffer, cx| {
base_buffer.merge(&branch_buffer, None, cx)
});
}
}
}
}
impl Render for ProposedChangesEditor {
@@ -122,4 +140,66 @@ impl Item for ProposedChangesEditor {
fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
Some("Proposed changes".into())
}
fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
Some(Box::new(self.editor.clone()))
}
fn act_as_type<'a>(
&'a self,
type_id: TypeId,
self_handle: &'a View<Self>,
_: &'a AppContext,
) -> Option<gpui::AnyView> {
if type_id == TypeId::of::<Self>() {
Some(self_handle.to_any())
} else if type_id == TypeId::of::<Editor>() {
Some(self.editor.to_any())
} else {
None
}
}
}
impl ProposedChangesEditorToolbar {
pub fn new() -> Self {
Self {
current_editor: None,
}
}
fn get_toolbar_item_location(&self) -> ToolbarItemLocation {
if self.current_editor.is_some() {
ToolbarItemLocation::PrimaryRight
} else {
ToolbarItemLocation::Hidden
}
}
}
impl Render for ProposedChangesEditorToolbar {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
let editor = self.current_editor.clone();
Button::new("apply-changes", "Apply All").on_click(move |_, cx| {
if let Some(editor) = &editor {
editor.update(cx, |editor, cx| {
editor.apply_all_changes(cx);
});
}
})
}
}
impl EventEmitter<ToolbarItemEvent> for ProposedChangesEditorToolbar {}
impl ToolbarItemView for ProposedChangesEditorToolbar {
fn set_active_pane_item(
&mut self,
active_pane_item: Option<&dyn workspace::ItemHandle>,
_cx: &mut ViewContext<Self>,
) -> workspace::ToolbarItemLocation {
self.current_editor =
active_pane_item.and_then(|item| item.downcast::<ProposedChangesEditor>());
self.get_toolbar_item_location()
}
}

View File

@@ -88,116 +88,3 @@ pub(crate) fn build_editor_with_project(
) -> Editor {
Editor::new(EditorMode::Full, buffer, Some(project), true, cx)
}
#[cfg(any(test, feature = "test-support"))]
pub fn editor_hunks(
editor: &Editor,
snapshot: &DisplaySnapshot,
cx: &mut ViewContext<'_, Editor>,
) -> Vec<(
String,
git::diff::DiffHunkStatus,
std::ops::Range<crate::DisplayRow>,
)> {
use multi_buffer::MultiBufferRow;
use text::Point;
use crate::hunk_status;
snapshot
.buffer_snapshot
.git_diff_hunks_in_range(MultiBufferRow::MIN..MultiBufferRow::MAX)
.map(|hunk| {
let display_range = Point::new(hunk.row_range.start.0, 0)
.to_display_point(snapshot)
.row()
..Point::new(hunk.row_range.end.0, 0)
.to_display_point(snapshot)
.row();
let (_, buffer, _) = editor
.buffer()
.read(cx)
.excerpt_containing(Point::new(hunk.row_range.start.0, 0), cx)
.expect("no excerpt for expanded buffer's hunk start");
let diff_base = buffer
.read(cx)
.diff_base()
.expect("should have a diff base for expanded hunk")
.slice(hunk.diff_base_byte_range.clone())
.to_string();
(diff_base, hunk_status(&hunk), display_range)
})
.collect()
}
#[cfg(any(test, feature = "test-support"))]
pub fn expanded_hunks(
editor: &Editor,
snapshot: &DisplaySnapshot,
cx: &mut ViewContext<'_, Editor>,
) -> Vec<(
String,
git::diff::DiffHunkStatus,
std::ops::Range<crate::DisplayRow>,
)> {
editor
.expanded_hunks
.hunks(false)
.map(|expanded_hunk| {
let hunk_display_range = expanded_hunk
.hunk_range
.start
.to_display_point(snapshot)
.row()
..expanded_hunk
.hunk_range
.end
.to_display_point(snapshot)
.row();
let (_, buffer, _) = editor
.buffer()
.read(cx)
.excerpt_containing(expanded_hunk.hunk_range.start, cx)
.expect("no excerpt for expanded buffer's hunk start");
let diff_base = buffer
.read(cx)
.diff_base()
.expect("should have a diff base for expanded hunk")
.slice(expanded_hunk.diff_base_byte_range.clone())
.to_string();
(diff_base, expanded_hunk.status, hunk_display_range)
})
.collect()
}
#[cfg(any(test, feature = "test-support"))]
pub fn expanded_hunks_background_highlights(
editor: &mut Editor,
cx: &mut gpui::WindowContext,
) -> Vec<std::ops::RangeInclusive<crate::DisplayRow>> {
use crate::DisplayRow;
let mut highlights = Vec::new();
let mut range_start = 0;
let mut previous_highlighted_row = None;
for (highlighted_row, _) in editor.highlighted_display_rows(cx) {
match previous_highlighted_row {
Some(previous_row) => {
if previous_row + 1 != highlighted_row.0 {
highlights.push(DisplayRow(range_start)..=DisplayRow(previous_row));
range_start = highlighted_row.0;
}
}
None => {
range_start = highlighted_row.0;
}
}
previous_highlighted_row = Some(highlighted_row.0);
}
if let Some(previous_row) = previous_highlighted_row {
highlights.push(DisplayRow(range_start)..=DisplayRow(previous_row));
}
highlights
}

View File

@@ -1,17 +1,17 @@
use crate::{
display_map::ToDisplayPoint, AnchorRangeExt, Autoscroll, DisplayPoint, Editor, MultiBuffer,
RowExt,
display_map::ToDisplayPoint, AnchorRangeExt, Autoscroll, DiffRowHighlight, DisplayPoint,
Editor, MultiBuffer, RowExt,
};
use collections::BTreeMap;
use futures::Future;
use git::diff::DiffHunkStatus;
use gpui::{
AnyWindowHandle, AppContext, Keystroke, ModelContext, Pixels, Point, View, ViewContext,
VisualTestContext,
VisualTestContext, WindowHandle,
};
use indoc::indoc;
use itertools::Itertools;
use language::{Buffer, BufferSnapshot, LanguageRegistry};
use multi_buffer::ExcerptRange;
use multi_buffer::{ExcerptRange, ToPoint};
use parking_lot::RwLock;
use project::{FakeFs, Project};
use std::{
@@ -71,6 +71,16 @@ impl EditorTestContext {
}
}
pub async fn for_editor(editor: WindowHandle<Editor>, cx: &mut gpui::TestAppContext) -> Self {
let editor_view = editor.root_view(cx).unwrap();
Self {
cx: VisualTestContext::from_window(*editor.deref(), cx),
window: editor.into(),
editor: editor_view,
assertion_cx: AssertionContextManager::new(),
}
}
pub fn new_multibuffer<const COUNT: usize>(
cx: &mut gpui::TestAppContext,
excerpts: [&str; COUNT],
@@ -297,19 +307,85 @@ impl EditorTestContext {
state_context
}
#[track_caller]
pub fn assert_diff_hunks(&mut self, expected_diff: String) {
// Normalize the expected diff. If it has no diff markers, then insert blank markers
// before each line. Strip any whitespace-only lines.
let has_diff_markers = expected_diff
.lines()
.any(|line| line.starts_with("+") || line.starts_with("-"));
let expected_diff_text = expected_diff
.split('\n')
.map(|line| {
let trimmed = line.trim();
if trimmed.is_empty() {
String::new()
} else if has_diff_markers {
line.to_string()
} else {
format!(" {line}")
}
})
.join("\n");
// Read the actual diff from the editor's row highlights and block
// decorations.
let actual_diff = self.editor.update(&mut self.cx, |editor, cx| {
let snapshot = editor.snapshot(cx);
let text = editor.text(cx);
let insertions = editor
.highlighted_rows::<DiffRowHighlight>()
.map(|(range, _)| {
let start = range.start.to_point(&snapshot.buffer_snapshot);
let end = range.end.to_point(&snapshot.buffer_snapshot);
start.row..end.row
})
.collect::<Vec<_>>();
let deletions = editor
.expanded_hunks
.hunks
.iter()
.filter_map(|hunk| {
if hunk.blocks.is_empty() {
return None;
}
let row = hunk
.hunk_range
.start
.to_point(&snapshot.buffer_snapshot)
.row;
let (_, buffer, _) = editor
.buffer()
.read(cx)
.excerpt_containing(hunk.hunk_range.start, cx)
.expect("no excerpt for expanded buffer's hunk start");
let deleted_text = buffer
.read(cx)
.diff_base()
.expect("should have a diff base for expanded hunk")
.slice(hunk.diff_base_byte_range.clone())
.to_string();
if let DiffHunkStatus::Modified | DiffHunkStatus::Removed = hunk.status {
Some((row, deleted_text))
} else {
None
}
})
.collect::<Vec<_>>();
format_diff(text, deletions, insertions)
});
pretty_assertions::assert_eq!(actual_diff, expected_diff_text, "unexpected diff state");
}
/// Make an assertion about the editor's text and the ranges and directions
/// of its selections using a string containing embedded range markers.
///
/// See the `util::test::marked_text_ranges` function for more information.
#[track_caller]
pub fn assert_editor_state(&mut self, marked_text: &str) {
let (unmarked_text, expected_selections) = marked_text_ranges(marked_text, true);
let buffer_text = self.buffer_text();
if buffer_text != unmarked_text {
panic!("Unmarked text doesn't match buffer text\nBuffer text: {buffer_text:?}\nUnmarked text: {unmarked_text:?}\nRaw buffer text\n{buffer_text}\nRaw unmarked text\n{unmarked_text}");
}
let (expected_text, expected_selections) = marked_text_ranges(marked_text, true);
pretty_assertions::assert_eq!(self.buffer_text(), expected_text, "unexpected buffer text");
self.assert_selections(expected_selections, marked_text.to_string())
}
@@ -382,25 +458,56 @@ impl EditorTestContext {
let actual_marked_text =
generate_marked_text(&self.buffer_text(), &actual_selections, true);
if expected_selections != actual_selections {
panic!(
indoc! {"
{}Editor has unexpected selections.
Expected selections:
{}
Actual selections:
{}
"},
self.assertion_context(),
expected_marked_text,
pretty_assertions::assert_eq!(
actual_marked_text,
expected_marked_text,
"{}Editor has unexpected selections",
self.assertion_context(),
);
}
}
}
fn format_diff(
text: String,
actual_deletions: Vec<(u32, String)>,
actual_insertions: Vec<Range<u32>>,
) -> String {
let mut diff = String::new();
for (row, line) in text.split('\n').enumerate() {
let row = row as u32;
if row > 0 {
diff.push('\n');
}
if let Some(text) = actual_deletions
.iter()
.find_map(|(deletion_row, deleted_text)| {
if *deletion_row == row {
Some(deleted_text)
} else {
None
}
})
{
for line in text.lines() {
diff.push('-');
if !line.is_empty() {
diff.push(' ');
diff.push_str(line);
}
diff.push('\n');
}
}
let marker = if actual_insertions.iter().any(|range| range.contains(&row)) {
"+ "
} else {
" "
};
diff.push_str(format!("{marker}{line}").trim_end());
}
diff
}
impl Deref for EditorTestContext {
type Target = gpui::VisualTestContext;

View File

@@ -108,7 +108,7 @@ fn main() -> Result<()> {
.clone()
.spawn(async move {
if let Err(err) = fetch_evaluation_resources(client, &executor).await {
eprintln!("Error fetching eval resources: {}", err);
eprintln!("Error: {}", err);
exit(1);
}
exit(0);
@@ -118,7 +118,7 @@ fn main() -> Result<()> {
Commands::Run { repo } => {
cx.spawn(|mut cx| async move {
if let Err(err) = run_evaluation(repo, &executor, &mut cx).await {
eprintln!("Error running eval: {}", err);
eprintln!("Error: {}", err);
exit(1);
}
exit(0);
@@ -294,8 +294,8 @@ async fn run_evaluation(
.unwrap();
let node_runtime = NodeRuntime::unavailable();
let evaluations = fs::read(&evaluations_path).expect("failed to read evaluations.json - run `cargo run -p evals --bin eval fetch` to fetch evaluations.json.");
let evaluations: Vec<EvaluationProject> = serde_json::from_slice(&evaluations).expect("evaluations.json was not valid JSON. It may have been corrupted; try deleting it and then running `cargo run -p evals --bin eval fetch` to fetch a new copy.");
let evaluations = fs::read(&evaluations_path).expect("failed to read evaluations.json");
let evaluations: Vec<EvaluationProject> = serde_json::from_slice(&evaluations).unwrap();
let embedding_provider = Arc::new(OpenAiEmbeddingProvider::new(
http_client.clone(),
@@ -322,7 +322,7 @@ async fn run_evaluation(
}
eprint!("\r\x1B[2K");
eprintln!(
eprint!(
"Running evals. {}/{} covered. {}/{} overlapped. {}/{} files captured. Project: {}...",
counts.covered_results,
counts.total_results,

View File

@@ -28,7 +28,6 @@ futures.workspace = true
gpui.workspace = true
http_client.workspace = true
indexed_docs.workspace = true
isahc.workspace = true
language.workspace = true
log.workspace = true
lsp.workspace = true

View File

@@ -664,7 +664,7 @@ impl ExtensionStore {
let content_length = response
.headers()
.get(isahc::http::header::CONTENT_LENGTH)
.get(http_client::http::header::CONTENT_LENGTH)
.and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
let mut body = BufReader::new(response.body_mut());

View File

@@ -576,7 +576,6 @@ async fn test_extension_store_with_test_extension(cx: &mut TestAppContext) {
std::env::consts::ARCH
)
});
let builder_client = IsahcHttpClient::new(None, Some(user_agent));
let extension_store = cx.new_model(|cx| {

View File

@@ -1,5 +1,5 @@
use crate::wasm_host::{wit::ToWasmtimeResult, WasmState};
use ::http_client::AsyncBody;
use ::http_client::{AsyncBody, HttpRequestExt};
use ::settings::{Settings, WorktreeId};
use anyhow::{anyhow, bail, Context, Result};
use async_compression::futures::bufread::GzipDecoder;
@@ -8,7 +8,6 @@ use async_trait::async_trait;
use futures::{io::BufReader, FutureExt as _};
use futures::{lock::Mutex, AsyncReadExt};
use indexed_docs::IndexedDocsDatabase;
use isahc::config::{Configurable, RedirectPolicy};
use language::{
language_settings::AllLanguageSettings, LanguageServerBinaryStatus, LspAdapterDelegate,
};
@@ -297,10 +296,12 @@ fn convert_request(
let mut request = ::http_client::Request::builder()
.method(::http_client::Method::from(extension_request.method))
.uri(&extension_request.url)
.redirect_policy(match extension_request.redirect_policy {
http_client::RedirectPolicy::NoFollow => RedirectPolicy::None,
http_client::RedirectPolicy::FollowLimit(limit) => RedirectPolicy::Limit(limit),
http_client::RedirectPolicy::FollowAll => RedirectPolicy::Follow,
.follow_redirects(match extension_request.redirect_policy {
http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
http_client::RedirectPolicy::FollowLimit(limit) => {
::http_client::RedirectPolicy::FollowLimit(limit)
}
http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
});
for (key, value) in &extension_request.headers {
request = request.header(key, value);

View File

@@ -1,5 +1,5 @@
use crate::wasm_host::{wit::ToWasmtimeResult, WasmState};
use ::http_client::AsyncBody;
use ::http_client::{AsyncBody, HttpRequestExt};
use ::settings::{Settings, WorktreeId};
use anyhow::{anyhow, bail, Context, Result};
use async_compression::futures::bufread::GzipDecoder;
@@ -8,7 +8,6 @@ use async_trait::async_trait;
use futures::{io::BufReader, FutureExt as _};
use futures::{lock::Mutex, AsyncReadExt};
use indexed_docs::IndexedDocsDatabase;
use isahc::config::{Configurable, RedirectPolicy};
use language::{
language_settings::AllLanguageSettings, LanguageServerBinaryStatus, LspAdapterDelegate,
};
@@ -213,10 +212,12 @@ fn convert_request(
let mut request = ::http_client::Request::builder()
.method(::http_client::Method::from(extension_request.method))
.uri(&extension_request.url)
.redirect_policy(match extension_request.redirect_policy {
http_client::RedirectPolicy::NoFollow => RedirectPolicy::None,
http_client::RedirectPolicy::FollowLimit(limit) => RedirectPolicy::Limit(limit),
http_client::RedirectPolicy::FollowAll => RedirectPolicy::Follow,
.follow_redirects(match extension_request.redirect_policy {
http_client::RedirectPolicy::NoFollow => ::http_client::RedirectPolicy::NoFollow,
http_client::RedirectPolicy::FollowLimit(limit) => {
::http_client::RedirectPolicy::FollowLimit(limit)
}
http_client::RedirectPolicy::FollowAll => ::http_client::RedirectPolicy::FollowAll,
});
for (key, value) in &extension_request.headers {
request = request.header(key, value);

View File

@@ -23,7 +23,6 @@ editor.workspace = true
futures.workspace = true
gpui.workspace = true
human_bytes = "0.4.1"
isahc.workspace = true
http_client.workspace = true
language.workspace = true
log.workspace = true

View File

@@ -11,7 +11,6 @@ use gpui::{
PromptLevel, Render, Task, View, ViewContext,
};
use http_client::HttpClient;
use isahc::Request;
use language::Buffer;
use project::Project;
use regex::Regex;
@@ -299,7 +298,7 @@ impl FeedbackModal {
is_staff: is_staff.unwrap_or(false),
};
let json_bytes = serde_json::to_vec(&request)?;
let request = Request::post(feedback_endpoint)
let request = http_client::http::Request::post(feedback_endpoint)
.header("content-type", "application/json")
.body(json_bytes.into())?;
let mut response = http_client.send(request).await?;

View File

@@ -394,7 +394,7 @@ fn matching_history_items<'a>(
.chars(),
),
};
candidates_paths.insert(Arc::clone(&found_path.project.path), found_path);
candidates_paths.insert(&found_path.project, found_path);
Some((found_path.project.worktree_id, candidate))
})
.fold(
@@ -419,17 +419,21 @@ fn matching_history_items<'a>(
max_results,
)
.into_iter()
.map(|path_match| {
let (_, found_path) = candidates_paths
.remove_entry(&path_match.path)
.expect("candidate info not found");
(
Arc::clone(&path_match.path),
Match::History {
path: found_path.clone(),
panel_match: Some(ProjectPanelOrdMatch(path_match)),
},
)
.filter_map(|path_match| {
candidates_paths
.remove_entry(&ProjectPath {
worktree_id: WorktreeId::from_usize(path_match.worktree_id),
path: Arc::clone(&path_match.path),
})
.map(|(_, found_path)| {
(
Arc::clone(&path_match.path),
Match::History {
path: found_path.clone(),
panel_match: Some(ProjectPanelOrdMatch(path_match)),
},
)
})
}),
);
}

View File

@@ -34,7 +34,7 @@ struct InternalDiffHunk {
impl sum_tree::Item for InternalDiffHunk {
type Summary = DiffHunkSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _cx: &text::BufferSnapshot) -> Self::Summary {
DiffHunkSummary {
buffer_range: self.buffer_range.clone(),
}

View File

@@ -3,7 +3,7 @@ use std::sync::Arc;
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use futures::AsyncReadExt;
use http_client::{AsyncBody, HttpClient, Request};
use http_client::{AsyncBody, HttpClient, HttpRequestExt, Request};
use serde::Deserialize;
use url::Url;
@@ -49,14 +49,16 @@ impl Codeberg {
let url =
format!("https://codeberg.org/api/v1/repos/{repo_owner}/{repo}/git/commits/{commit}");
let mut request = Request::get(&url).header("Content-Type", "application/json");
let mut request = Request::get(&url)
.header("Content-Type", "application/json")
.follow_redirects(http_client::RedirectPolicy::FollowAll);
if let Ok(codeberg_token) = std::env::var("CODEBERG_TOKEN") {
request = request.header("Authorization", format!("Bearer {}", codeberg_token));
}
let mut response = client
.send_with_redirect_policy(request.body(AsyncBody::default())?, true)
.send(request.body(AsyncBody::default())?)
.await
.with_context(|| format!("error fetching Codeberg commit details at {:?}", url))?;

View File

@@ -3,7 +3,7 @@ use std::sync::{Arc, OnceLock};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use futures::AsyncReadExt;
use http_client::{AsyncBody, HttpClient, Request};
use http_client::{AsyncBody, HttpClient, HttpRequestExt, Request};
use regex::Regex;
use serde::Deserialize;
use url::Url;
@@ -53,14 +53,16 @@ impl Github {
) -> Result<Option<User>> {
let url = format!("https://api.github.com/repos/{repo_owner}/{repo}/commits/{commit}");
let mut request = Request::get(&url).header("Content-Type", "application/json");
let mut request = Request::get(&url)
.header("Content-Type", "application/json")
.follow_redirects(http_client::RedirectPolicy::FollowAll);
if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
request = request.header("Authorization", format!("Bearer {}", github_token));
}
let mut response = client
.send_with_redirect_policy(request.body(AsyncBody::default())?, true)
.send(request.body(AsyncBody::default())?)
.await
.with_context(|| format!("error fetching GitHub commit details at {:?}", url))?;

View File

@@ -116,12 +116,14 @@ impl GoToLine {
if let Some(point) = self.point_from_query(cx) {
self.active_editor.update(cx, |active_editor, cx| {
let snapshot = active_editor.snapshot(cx).display_snapshot;
let point = snapshot.buffer_snapshot.clip_point(point, Bias::Left);
let anchor = snapshot.buffer_snapshot.anchor_before(point);
let start = snapshot.buffer_snapshot.clip_point(point, Bias::Left);
let end = start + Point::new(1, 0);
let start = snapshot.buffer_snapshot.anchor_before(start);
let end = snapshot.buffer_snapshot.anchor_after(end);
active_editor.clear_row_highlights::<GoToLineRowHighlights>();
active_editor.highlight_rows::<GoToLineRowHighlights>(
anchor..=anchor,
Some(cx.theme().colors().editor_highlighted_line_background),
start..end,
cx.theme().colors().editor_highlighted_line_background,
true,
cx,
);
@@ -244,13 +246,13 @@ mod tests {
field_1: i32, // display line 3
field_2: i32, // display line 4
} // display line 5
// display line 7
struct Another { // display line 8
field_1: i32, // display line 9
field_2: i32, // display line 10
field_3: i32, // display line 11
field_4: i32, // display line 12
} // display line 13
// display line 6
struct Another { // display line 7
field_1: i32, // display line 8
field_2: i32, // display line 9
field_3: i32, // display line 10
field_4: i32, // display line 11
} // display line 12
"}
}),
)

View File

@@ -18,7 +18,6 @@ schemars = ["dep:schemars"]
anyhow.workspace = true
futures.workspace = true
http_client.workspace = true
isahc.workspace = true
schemars = { workspace = true, optional = true }
serde.workspace = true
serde_json.workspace = true

View File

@@ -2,8 +2,7 @@ mod supported_countries;
use anyhow::{anyhow, Result};
use futures::{io::BufReader, stream::BoxStream, AsyncBufReadExt, AsyncReadExt, Stream, StreamExt};
use http_client::{AsyncBody, HttpClient, Method, Request as HttpRequest};
use isahc::config::Configurable;
use http_client::{AsyncBody, HttpClient, HttpRequestExt, Method, Request as HttpRequest};
use serde::{Deserialize, Serialize};
use std::time::Duration;
@@ -30,7 +29,7 @@ pub async fn stream_generate_content(
.header("Content-Type", "application/json");
if let Some(low_speed_timeout) = low_speed_timeout {
request_builder = request_builder.low_speed_timeout(100, low_speed_timeout);
request_builder = request_builder.read_timeout(low_speed_timeout);
};
let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
@@ -85,7 +84,7 @@ pub async fn count_tokens(
.header("Content-Type", "application/json");
if let Some(low_speed_timeout) = low_speed_timeout {
request_builder = request_builder.low_speed_timeout(100, low_speed_timeout);
request_builder = request_builder.read_timeout(low_speed_timeout);
}
let http_request = request_builder.body(AsyncBody::from(request))?;

View File

@@ -69,25 +69,51 @@ struct ImageShowcase {
impl Render for ImageShowcase {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
div()
.flex()
.flex_row()
.size_full()
.flex()
.flex_col()
.justify_center()
.items_center()
.gap_8()
.bg(rgb(0xFFFFFF))
.child(ImageContainer::new(
"Image loaded from a local file",
self.local_resource.clone(),
))
.child(ImageContainer::new(
"Image loaded from a remote resource",
self.remote_resource.clone(),
))
.child(ImageContainer::new(
"Image loaded from an asset",
self.asset_resource.clone(),
))
.child(
div()
.flex()
.flex_row()
.justify_center()
.items_center()
.gap_8()
.child(ImageContainer::new(
"Image loaded from a local file",
self.local_resource.clone(),
))
.child(ImageContainer::new(
"Image loaded from a remote resource",
self.remote_resource.clone(),
))
.child(ImageContainer::new(
"Image loaded from an asset",
self.asset_resource.clone(),
)),
)
.child(
div()
.flex()
.flex_row()
.gap_8()
.child(
div()
.flex_col()
.child("Auto Width")
.child(img("https://picsum.photos/800/400").h(px(180.))),
)
.child(
div()
.flex_col()
.child("Auto Height")
.child(img("https://picsum.photos/480/640").w(px(180.))),
),
)
}
}

View File

@@ -1524,10 +1524,9 @@ pub struct KeystrokeEvent {
struct NullHttpClient;
impl HttpClient for NullHttpClient {
fn send_with_redirect_policy(
fn send(
&self,
_req: http_client::Request<http_client::AsyncBody>,
_follow_redirects: bool,
) -> futures::future::BoxFuture<
'static,
Result<http_client::Response<http_client::AsyncBody>, anyhow::Error>,

View File

@@ -1,7 +1,7 @@
use crate::{
px, AbsoluteLength, AppContext, Asset, Bounds, DefiniteLength, Element, ElementId,
GlobalElementId, Hitbox, Image, InteractiveElement, Interactivity, IntoElement, LayoutId,
Length, ObjectFit, Pixels, RenderImage, SharedString, SharedUri, Size, StyleRefinement, Styled,
Length, ObjectFit, Pixels, RenderImage, SharedString, SharedUri, StyleRefinement, Styled,
SvgSize, UriOrPath, WindowContext,
};
use futures::{AsyncReadExt, Future};
@@ -187,16 +187,30 @@ impl Element for Img {
let image_size = data.size(frame_index);
if let (Length::Auto, Length::Auto) = (style.size.width, style.size.height)
{
style.size = Size {
width: Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(px(image_size.width.0 as f32)),
)),
height: Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(px(image_size.height.0 as f32)),
)),
}
if let Length::Auto = style.size.width {
style.size.width = match style.size.height {
Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(height),
)) => Length::Definite(
px(image_size.width.0 as f32 * height.0
/ image_size.height.0 as f32)
.into(),
),
_ => Length::Definite(px(image_size.width.0 as f32).into()),
};
}
if let Length::Auto = style.size.height {
style.size.height = match style.size.width {
Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(width),
)) => Length::Definite(
px(image_size.height.0 as f32 * width.0
/ image_size.width.0 as f32)
.into(),
),
_ => Length::Definite(px(image_size.height.0 as f32).into()),
};
}
if global_id.is_some() && data.frame_count() > 1 {

View File

@@ -858,7 +858,7 @@ impl Styled for List {
impl sum_tree::Item for ListItem {
type Summary = ListItemSummary;
fn summary(&self) -> Self::Summary {
fn summary(&self, _: &()) -> Self::Summary {
match self {
ListItem::Unmeasured { focus_handle } => ListItemSummary {
count: 1,

View File

@@ -2612,6 +2612,12 @@ impl From<ScaledPixels> for f64 {
}
}
impl From<ScaledPixels> for u32 {
fn from(pixels: ScaledPixels) -> Self {
pixels.0 as u32
}
}
/// Represents a length in rems, a unit based on the font-size of the window, which can be assigned with [`WindowContext::set_rem_size`][set_rem_size].
///
/// Rems are used for defining lengths that are scalable and consistent across different UI elements.

View File

@@ -23,8 +23,8 @@ use crate::{
point, Action, AnyWindowHandle, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds,
DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun, ForegroundExecutor,
GPUSpecs, GlyphId, ImageSource, Keymap, LineLayout, Pixels, PlatformInput, Point,
RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, SharedString, Size,
SvgSize, Task, TaskLabel, WindowContext, DEFAULT_WINDOW_SIZE,
RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, ScaledPixels, Scene,
SharedString, Size, SvgSize, Task, TaskLabel, WindowContext, DEFAULT_WINDOW_SIZE,
};
use anyhow::Result;
use async_task::Runnable;
@@ -381,7 +381,7 @@ pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
fn set_client_inset(&self, _inset: Pixels) {}
fn gpu_specs(&self) -> Option<GPUSpecs>;
fn update_ime_position(&self, _bounds: Bounds<Pixels>);
fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>);
#[cfg(any(test, feature = "test-support"))]
fn as_test(&mut self) -> Option<&mut TestWindow> {

View File

@@ -603,17 +603,11 @@ pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::S
state
}
pub(super) unsafe fn read_fd(mut fd: FileDescriptor) -> Result<String> {
pub(super) unsafe fn read_fd(mut fd: FileDescriptor) -> Result<Vec<u8>> {
let mut file = File::from_raw_fd(fd.as_raw_fd());
let mut buffer = String::new();
file.read_to_string(&mut buffer)?;
// Normalize the text to unix line endings, otherwise
// copying from eg: firefox inserts a lot of blank
// lines, and that is super annoying.
let result = buffer.replace("\r\n", "\n");
Ok(result)
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
Ok(buffer)
}
impl CursorStyle {

View File

@@ -84,7 +84,7 @@ use crate::{
use crate::{
AnyWindowHandle, CursorStyle, DisplayId, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
NavigationDirection, Pixels, PlatformDisplay, PlatformInput, Point, ScrollDelta,
NavigationDirection, Pixels, PlatformDisplay, PlatformInput, Point, ScaledPixels, ScrollDelta,
ScrollWheelEvent, TouchPhase,
};
use crate::{LinuxCommon, WindowParams};
@@ -236,6 +236,7 @@ pub struct DragState {
}
pub struct ClickState {
last_mouse_button: Option<MouseButton>,
last_click: Instant,
last_location: Point<Pixels>,
current_count: usize,
@@ -313,7 +314,7 @@ impl WaylandClientStatePtr {
}
}
pub fn update_ime_position(&self, bounds: Bounds<Pixels>) {
pub fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
let client = self.get_client();
let mut state = client.borrow_mut();
if state.composing || state.text_input.is_none() || state.pre_edit_text.is_some() {
@@ -535,6 +536,7 @@ impl WaylandClient {
},
click: ClickState {
last_click: Instant::now(),
last_mouse_button: None,
last_location: Point::default(),
current_count: 0,
},
@@ -1524,6 +1526,10 @@ impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
let click_elapsed = state.click.last_click.elapsed();
if click_elapsed < DOUBLE_CLICK_INTERVAL
&& state
.click
.last_mouse_button
.is_some_and(|prev_button| prev_button == button)
&& is_within_click_distance(
state.click.last_location,
state.mouse_location.unwrap(),
@@ -1535,6 +1541,7 @@ impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
}
state.click.last_click = Instant::now();
state.click.last_mouse_button = Some(button);
state.click.last_location = state.mouse_location.unwrap();
state.button_pressed = Some(button);
@@ -1799,10 +1806,11 @@ impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
let fd = pipe.read;
drop(pipe.write);
let read_task = state
.common
.background_executor
.spawn(async { unsafe { read_fd(fd) } });
let read_task = state.common.background_executor.spawn(async {
let buffer = unsafe { read_fd(fd)? };
let text = String::from_utf8(buffer)?;
anyhow::Ok(text)
});
let this = this.clone();
state

View File

@@ -6,10 +6,14 @@ use std::{
use calloop::{LoopHandle, PostAction};
use filedescriptor::Pipe;
use strum::IntoEnumIterator;
use wayland_client::{protocol::wl_data_offer::WlDataOffer, Connection};
use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1;
use crate::{platform::linux::platform::read_fd, ClipboardItem, WaylandClientStatePtr};
use crate::{
hash, platform::linux::platform::read_fd, ClipboardEntry, ClipboardItem, Image, ImageFormat,
WaylandClientStatePtr,
};
pub(crate) const TEXT_MIME_TYPE: &str = "text/plain;charset=utf-8";
pub(crate) const FILE_LIST_MIME_TYPE: &str = "text/uri-list";
@@ -33,14 +37,30 @@ pub(crate) struct Clipboard {
current_primary_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>,
}
pub(crate) trait ReceiveData {
fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>);
}
impl ReceiveData for WlDataOffer {
fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>) {
self.receive(mime_type, fd);
}
}
impl ReceiveData for ZwpPrimarySelectionOfferV1 {
fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>) {
self.receive(mime_type, fd);
}
}
#[derive(Clone, Debug)]
/// Wrapper for `WlDataOffer` and `ZwpPrimarySelectionOfferV1`, used to help track mime types.
pub(crate) struct DataOffer<T> {
pub(crate) struct DataOffer<T: ReceiveData> {
pub inner: T,
mime_types: Vec<String>,
}
impl<T> DataOffer<T> {
impl<T: ReceiveData> DataOffer<T> {
pub fn new(offer: T) -> Self {
Self {
inner: offer,
@@ -52,17 +72,71 @@ impl<T> DataOffer<T> {
self.mime_types.push(mime_type)
}
pub fn has_mime_type(&self, mime_type: &str) -> bool {
fn has_mime_type(&self, mime_type: &str) -> bool {
self.mime_types.iter().any(|t| t == mime_type)
}
pub fn find_text_mime_type(&self) -> Option<String> {
for offered_mime_type in &self.mime_types {
if let Some(offer_text_mime_type) = ALLOWED_TEXT_MIME_TYPES
.into_iter()
.find(|text_mime_type| text_mime_type == offered_mime_type)
{
return Some(offer_text_mime_type.to_owned());
fn read_bytes(&self, connection: &Connection, mime_type: &str) -> Option<Vec<u8>> {
let pipe = Pipe::new().unwrap();
self.inner.receive_data(mime_type.to_string(), unsafe {
BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
});
let fd = pipe.read;
drop(pipe.write);
connection.flush().unwrap();
match unsafe { read_fd(fd) } {
Ok(bytes) => Some(bytes),
Err(err) => {
log::error!("error reading clipboard pipe: {err:?}");
None
}
}
}
fn read_text(&self, connection: &Connection) -> Option<ClipboardItem> {
let mime_type = self.mime_types.iter().find(|&mime_type| {
ALLOWED_TEXT_MIME_TYPES
.iter()
.any(|&allowed| allowed == mime_type)
})?;
let bytes = self.read_bytes(connection, mime_type)?;
let text_content = match String::from_utf8(bytes) {
Ok(content) => content,
Err(e) => {
log::error!("Failed to convert clipboard content to UTF-8: {}", e);
return None;
}
};
// Normalize the text to unix line endings, otherwise
// copying from eg: firefox inserts a lot of blank
// lines, and that is super annoying.
let result = text_content.replace("\r\n", "\n");
Some(ClipboardItem::new_string(result))
}
fn read_image(&self, connection: &Connection) -> Option<ClipboardItem> {
for format in ImageFormat::iter() {
let mime_type = match format {
ImageFormat::Png => "image/png",
ImageFormat::Jpeg => "image/jpeg",
ImageFormat::Webp => "image/webp",
ImageFormat::Gif => "image/gif",
ImageFormat::Svg => "image/svg+xml",
ImageFormat::Bmp => "image/bmp",
ImageFormat::Tiff => "image/tiff",
};
if !self.has_mime_type(mime_type) {
continue;
}
if let Some(bytes) = self.read_bytes(connection, mime_type) {
let id = hash(&bytes);
return Some(ClipboardItem {
entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
});
}
}
None
@@ -128,7 +202,7 @@ impl Clipboard {
}
pub fn read(&mut self) -> Option<ClipboardItem> {
let offer = self.current_offer.clone()?;
let offer = self.current_offer.as_ref()?;
if let Some(cached) = self.cached_read.clone() {
return Some(cached);
}
@@ -137,30 +211,16 @@ impl Clipboard {
return self.contents.clone();
}
let mime_type = offer.find_text_mime_type()?;
let pipe = Pipe::new().unwrap();
offer.inner.receive(mime_type, unsafe {
BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
});
let fd = pipe.read;
drop(pipe.write);
let item = offer
.read_text(&self.connection)
.or_else(|| offer.read_image(&self.connection))?;
self.connection.flush().unwrap();
match unsafe { read_fd(fd) } {
Ok(v) => {
self.cached_read = Some(ClipboardItem::new_string(v));
self.cached_read.clone()
}
Err(err) => {
log::error!("error reading clipboard pipe: {err:?}");
None
}
}
self.cached_read = Some(item.clone());
Some(item)
}
pub fn read_primary(&mut self) -> Option<ClipboardItem> {
let offer = self.current_primary_offer.clone()?;
let offer = self.current_primary_offer.as_ref()?;
if let Some(cached) = self.cached_primary_read.clone() {
return Some(cached);
}
@@ -169,26 +229,12 @@ impl Clipboard {
return self.primary_contents.clone();
}
let mime_type = offer.find_text_mime_type()?;
let pipe = Pipe::new().unwrap();
offer.inner.receive(mime_type, unsafe {
BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
});
let fd = pipe.read;
drop(pipe.write);
let item = offer
.read_text(&self.connection)
.or_else(|| offer.read_image(&self.connection))?;
self.connection.flush().unwrap();
match unsafe { read_fd(fd) } {
Ok(v) => {
self.cached_primary_read = Some(ClipboardItem::new_string(v.clone()));
self.cached_primary_read.clone()
}
Err(err) => {
log::error!("error reading clipboard pipe: {err:?}");
None
}
}
self.cached_primary_read = Some(item.clone());
Some(item)
}
fn send_internal(&self, fd: OwnedFd, bytes: Vec<u8>) {

View File

@@ -26,7 +26,7 @@ use crate::platform::{PlatformAtlas, PlatformInputHandler, PlatformWindow};
use crate::scene::Scene;
use crate::{
px, size, AnyWindowHandle, Bounds, Decorations, GPUSpecs, Globals, Modifiers, Output, Pixels,
PlatformDisplay, PlatformInput, Point, PromptLevel, ResizeEdge, Size, Tiling,
PlatformDisplay, PlatformInput, Point, PromptLevel, ResizeEdge, ScaledPixels, Size, Tiling,
WaylandClientStatePtr, WindowAppearance, WindowBackgroundAppearance, WindowBounds,
WindowControls, WindowDecorations, WindowParams,
};
@@ -1010,7 +1010,7 @@ impl PlatformWindow for WaylandWindow {
}
}
fn update_ime_position(&self, bounds: Bounds<Pixels>) {
fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
let state = self.borrow();
state.client.update_ime_position(bounds);
}
@@ -1046,8 +1046,8 @@ fn update_window(mut state: RefMut<WaylandWindowState>) {
&& state.decorations == WindowDecorations::Server
{
// Promise the compositor that this region of the window surface
// contains no transparent pixels. This allows the compositor to
// do skip whatever is behind the surface for better performance.
// contains no transparent pixels. This allows the compositor to skip
// updating whatever is behind the surface for better performance.
state.surface.set_opaque_region(Some(&region));
} else {
state.surface.set_opaque_region(None);
@@ -1057,7 +1057,6 @@ fn update_window(mut state: RefMut<WaylandWindowState>) {
if state.background_appearance == WindowBackgroundAppearance::Blurred {
if state.blur.is_none() {
let blur = blur_manager.create(&state.surface, &state.globals.qh, ());
blur.set_region(Some(&region));
state.blur = Some(blur);
}
state.blur.as_ref().unwrap().commit();

View File

@@ -37,8 +37,9 @@ use crate::platform::linux::LinuxClient;
use crate::platform::{LinuxCommon, PlatformWindow};
use crate::{
modifiers_from_xinput_info, point, px, AnyWindowHandle, Bounds, ClipboardItem, CursorStyle,
DisplayId, FileDropEvent, Keystroke, Modifiers, ModifiersChangedEvent, Pixels, Platform,
PlatformDisplay, PlatformInput, Point, ScrollDelta, Size, TouchPhase, WindowParams, X11Window,
DisplayId, FileDropEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, Pixels,
Platform, PlatformDisplay, PlatformInput, Point, ScaledPixels, ScrollDelta, Size, TouchPhase,
WindowParams, X11Window,
};
use super::{button_of_key, modifiers_from_state, pressed_button_from_mask};
@@ -121,6 +122,7 @@ pub struct X11ClientState {
pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
pub(crate) last_click: Instant,
pub(crate) last_mouse_button: Option<MouseButton>,
pub(crate) last_location: Point<Pixels>,
pub(crate) current_count: usize,
@@ -188,7 +190,7 @@ impl X11ClientStatePtr {
}
}
pub fn update_ime_position(&self, bounds: Bounds<Pixels>) {
pub fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
let client = self.get_client();
let mut state = client.0.borrow_mut();
if state.composing || state.ximc.is_none() {
@@ -403,6 +405,7 @@ impl X11Client {
loop_handle: handle,
common,
last_click: Instant::now(),
last_mouse_button: None,
last_location: Point::new(px(0.0), px(0.0)),
current_count: 0,
scale_factor,
@@ -951,6 +954,9 @@ impl X11Client {
let click_elapsed = state.last_click.elapsed();
if click_elapsed < DOUBLE_CLICK_INTERVAL
&& state
.last_mouse_button
.is_some_and(|prev_button| prev_button == button)
&& is_within_click_distance(state.last_location, position)
{
state.current_count += 1;
@@ -959,6 +965,7 @@ impl X11Client {
}
state.last_click = Instant::now();
state.last_mouse_button = Some(button);
state.last_location = position;
let current_count = state.current_count;

View File

@@ -4,9 +4,9 @@ use crate::{
platform::blade::{BladeRenderer, BladeSurfaceConfig},
px, size, AnyWindowHandle, Bounds, Decorations, DevicePixels, ForegroundExecutor, GPUSpecs,
Modifiers, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler,
PlatformWindow, Point, PromptLevel, ResizeEdge, Scene, Size, Tiling, WindowAppearance,
WindowBackgroundAppearance, WindowBounds, WindowDecorations, WindowKind, WindowParams,
X11ClientStatePtr,
PlatformWindow, Point, PromptLevel, ResizeEdge, ScaledPixels, Scene, Size, Tiling,
WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowDecorations, WindowKind,
WindowParams, X11ClientStatePtr,
};
use blade_graphics as gpu;
@@ -1412,7 +1412,7 @@ impl PlatformWindow for X11Window {
}
}
fn update_ime_position(&self, bounds: Bounds<Pixels>) {
fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
let mut state = self.0.state.borrow_mut();
let client = state.client.clone();
drop(state);

View File

@@ -70,9 +70,7 @@ mod tests {
unsafe {
let image: id = msg_send![class!(NSImage), alloc];
image.initWithContentsOfFile_(
NSString::alloc(nil).init_str("/Users/rtfeldman/Downloads/test.jpeg"),
);
image.initWithContentsOfFile_(NSString::alloc(nil).init_str("test.jpeg"));
let _size = image.size();
let string = NSString::alloc(nil).init_str("Test String");

View File

@@ -3,8 +3,9 @@ use crate::{
platform::PlatformInputHandler, point, px, size, AnyWindowHandle, Bounds, DisplayLink,
ExternalPaths, FileDropEvent, ForegroundExecutor, KeyDownEvent, Keystroke, Modifiers,
ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
PlatformAtlas, PlatformDisplay, PlatformInput, PlatformWindow, Point, PromptLevel, Size, Timer,
WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowKind, WindowParams,
PlatformAtlas, PlatformDisplay, PlatformInput, PlatformWindow, Point, PromptLevel,
ScaledPixels, Size, Timer, WindowAppearance, WindowBackgroundAppearance, WindowBounds,
WindowKind, WindowParams,
};
use block::ConcreteBlock;
use cocoa::{
@@ -1119,7 +1120,7 @@ impl PlatformWindow for MacWindow {
None
}
fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>) {
unsafe {
let input_context: id = msg_send![class!(NSTextInputContext), currentInputContext];
let _: () = msg_send![input_context, invalidateCharacterCoordinates];

View File

@@ -1,8 +1,8 @@
use crate::{
AnyWindowHandle, AtlasKey, AtlasTextureId, AtlasTile, Bounds, DispatchEventResult, GPUSpecs,
Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
Point, Size, TestPlatform, TileId, WindowAppearance, WindowBackgroundAppearance, WindowBounds,
WindowParams,
Point, ScaledPixels, Size, TestPlatform, TileId, WindowAppearance, WindowBackgroundAppearance,
WindowBounds, WindowParams,
};
use collections::HashMap;
use parking_lot::Mutex;
@@ -274,7 +274,7 @@ impl PlatformWindow for TestWindow {
unimplemented!()
}
fn update_ime_position(&self, _bounds: Bounds<Pixels>) {}
fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>) {}
fn gpu_specs(&self) -> Option<GPUSpecs> {
None

View File

@@ -1,3 +1,4 @@
mod clipboard;
mod direct_write;
mod dispatcher;
mod display;
@@ -8,6 +9,7 @@ mod util;
mod window;
mod wrapper;
pub(crate) use clipboard::*;
pub(crate) use direct_write::*;
pub(crate) use dispatcher::*;
pub(crate) use display::*;

View File

@@ -0,0 +1,366 @@
use std::sync::LazyLock;
use anyhow::Result;
use collections::{FxHashMap, FxHashSet};
use itertools::Itertools;
use util::ResultExt;
use windows::Win32::{
Foundation::HANDLE,
System::{
DataExchange::{
CloseClipboard, CountClipboardFormats, EmptyClipboard, EnumClipboardFormats,
GetClipboardData, GetClipboardFormatNameW, IsClipboardFormatAvailable, OpenClipboard,
RegisterClipboardFormatW, SetClipboardData,
},
Memory::{GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE},
Ole::{CF_HDROP, CF_UNICODETEXT},
},
UI::Shell::{DragQueryFileW, HDROP},
};
use windows_core::PCWSTR;
use crate::{
hash, ClipboardEntry, ClipboardItem, ClipboardString, Image, ImageFormat, SmartGlobal,
};
// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-dragqueryfilew
const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
// Clipboard formats
static CLIPBOARD_HASH_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("GPUI internal text hash")));
static CLIPBOARD_METADATA_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("GPUI internal metadata")));
static CLIPBOARD_SVG_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("image/svg+xml")));
static CLIPBOARD_GIF_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("GIF")));
static CLIPBOARD_PNG_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("PNG")));
static CLIPBOARD_JPG_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("JFIF")));
// Helper maps and sets
static FORMATS_MAP: LazyLock<FxHashMap<u32, ClipboardFormatType>> = LazyLock::new(|| {
let mut formats_map = FxHashMap::default();
formats_map.insert(CF_UNICODETEXT.0 as u32, ClipboardFormatType::Text);
formats_map.insert(*CLIPBOARD_PNG_FORMAT, ClipboardFormatType::Image);
formats_map.insert(*CLIPBOARD_GIF_FORMAT, ClipboardFormatType::Image);
formats_map.insert(*CLIPBOARD_JPG_FORMAT, ClipboardFormatType::Image);
formats_map.insert(*CLIPBOARD_SVG_FORMAT, ClipboardFormatType::Image);
formats_map.insert(CF_HDROP.0 as u32, ClipboardFormatType::Files);
formats_map
});
static FORMATS_SET: LazyLock<FxHashSet<u32>> = LazyLock::new(|| {
let mut formats_map = FxHashSet::default();
formats_map.insert(CF_UNICODETEXT.0 as u32);
formats_map.insert(*CLIPBOARD_PNG_FORMAT);
formats_map.insert(*CLIPBOARD_GIF_FORMAT);
formats_map.insert(*CLIPBOARD_JPG_FORMAT);
formats_map.insert(*CLIPBOARD_SVG_FORMAT);
formats_map.insert(CF_HDROP.0 as u32);
formats_map
});
static IMAGE_FORMATS_MAP: LazyLock<FxHashMap<u32, ImageFormat>> = LazyLock::new(|| {
let mut formats_map = FxHashMap::default();
formats_map.insert(*CLIPBOARD_PNG_FORMAT, ImageFormat::Png);
formats_map.insert(*CLIPBOARD_GIF_FORMAT, ImageFormat::Gif);
formats_map.insert(*CLIPBOARD_JPG_FORMAT, ImageFormat::Jpeg);
formats_map.insert(*CLIPBOARD_SVG_FORMAT, ImageFormat::Svg);
formats_map
});
#[derive(Debug, Clone, Copy)]
enum ClipboardFormatType {
Text,
Image,
Files,
}
pub(crate) fn write_to_clipboard(item: ClipboardItem) {
write_to_clipboard_inner(item).log_err();
unsafe { CloseClipboard().log_err() };
}
pub(crate) fn read_from_clipboard() -> Option<ClipboardItem> {
let result = read_from_clipboard_inner();
unsafe { CloseClipboard().log_err() };
result
}
pub(crate) fn with_file_names<F>(hdrop: HDROP, mut f: F)
where
F: FnMut(String),
{
let file_count = unsafe { DragQueryFileW(hdrop, DRAGDROP_GET_FILES_COUNT, None) };
for file_index in 0..file_count {
let filename_length = unsafe { DragQueryFileW(hdrop, file_index, None) } as usize;
let mut buffer = vec![0u16; filename_length + 1];
let ret = unsafe { DragQueryFileW(hdrop, file_index, Some(buffer.as_mut_slice())) };
if ret == 0 {
log::error!("unable to read file name");
continue;
}
if let Some(file_name) = String::from_utf16(&buffer[0..filename_length]).log_err() {
f(file_name);
}
}
}
fn register_clipboard_format(format: PCWSTR) -> u32 {
let ret = unsafe { RegisterClipboardFormatW(format) };
if ret == 0 {
panic!(
"Error when registering clipboard format: {}",
std::io::Error::last_os_error()
);
}
ret
}
#[inline]
fn format_to_type(item_format: u32) -> &'static ClipboardFormatType {
FORMATS_MAP.get(&item_format).unwrap()
}
// Currently, we only write the first item.
fn write_to_clipboard_inner(item: ClipboardItem) -> Result<()> {
unsafe {
OpenClipboard(None)?;
EmptyClipboard()?;
}
match item.entries().first() {
Some(entry) => match entry {
ClipboardEntry::String(string) => {
write_string_to_clipboard(string)?;
}
ClipboardEntry::Image(image) => {
write_image_to_clipboard(image)?;
}
},
None => {
// Writing an empty list of entries just clears the clipboard.
}
}
Ok(())
}
fn write_string_to_clipboard(item: &ClipboardString) -> Result<()> {
let encode_wide = item.text.encode_utf16().chain(Some(0)).collect_vec();
set_data_to_clipboard(&encode_wide, CF_UNICODETEXT.0 as u32)?;
if let Some(metadata) = item.metadata.as_ref() {
let hash_result = {
let hash = ClipboardString::text_hash(&item.text);
hash.to_ne_bytes()
};
let encode_wide =
unsafe { std::slice::from_raw_parts(hash_result.as_ptr().cast::<u16>(), 4) };
set_data_to_clipboard(encode_wide, *CLIPBOARD_HASH_FORMAT)?;
let metadata_wide = metadata.encode_utf16().chain(Some(0)).collect_vec();
set_data_to_clipboard(&metadata_wide, *CLIPBOARD_METADATA_FORMAT)?;
}
Ok(())
}
fn set_data_to_clipboard<T>(data: &[T], format: u32) -> Result<()> {
unsafe {
let global = GlobalAlloc(GMEM_MOVEABLE, std::mem::size_of_val(data))?;
let handle = GlobalLock(global);
std::ptr::copy_nonoverlapping(data.as_ptr(), handle as _, data.len());
let _ = GlobalUnlock(global);
SetClipboardData(format, HANDLE(global.0))?;
}
Ok(())
}
// Here writing PNG to the clipboard to better support other apps. For more info, please ref to
// the PR.
fn write_image_to_clipboard(item: &Image) -> Result<()> {
match item.format {
ImageFormat::Svg => set_data_to_clipboard(item.bytes(), *CLIPBOARD_SVG_FORMAT)?,
ImageFormat::Gif => {
set_data_to_clipboard(item.bytes(), *CLIPBOARD_GIF_FORMAT)?;
let png_bytes = convert_image_to_png_format(item.bytes(), ImageFormat::Gif)?;
set_data_to_clipboard(&png_bytes, *CLIPBOARD_PNG_FORMAT)?;
}
ImageFormat::Png => {
set_data_to_clipboard(item.bytes(), *CLIPBOARD_PNG_FORMAT)?;
let png_bytes = convert_image_to_png_format(item.bytes(), ImageFormat::Png)?;
set_data_to_clipboard(&png_bytes, *CLIPBOARD_PNG_FORMAT)?;
}
ImageFormat::Jpeg => {
set_data_to_clipboard(item.bytes(), *CLIPBOARD_JPG_FORMAT)?;
let png_bytes = convert_image_to_png_format(item.bytes(), ImageFormat::Jpeg)?;
set_data_to_clipboard(&png_bytes, *CLIPBOARD_PNG_FORMAT)?;
}
other => {
log::warn!(
"Clipboard unsupported image format: {:?}, convert to PNG instead.",
item.format
);
let png_bytes = convert_image_to_png_format(item.bytes(), other)?;
set_data_to_clipboard(&png_bytes, *CLIPBOARD_PNG_FORMAT)?;
}
}
Ok(())
}
fn convert_image_to_png_format(bytes: &[u8], image_format: ImageFormat) -> Result<Vec<u8>> {
let image = image::load_from_memory_with_format(bytes, image_format.into())?;
let mut output_buf = Vec::new();
image.write_to(
&mut std::io::Cursor::new(&mut output_buf),
image::ImageFormat::Png,
)?;
Ok(output_buf)
}
fn read_from_clipboard_inner() -> Option<ClipboardItem> {
unsafe { OpenClipboard(None) }.log_err()?;
with_best_match_format(|item_format| match format_to_type(item_format) {
ClipboardFormatType::Text => read_string_from_clipboard(),
ClipboardFormatType::Image => read_image_from_clipboard(item_format),
ClipboardFormatType::Files => read_files_from_clipboard(),
})
}
// Here, we enumerate all formats on the clipboard and find the first one that we can process.
// The reason we don't use `GetPriorityClipboardFormat` is that it sometimes returns the
// wrong format.
// For instance, when copying a JPEG image from Microsoft Word, there may be several formats
// on the clipboard: Jpeg, Png, Svg.
// If we use `GetPriorityClipboardFormat`, it will return Svg, which is not what we want.
fn with_best_match_format<F>(f: F) -> Option<ClipboardItem>
where
F: Fn(u32) -> Option<ClipboardEntry>,
{
let count = unsafe { CountClipboardFormats() };
let mut clipboard_format = 0;
for _ in 0..count {
clipboard_format = unsafe { EnumClipboardFormats(clipboard_format) };
let Some(item_format) = FORMATS_SET.get(&clipboard_format) else {
continue;
};
if let Some(entry) = f(*item_format) {
return Some(ClipboardItem {
entries: vec![entry],
});
}
}
// log the formats that we don't support yet.
{
clipboard_format = 0;
for _ in 0..count {
clipboard_format = unsafe { EnumClipboardFormats(clipboard_format) };
let mut buffer = [0u16; 64];
unsafe { GetClipboardFormatNameW(clipboard_format, &mut buffer) };
let format_name = String::from_utf16_lossy(&buffer);
log::warn!(
"Try to paste with unsupported clipboard format: {}, {}.",
clipboard_format,
format_name
);
}
}
None
}
fn read_string_from_clipboard() -> Option<ClipboardEntry> {
let text = {
let global = SmartGlobal::from_raw_ptr(
unsafe { GetClipboardData(CF_UNICODETEXT.0 as u32).log_err() }?.0,
);
let text = PCWSTR(global.lock() as *const u16);
String::from_utf16_lossy(unsafe { text.as_wide() })
};
let Some(hash) = read_hash_from_clipboard() else {
return Some(ClipboardEntry::String(ClipboardString::new(text)));
};
let Some(metadata) = read_metadata_from_clipboard() else {
return Some(ClipboardEntry::String(ClipboardString::new(text)));
};
if hash == ClipboardString::text_hash(&text) {
Some(ClipboardEntry::String(ClipboardString {
text,
metadata: Some(metadata),
}))
} else {
Some(ClipboardEntry::String(ClipboardString::new(text)))
}
}
fn read_hash_from_clipboard() -> Option<u64> {
if unsafe { IsClipboardFormatAvailable(*CLIPBOARD_HASH_FORMAT).is_err() } {
return None;
}
let global =
SmartGlobal::from_raw_ptr(unsafe { GetClipboardData(*CLIPBOARD_HASH_FORMAT).log_err() }?.0);
let raw_ptr = global.lock() as *const u16;
let hash_bytes: [u8; 8] = unsafe {
std::slice::from_raw_parts(raw_ptr.cast::<u8>(), 8)
.to_vec()
.try_into()
.log_err()
}?;
Some(u64::from_ne_bytes(hash_bytes))
}
fn read_metadata_from_clipboard() -> Option<String> {
unsafe { IsClipboardFormatAvailable(*CLIPBOARD_METADATA_FORMAT).log_err()? };
let global = SmartGlobal::from_raw_ptr(
unsafe { GetClipboardData(*CLIPBOARD_METADATA_FORMAT).log_err() }?.0,
);
let text = PCWSTR(global.lock() as *const u16);
Some(String::from_utf16_lossy(unsafe { text.as_wide() }))
}
fn read_image_from_clipboard(format: u32) -> Option<ClipboardEntry> {
let image_format = format_number_to_image_format(format)?;
read_image_for_type(format, *image_format)
}
#[inline]
fn format_number_to_image_format(format_number: u32) -> Option<&'static ImageFormat> {
IMAGE_FORMATS_MAP.get(&format_number)
}
fn read_image_for_type(format_number: u32, format: ImageFormat) -> Option<ClipboardEntry> {
let global = SmartGlobal::from_raw_ptr(unsafe { GetClipboardData(format_number).log_err() }?.0);
let image_ptr = global.lock();
let iamge_size = global.size();
let bytes =
unsafe { std::slice::from_raw_parts(image_ptr as *mut u8 as _, iamge_size).to_vec() };
let id = hash(&bytes);
Some(ClipboardEntry::Image(Image { format, bytes, id }))
}
fn read_files_from_clipboard() -> Option<ClipboardEntry> {
let global =
SmartGlobal::from_raw_ptr(unsafe { GetClipboardData(CF_HDROP.0 as u32).log_err() }?.0);
let hdrop = HDROP(global.lock());
let mut filenames = String::new();
with_file_names(hdrop, |file_name| {
filenames.push_str(&file_name);
});
Some(ClipboardEntry::String(ClipboardString {
text: filenames,
metadata: None,
}))
}
impl From<ImageFormat> for image::ImageFormat {
fn from(value: ImageFormat) -> Self {
match value {
ImageFormat::Png => image::ImageFormat::Png,
ImageFormat::Jpeg => image::ImageFormat::Jpeg,
ImageFormat::Webp => image::ImageFormat::WebP,
ImageFormat::Gif => image::ImageFormat::Gif,
// ImageFormat::Svg => todo!(),
ImageFormat::Bmp => image::ImageFormat::Bmp,
ImageFormat::Tiff => image::ImageFormat::Tiff,
_ => unreachable!(),
}
}
}

View File

@@ -17,24 +17,12 @@ use windows::{
core::*,
Win32::{
Foundation::*,
Globalization::u_memcpy,
Graphics::{
Gdi::*,
Imaging::{CLSID_WICImagingFactory, IWICImagingFactory},
},
Security::Credentials::*,
System::{
Com::*,
DataExchange::{
CloseClipboard, EmptyClipboard, GetClipboardData, OpenClipboard,
RegisterClipboardFormatW, SetClipboardData,
},
LibraryLoader::*,
Memory::{GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE},
Ole::*,
SystemInformation::*,
Threading::*,
},
System::{Com::*, LibraryLoader::*, Ole::*, SystemInformation::*, Threading::*},
UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},
},
UI::ViewManagement::UISettings,
@@ -52,8 +40,6 @@ pub(crate) struct WindowsPlatform {
background_executor: BackgroundExecutor,
foreground_executor: ForegroundExecutor,
text_system: Arc<DirectWriteTextSystem>,
clipboard_hash_format: u32,
clipboard_metadata_format: u32,
windows_version: WindowsVersion,
bitmap_factory: ManuallyDrop<IWICImagingFactory>,
validation_number: usize,
@@ -108,9 +94,6 @@ impl WindowsPlatform {
let icon = load_icon().unwrap_or_default();
let state = RefCell::new(WindowsPlatformState::new());
let raw_window_handles = RwLock::new(SmallVec::new());
let clipboard_hash_format = register_clipboard_format(CLIPBOARD_HASH_FORMAT).unwrap();
let clipboard_metadata_format =
register_clipboard_format(CLIPBOARD_METADATA_FORMAT).unwrap();
let windows_version = WindowsVersion::new().expect("Error retrieve windows version");
let validation_number = rand::random::<usize>();
@@ -123,8 +106,6 @@ impl WindowsPlatform {
background_executor,
foreground_executor,
text_system,
clipboard_hash_format,
clipboard_metadata_format,
windows_version,
bitmap_factory,
validation_number,
@@ -487,15 +468,11 @@ impl Platform for WindowsPlatform {
}
fn write_to_clipboard(&self, item: ClipboardItem) {
write_to_clipboard(
item,
self.clipboard_hash_format,
self.clipboard_metadata_format,
);
write_to_clipboard(item);
}
fn read_from_clipboard(&self) -> Option<ClipboardItem> {
read_from_clipboard(self.clipboard_hash_format, self.clipboard_metadata_format)
read_from_clipboard()
}
fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
@@ -664,10 +641,11 @@ fn file_save_dialog(directory: PathBuf) -> Result<Option<PathBuf>> {
let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };
if !directory.to_string_lossy().is_empty() {
if let Some(full_path) = directory.canonicalize().log_err() {
let full_path = full_path.to_string_lossy().to_string();
if !full_path.is_empty() {
let full_path = full_path.to_string_lossy();
let full_path_str = full_path.trim_start_matches("\\\\?\\");
if !full_path_str.is_empty() {
let path_item: IShellItem =
unsafe { SHCreateItemFromParsingName(&HSTRING::from(&full_path), None)? };
unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_str), None)? };
unsafe { dialog.SetFolder(&path_item).log_err() };
}
}
@@ -724,117 +702,6 @@ fn should_auto_hide_scrollbars() -> Result<bool> {
Ok(ui_settings.AutoHideScrollBars()?)
}
fn register_clipboard_format(format: PCWSTR) -> Result<u32> {
let ret = unsafe { RegisterClipboardFormatW(format) };
if ret == 0 {
Err(anyhow::anyhow!(
"Error when registering clipboard format: {}",
std::io::Error::last_os_error()
))
} else {
Ok(ret)
}
}
fn write_to_clipboard(item: ClipboardItem, hash_format: u32, metadata_format: u32) {
write_to_clipboard_inner(item, hash_format, metadata_format).log_err();
unsafe { CloseClipboard().log_err() };
}
fn write_to_clipboard_inner(
item: ClipboardItem,
hash_format: u32,
metadata_format: u32,
) -> Result<()> {
unsafe {
OpenClipboard(None)?;
EmptyClipboard()?;
let encode_wide = item
.text()
.unwrap_or_default()
.encode_utf16()
.chain(Some(0))
.collect_vec();
set_data_to_clipboard(&encode_wide, CF_UNICODETEXT.0 as u32)?;
if let Some((metadata, text)) = item.metadata().zip(item.text()) {
let hash_result = {
let hash = ClipboardString::text_hash(&text);
hash.to_ne_bytes()
};
let encode_wide = std::slice::from_raw_parts(hash_result.as_ptr().cast::<u16>(), 4);
set_data_to_clipboard(encode_wide, hash_format)?;
let metadata_wide = metadata.encode_utf16().chain(Some(0)).collect_vec();
set_data_to_clipboard(&metadata_wide, metadata_format)?;
}
}
Ok(())
}
fn set_data_to_clipboard(data: &[u16], format: u32) -> Result<()> {
unsafe {
let global = GlobalAlloc(GMEM_MOVEABLE, data.len() * 2)?;
let handle = GlobalLock(global);
u_memcpy(handle as _, data.as_ptr(), data.len() as _);
let _ = GlobalUnlock(global);
SetClipboardData(format, HANDLE(global.0))?;
}
Ok(())
}
fn read_from_clipboard(hash_format: u32, metadata_format: u32) -> Option<ClipboardItem> {
let result = read_from_clipboard_inner(hash_format, metadata_format).log_err();
unsafe { CloseClipboard().log_err() };
result
}
fn read_from_clipboard_inner(hash_format: u32, metadata_format: u32) -> Result<ClipboardItem> {
unsafe {
OpenClipboard(None)?;
let text = {
let handle = GetClipboardData(CF_UNICODETEXT.0 as u32)?;
let text = PCWSTR(handle.0 as *const u16);
String::from_utf16_lossy(text.as_wide())
};
let Some(hash) = read_hash_from_clipboard(hash_format) else {
return Ok(ClipboardItem::new_string(text));
};
let Some(metadata) = read_metadata_from_clipboard(metadata_format) else {
return Ok(ClipboardItem::new_string(text));
};
if hash == ClipboardString::text_hash(&text) {
Ok(ClipboardItem::new_string_with_metadata(text, metadata))
} else {
Ok(ClipboardItem::new_string(text))
}
}
}
fn read_hash_from_clipboard(hash_format: u32) -> Option<u64> {
unsafe {
let handle = GetClipboardData(hash_format).log_err()?;
let raw_ptr = handle.0 as *const u16;
let hash_bytes: [u8; 8] = std::slice::from_raw_parts(raw_ptr.cast::<u8>(), 8)
.to_vec()
.try_into()
.log_err()?;
Some(u64::from_ne_bytes(hash_bytes))
}
}
fn read_metadata_from_clipboard(metadata_format: u32) -> Option<String> {
unsafe {
let handle = GetClipboardData(metadata_format).log_err()?;
let text = PCWSTR(handle.0 as *const u16);
Some(String::from_utf16_lossy(text.as_wide()))
}
}
// clipboard
pub const CLIPBOARD_HASH_FORMAT: PCWSTR = windows::core::w!("zed-text-hash");
pub const CLIPBOARD_METADATA_FORMAT: PCWSTR = windows::core::w!("zed-metadata");
#[cfg(test)]
mod tests {
use crate::{ClipboardItem, Platform, WindowsPlatform};

View File

@@ -685,7 +685,7 @@ impl PlatformWindow for WindowsWindow {
Some(self.0.state.borrow().renderer.gpu_specs())
}
fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>) {
// todo(windows)
}
}
@@ -735,23 +735,11 @@ impl IDropTarget_Impl for WindowsDragDropHandler_Impl {
}
let hdrop = idata.u.hGlobal.0 as *mut HDROP;
let mut paths = SmallVec::<[PathBuf; 2]>::new();
let file_count = DragQueryFileW(*hdrop, DRAGDROP_GET_FILES_COUNT, None);
for file_index in 0..file_count {
let filename_length = DragQueryFileW(*hdrop, file_index, None) as usize;
let mut buffer = vec![0u16; filename_length + 1];
let ret = DragQueryFileW(*hdrop, file_index, Some(buffer.as_mut_slice()));
if ret == 0 {
log::error!("unable to read file name");
continue;
with_file_names(*hdrop, |file_name| {
if let Some(path) = PathBuf::from_str(&file_name).log_err() {
paths.push(path);
}
if let Some(file_name) =
String::from_utf16(&buffer[0..filename_length]).log_err()
{
if let Some(path) = PathBuf::from_str(&file_name).log_err() {
paths.push(path);
}
}
}
});
ReleaseStgMedium(&mut idata);
let mut cursor_position = POINT { x: pt.x, y: pt.y };
ScreenToClient(self.0.hwnd, &mut cursor_position)
@@ -1069,9 +1057,6 @@ fn calculate_client_rect(
}
}
// https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-dragqueryfilew
const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
mod windows_renderer {
use std::{num::NonZeroIsize, sync::Arc};

View File

@@ -1,6 +1,11 @@
use std::ops::Deref;
use windows::Win32::{Foundation::HANDLE, UI::WindowsAndMessaging::HCURSOR};
use util::ResultExt;
use windows::Win32::{
Foundation::{HANDLE, HGLOBAL},
System::Memory::{GlobalLock, GlobalSize, GlobalUnlock},
UI::WindowsAndMessaging::HCURSOR,
};
#[derive(Debug, Clone, Copy)]
pub(crate) struct SafeHandle {
@@ -45,3 +50,30 @@ impl Deref for SafeCursor {
&self.raw
}
}
#[derive(Debug, Clone)]
pub(crate) struct SmartGlobal {
raw: HGLOBAL,
}
impl SmartGlobal {
pub(crate) fn from_raw_ptr(ptr: *mut std::ffi::c_void) -> Self {
Self { raw: HGLOBAL(ptr) }
}
pub(crate) fn lock(&self) -> *mut std::ffi::c_void {
unsafe { GlobalLock(self.raw) }
}
pub(crate) fn size(&self) -> usize {
unsafe { GlobalSize(self.raw) }
}
}
impl Drop for SmartGlobal {
fn drop(&mut self) {
unsafe {
GlobalUnlock(self.raw).log_err();
}
}
}

View File

@@ -3610,7 +3610,9 @@ impl<'a> WindowContext<'a> {
self.on_next_frame(|cx| {
if let Some(mut input_handler) = cx.window.platform_window.take_input_handler() {
if let Some(bounds) = input_handler.selected_bounds(cx) {
cx.window.platform_window.update_ime_position(bounds);
cx.window
.platform_window
.update_ime_position(bounds.scale(cx.scale_factor()));
}
cx.window.platform_window.set_input_handler(input_handler);
}

View File

@@ -10,22 +10,46 @@ use futures::future::BoxFuture;
use http::request::Builder;
#[cfg(feature = "test-support")]
use std::fmt;
use std::sync::{Arc, Mutex};
use std::{
sync::{Arc, Mutex},
time::Duration,
};
pub use url::Url;
pub struct ReadTimeout(pub Duration);
#[derive(Default, Debug, Clone)]
pub enum RedirectPolicy {
#[default]
NoFollow,
FollowLimit(u32),
FollowAll,
}
pub struct FollowRedirects(pub bool);
pub trait HttpRequestExt {
/// Set a read timeout on the request.
/// For isahc, this is the low_speed_timeout.
/// For other clients, this is the timeout used for read calls when reading the response.
/// In all cases this prevents servers stalling completely, but allows them to send data slowly.
fn read_timeout(self, timeout: Duration) -> Self;
/// Whether or not to follow redirects
fn follow_redirects(self, follow: RedirectPolicy) -> Self;
}
impl HttpRequestExt for http::request::Builder {
fn read_timeout(self, timeout: Duration) -> Self {
self.extension(ReadTimeout(timeout))
}
fn follow_redirects(self, follow: RedirectPolicy) -> Self {
self.extension(follow)
}
}
pub trait HttpClient: 'static + Send + Sync {
fn send(
&self,
req: http::Request<AsyncBody>,
) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
self.send_with_redirect_policy(req, false)
}
// TODO: Make a better API for this
fn send_with_redirect_policy(
&self,
req: Request<AsyncBody>,
follow_redirects: bool,
) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>>;
fn get<'a>(
@@ -34,14 +58,17 @@ pub trait HttpClient: 'static + Send + Sync {
body: AsyncBody,
follow_redirects: bool,
) -> BoxFuture<'a, Result<Response<AsyncBody>, anyhow::Error>> {
let request = Builder::new().uri(uri).body(body);
let request = Builder::new()
.uri(uri)
.follow_redirects(if follow_redirects {
RedirectPolicy::FollowAll
} else {
RedirectPolicy::NoFollow
})
.body(body);
match request {
Ok(request) => Box::pin(async move {
self.send_with_redirect_policy(request, follow_redirects)
.await
.map_err(Into::into)
}),
Ok(request) => Box::pin(async move { self.send(request).await.map_err(Into::into) }),
Err(e) => Box::pin(async move { Err(e.into()) }),
}
}
@@ -92,12 +119,11 @@ impl HttpClientWithProxy {
}
impl HttpClient for HttpClientWithProxy {
fn send_with_redirect_policy(
fn send(
&self,
req: Request<AsyncBody>,
follow_redirects: bool,
) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
self.client.send_with_redirect_policy(req, follow_redirects)
self.client.send(req)
}
fn proxy(&self) -> Option<&Uri> {
@@ -106,12 +132,11 @@ impl HttpClient for HttpClientWithProxy {
}
impl HttpClient for Arc<HttpClientWithProxy> {
fn send_with_redirect_policy(
fn send(
&self,
req: Request<AsyncBody>,
follow_redirects: bool,
) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
self.client.send_with_redirect_policy(req, follow_redirects)
self.client.send(req)
}
fn proxy(&self) -> Option<&Uri> {
@@ -218,12 +243,11 @@ impl HttpClientWithUrl {
}
impl HttpClient for Arc<HttpClientWithUrl> {
fn send_with_redirect_policy(
fn send(
&self,
req: Request<AsyncBody>,
follow_redirects: bool,
) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
self.client.send_with_redirect_policy(req, follow_redirects)
self.client.send(req)
}
fn proxy(&self) -> Option<&Uri> {
@@ -232,12 +256,11 @@ impl HttpClient for Arc<HttpClientWithUrl> {
}
impl HttpClient for HttpClientWithUrl {
fn send_with_redirect_policy(
fn send(
&self,
req: Request<AsyncBody>,
follow_redirects: bool,
) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
self.client.send_with_redirect_policy(req, follow_redirects)
self.client.send(req)
}
fn proxy(&self) -> Option<&Uri> {
@@ -283,14 +306,6 @@ impl HttpClient for BlockedHttpClient {
fn proxy(&self) -> Option<&Uri> {
None
}
fn send_with_redirect_policy(
&self,
req: Request<AsyncBody>,
_: bool,
) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
self.send(req)
}
}
#[cfg(feature = "test-support")]
@@ -352,10 +367,9 @@ impl fmt::Debug for FakeHttpClient {
#[cfg(feature = "test-support")]
impl HttpClient for FakeHttpClient {
fn send_with_redirect_policy(
fn send(
&self,
req: Request<AsyncBody>,
_follow_redirects: bool,
) -> BoxFuture<'static, Result<Response<AsyncBody>, anyhow::Error>> {
let future = (self.handler)(req);
future

View File

@@ -1,7 +1,6 @@
use std::{mem, sync::Arc, time::Duration};
use futures::future::BoxFuture;
use isahc::config::RedirectPolicy;
use util::maybe;
pub use isahc::config::Configurable;
@@ -9,13 +8,10 @@ pub struct IsahcHttpClient(isahc::HttpClient);
pub use http_client::*;
const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(60);
impl IsahcHttpClient {
pub fn new(proxy: Option<Uri>, user_agent: Option<String>) -> Arc<IsahcHttpClient> {
let mut builder = isahc::HttpClient::builder()
.connect_timeout(Duration::from_secs(5))
.timeout(DEFAULT_HTTP_TIMEOUT)
.low_speed_timeout(100, Duration::from_secs(5))
.proxy(proxy.clone());
if let Some(agent) = user_agent {
@@ -39,18 +35,29 @@ impl HttpClient for IsahcHttpClient {
None
}
fn send_with_redirect_policy(
fn send(
&self,
req: http_client::http::Request<http_client::AsyncBody>,
follow_redirects: bool,
) -> BoxFuture<'static, Result<http_client::Response<http_client::AsyncBody>, anyhow::Error>>
{
let redirect_policy = req
.extensions()
.get::<http_client::RedirectPolicy>()
.cloned()
.unwrap_or_default();
let read_timeout = req
.extensions()
.get::<http_client::ReadTimeout>()
.map(|t| t.0);
let req = maybe!({
let (mut parts, body) = req.into_parts();
let mut builder = isahc::Request::builder()
.method(parts.method)
.uri(parts.uri)
.version(parts.version);
if let Some(read_timeout) = read_timeout {
builder = builder.low_speed_timeout(100, read_timeout);
}
let headers = builder.headers_mut()?;
mem::swap(headers, &mut parts.headers);
@@ -67,10 +74,12 @@ impl HttpClient for IsahcHttpClient {
};
builder
.redirect_policy(if follow_redirects {
RedirectPolicy::Follow
} else {
RedirectPolicy::None
.redirect_policy(match redirect_policy {
http_client::RedirectPolicy::FollowAll => isahc::config::RedirectPolicy::Follow,
http_client::RedirectPolicy::FollowLimit(limit) => {
isahc::config::RedirectPolicy::Limit(limit)
}
http_client::RedirectPolicy::NoFollow => isahc::config::RedirectPolicy::None,
})
.body(isahc_body)
.ok()

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